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