pygame小游戏代码完整版
时间: 2023-08-01 17:09:24 浏览: 149
当然,我可以为你提供一个简单的 Pygame 小游戏代码示例。以下是一个简单的打砖块游戏的完整代码:
```python
import pygame
import random
# 游戏窗口大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# 砖块大小
BRICK_WIDTH = 80
BRICK_HEIGHT = 20
# 球的半径和速度
BALL_RADIUS = 10
BALL_SPEED_X = 3
BALL_SPEED_Y = 3
# 挡板大小和速度
PADDLE_WIDTH = 100
PADDLE_HEIGHT = 10
PADDLE_SPEED = 5
# 颜色定义
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
# 初始化 Pygame
pygame.init()
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("打砖块游戏")
clock = pygame.time.Clock()
# 定义砖块类
class Brick(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface([BRICK_WIDTH, BRICK_HEIGHT])
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# 定义球类
class Ball(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([BALL_RADIUS * 2, BALL_RADIUS * 2])
self.image.fill(BLUE)
self.rect = self.image.get_rect()
self.rect.x = WINDOW_WIDTH // 2
self.rect.y = WINDOW_HEIGHT // 2
self.speed_x = BALL_SPEED_X
self.speed_y = BALL_SPEED_Y
def update(self):
self.rect.x += self.speed_x
self.rect.y += self.speed_y
# 碰到边界反弹
if self.rect.x <= 0 or self.rect.x >= WINDOW_WIDTH - BALL_RADIUS * 2:
self.speed_x = -self.speed_x
if self.rect.y <= 0:
self.speed_y = -self.speed_y
# 碰到挡板反弹
if pygame.sprite.collide_rect(self, paddle):
self.speed_y = -self.speed_y
# 碰到砖块反弹
brick_collision = pygame.sprite.spritecollide(self, bricks_group, True)
if brick_collision:
self.speed_y = -self.speed_y
# 定义挡板类
class Paddle(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([PADDLE_WIDTH, PADDLE_HEIGHT])
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.x = (WINDOW_WIDTH - PADDLE_WIDTH) // 2
self.rect.y = WINDOW_HEIGHT - PADDLE_HEIGHT
def update(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.rect.x -= PADDLE_SPEED
if keys[pygame.K_RIGHT]:
self.rect.x += PADDLE_SPEED
# 限制挡板移动范围
if self.rect.x < 0:
self.rect.x = 0
elif self.rect.x > WINDOW_WIDTH - PADDLE_WIDTH:
self.rect.x = WINDOW_WIDTH - PADDLE_WIDTH
# 创建砖块组
bricks_group = pygame.sprite.Group()
# 创建砖块
for i in range(10):
for j in range(5):
brick = Brick(i * (BRICK_WIDTH + 2), j * (BRICK_HEIGHT + 2))
bricks_group.add(brick)
# 创建球和挡板
ball = Ball()
paddle = Paddle()
# 创建精灵组
all_sprites_group = pygame.sprite.Group()
all_sprites_group.add(ball, paddle, bricks_group)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
all_sprites_group.update()
window.fill(WHITE)
all_sprites_group.draw(window)
pygame.display.flip()
clock.tick(60)
pygame.quit()
```
这个示例是一个简单的打砖块游戏,包括球、挡板和砖块。你可以根据需要进行修改和扩展。希望对你有所帮助!
阅读全文