基于pygame python的小游戏
时间: 2023-09-21 12:02:52 浏览: 96
好的,我可以提供一个简单的基于pygame的小游戏示例,这个游戏叫做“贪吃蛇”。
首先,我们需要安装pygame模块,可以使用以下命令安装:
```
pip install pygame
```
接下来,我们创建一个Python文件,例如“snake_game.py”,并将以下代码复制到文件中:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置屏幕尺寸
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
BLOCK_SIZE = 20
# 创建屏幕对象
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# 设置窗口标题
pygame.display.set_caption("Snake Game")
# 定义蛇的初始位置
snake_x = SCREEN_WIDTH / 2
snake_y = SCREEN_HEIGHT / 2
# 定义蛇的初始移动方向
snake_dx = BLOCK_SIZE
snake_dy = 0
# 定义食物的初始位置
food_x = round(random.randrange(0, SCREEN_WIDTH - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
food_y = round(random.randrange(0, SCREEN_HEIGHT - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
# 定义蛇的初始长度和身体位置列表
snake_length = 1
snake_body = [(snake_x, snake_y)]
# 创建时钟对象
clock = pygame.time.Clock()
# 定义游戏结束函数
def game_over():
font = pygame.font.SysFont(None, 60)
text = font.render("Game Over", True, RED)
screen.blit(text, (SCREEN_WIDTH / 2 - text.get_width() / 2, SCREEN_HEIGHT / 2 - text.get_height() / 2))
pygame.display.update()
pygame.time.wait(2000)
pygame.quit()
quit()
# 游戏循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# 处理键盘事件
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snake_dx = -BLOCK_SIZE
snake_dy = 0
elif event.key == pygame.K_RIGHT:
snake_dx = BLOCK_SIZE
snake_dy = 0
elif event.key == pygame.K_UP:
snake_dy = -BLOCK_SIZE
snake_dx = 0
elif event.key == pygame.K_DOWN:
snake_dy = BLOCK_SIZE
snake_dx = 0
# 移动蛇
snake_x += snake_dx
snake_y += snake_dy
# 判断是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, SCREEN_WIDTH - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
food_y = round(random.randrange(0, SCREEN_HEIGHT - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
snake_length += 1
# 更新蛇的身体位置列表
snake_body.insert(0, (snake_x, snake_y))
if len(snake_body) > snake_length:
snake_body.pop()
# 检查是否碰到边界或自身
if snake_x < 0 or snake_x > SCREEN_WIDTH - BLOCK_SIZE or snake_y < 0 or snake_y > SCREEN_HEIGHT - BLOCK_SIZE:
game_over()
for body_part in snake_body[1:]:
if body_part == (snake_x, snake_y):
game_over()
# 绘制屏幕
screen.fill(BLACK)
pygame.draw.rect(screen, GREEN, [food_x, food_y, BLOCK_SIZE, BLOCK_SIZE])
for body_part in snake_body:
pygame.draw.rect(screen, WHITE, [body_part[0], body_part[1], BLOCK_SIZE, BLOCK_SIZE])
pygame.display.update()
# 设置游戏帧率
clock.tick(10)
```
运行这个Python文件,将会在屏幕上看到一个贪吃蛇游戏窗口。使用键盘的方向键来控制蛇的运动,吃到食物会增加蛇的长度。如果蛇碰到边界或自身,游戏将结束并显示“Game Over”字样。
希望这个示例能够帮助你开始使用pygame开发小游戏!
阅读全文