用pygame做一个简单小游戏
时间: 2024-01-21 12:03:48 浏览: 177
好的,下面是一个用pygame制作的简单小游戏示例:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口的大小
screen_width = 400
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏标题
pygame.display.set_caption("小游戏")
# 设置游戏背景颜色
background_color = (255, 255, 255)
# 设置游戏结束的标志
game_over = False
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义玩家的位置和大小
player_size = 50
player_x = screen_width / 2 - player_size / 2
player_y = screen_height - player_size - 10
# 定义敌人的位置和大小
enemy_size = 50
enemy_x = random.randint(0, screen_width - enemy_size)
enemy_y = 0
enemy_speed = 10
# 定义得分
score = 0
font = pygame.font.SysFont(None, 25)
# 游戏循环
while not game_over:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 获取键盘按键状态
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_x > 0:
player_x -= 5
elif keys[pygame.K_RIGHT] and player_x < screen_width - player_size:
player_x += 5
# 移动敌人
enemy_y += enemy_speed
if enemy_y > screen_height:
enemy_x = random.randint(0, screen_width - enemy_size)
enemy_y = 0
score += 10
enemy_speed += 1
# 判断是否碰撞
if (enemy_x >= player_x and enemy_x < player_x + player_size) or (player_x >= enemy_x and player_x < enemy_x + enemy_size):
if (enemy_y >= player_y and enemy_y < player_y + player_size) or (player_y >= enemy_y and player_y < enemy_y + enemy_size):
game_over = True
# 绘制游戏界面
screen.fill(background_color)
pygame.draw.rect(screen, (255, 0, 0), (enemy_x, enemy_y, enemy_size, enemy_size))
pygame.draw.rect(screen, (0, 0, 255), (player_x, player_y, player_size, player_size))
# 绘制得分
text = font.render("得分: " + str(score), True, (0, 0, 0))
screen.blit(text, (10, 10))
# 更新游戏显示
pygame.display.update()
# 控制游戏帧率
clock.tick(30)
# 退出游戏
pygame.quit()
```
这个小游戏的规则很简单,玩家需要控制一个方块躲避从屏幕上方下落的另一个方块,同时获得尽可能高的得分。玩家可以使用左右箭头键来移动自己的方块。如果玩家的方块与下落的方块相撞,游戏结束。
阅读全文