python实现打砖块小游戏
  pAgaEjJpCfYa 2023年11月14日 32 0


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文件,然后运行它。你将看到一个简单的打砖块游戏。

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

pAgaEjJpCfYa