首页 > 编程语言 >python实现打砖块小游戏

python实现打砖块小游戏

时间:2023-11-01 19:06:14浏览次数:27  
标签:ball python self 小游戏 pygame 砖块 brick speed screen


import pygame
import sys
import random

# 初始化pygame
pygame.init()

# 设置屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置颜色
white = (255, 255, 255)
black = (0, 0, 0)

# 设置球和砖块的属性
ball_radius = 10
ball_speed = [2, 2]
brick_width = 80
brick_height = 30
brick_rows = 5
brick_cols = 10
brick_padding = 10
brick_color = (144, 238, 144)

# 创建球和砖块的类
class Ball:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.speed = ball_speed

    def move(self):
        self.x += self.speed[0]
        self.y += self.speed[1]

    def draw(self):
        pygame.draw.circle(screen, white, (self.x, self.y), ball_radius)

class Brick:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.width = brick_width
        self.height = brick_height
        self.color = brick_color

    def draw(self):
        pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))

# 创建球和砖块的对象
ball = Ball(screen_width // 2, screen_height // 2)
bricks = []
for i in range(brick_rows):
    for j in range(brick_cols):
        bricks.append(Brick(j * (brick_width + brick_padding) + brick_padding, i * (brick_height + brick_padding) + brick_padding))

# 游戏主循环
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # 更新球的位置
    ball.move()

    # 检测球是否碰到边界或砖块
    if ball.x - ball_radius <= 0 or ball.x + ball_radius >= screen_width:
        ball.speed[0] = -ball.speed[0]
    if ball.y - ball_radius <= 0:
        ball.speed[1] = -ball.speed[1]
    for brick in bricks:
        if (ball.x - ball_radius <= brick.x + brick.width and ball.x + ball_radius >= brick.x) and (ball.y - ball_radius <= brick.y + brick.height and ball.y + ball_radius >= brick.y):
            ball.speed[1] = -ball.speed[1]
            bricks.remove(brick)
            break

    # 清空屏幕并绘制球和砖块
    screen.fill(black)
    ball.draw()
    for brick in bricks:
        brick.draw()

    # 更新屏幕显示
    pygame.display.flip()

请确保已经安装了pygame库,如果没有安装,可以使用以下命令安装:

pip install pygame

将以上代码保存为一个.py文件,然后运行它。你将看到一个简单的打砖块游戏。

标签:ball,python,self,小游戏,pygame,砖块,brick,speed,screen
From: https://blog.51cto.com/u_16318042/8130967

相关文章

  • Python selenium Chrome下载文件并设置下载路径
    PythonseleniumChrome下载文件并设置下载路径具体代码如下:importosimporttimefromtimeimportsleepfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydown_path="D:\\Temp"chrome_options=webdriver.ChromeOptions()diy_prefs={......
  • Python:报错——ModuleNotFoundError: No module named 'encodings'
    运行Python报错:FatalPythonerror:Py_Initialize:unabletoloadthefilesystemcodecModuleNotFoundError:Nomodulenamed'encodings' 处理步骤:1.Files>>>Setting>>>Project>>>PythonInterpreter >>>AddInterpret......
  • 在简单的python程序中直接使用sqlalchemy
    database.pyfromsqlalchemyimportInteger,String,Columnfromsqlalchemy.ext.declarativeimportdeclarative_baseBase=declarative_base()classUsers(Base):__tablename__="users"id=Column(Integer,primary_key=True)name=......
  • 创建一个Web服务器并保持其运行,可以使用Python的Flask库。以下是一个基本的示例: ```p
    创建一个Web服务器并保持其运行,可以使用Python的Flask库。以下是一个基本的示例:```pythonfromflaskimportFlask,requestimportosapp=Flask(__name__)@app.route('/webhook',methods=['POST'])defwebhook():  data=request.get_json()  #在这里添加你的......
  • Python使用selenium的Chrome下载文件报错解决
    Python使用selenium的Chrome下载文件报错:失败下载错误。网络不稳定也会引发该错误。咱们这里是因为路径多个反斜杠造成的。 下图是报错内容运行日志:路径代码:base_url="https://www.2ppt.com/"#采集的网址ASP.NET电子商务源码save_path="E:\\Spider\\PPT\\"去掉SaveP......
  • 如何安装Python3.8版本的TensorFlow?
    condainstallkeras 现在tensorflow2.4支持3.63.73.8可以放心安装pipinstalltensorflowDownloadinghttps://mirrors.aliyun.com/pypi/packages/59/9b/tensorflow-2.5.0-cp38-cp38-manylinux2010_x86_64.whl(454.4MB)升级的话可以加个--upgradepipinstalltensorf......
  • Python中的字典的循环和嵌套
     字典进阶操作--循环和嵌套dic={"赵四":"特别能歪嘴","刘能":"老,老四啊...","大脚":"跟这个和那个搞对象","大脑袋":"瞎折腾....",}1.可以用for循环,直接拿到keyforkeyindic:print(key,dic[key])......
  • Python eval的用法及注意事项
    eval是Python的一个内置函数,这个函数的作用是,返回传入字符串的表达式的结果。想象一下变量赋值时,将等号右边的表达式写成字符串的格式,将这个字符串作为eval的参数,eval的返回值就是这个表达式的结果。python中eval函数的用法十分的灵活,但也十分危险,安全性是其最大的缺点。本文从灵活......
  • python 模块导入赋值给变量
    一、假设有一个dangerous_code.py文件。二、导入模块赋值给变量dangerous_module=__import__('dangerous_code')三、执行模块中的delete_all函数(方法)删除内容danderous_module.delete_all()免责声明:本号所涉及内容仅供安全研究与教学使用,如出现其他风险,后果......
  • 《最新出炉》系列初窥篇-Python+Playwright自动化测试-24-处理单选和多选按钮-上篇
    1.简介在工作和生活中,经常会遇到我们需要进行选择的情况,比如勾选我们选择性别,男女两个性别总是不能同时选中的,再比如我们在选择兴趣爱好时,我们可以选择多个自己感兴趣的话题,比如:篮球、足球、电竞等话题。我们在执行自动化测试的过程中,必须要学会处理这样的情况。在实际自动化测试......