做一个简单的贪吃蛇游戏python程序
时间: 2024-03-18 09:20:41 浏览: 51
以下是一个简单的贪吃蛇游戏Python程序,使用Pygame库实现:
```python
import pygame
import random
pygame.init()
# 游戏窗口尺寸
window_width = 640
window_height = 480
# 贪吃蛇大小
snake_size = 20
# 创建游戏窗口
game_window = pygame.display.set_mode((window_width, window_height))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇游戏")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 设置游戏字体
font = pygame.font.SysFont(None, 24)
# 定义贪吃蛇方向
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
# 初始化贪吃蛇位置和方向
snake_x = window_width / 2
snake_y = window_height / 2
snake_direction = RIGHT
# 定义食物位置
food_x = round(random.randrange(0, window_width - snake_size) / snake_size) * snake_size
food_y = round(random.randrange(0, window_height - snake_size) / snake_size) * snake_size
# 定义贪吃蛇身体列表
snake_body = []
snake_length = 1
# 游戏循环
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_UP and snake_direction != DOWN:
snake_direction = UP
elif event.key == pygame.K_DOWN and snake_direction != UP:
snake_direction = DOWN
elif event.key == pygame.K_LEFT and snake_direction != RIGHT:
snake_direction = LEFT
elif event.key == pygame.K_RIGHT and snake_direction != LEFT:
snake_direction = RIGHT
# 移动贪吃蛇
if snake_direction == UP:
snake_y -= snake_size
elif snake_direction == DOWN:
snake_y += snake_size
elif snake_direction == LEFT:
snake_x -= snake_size
elif snake_direction == RIGHT:
snake_x += snake_size
# 判断是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, window_width - snake_size) / snake_size) * snake_size
food_y = round(random.randrange(0, window_height - snake_size) / snake_size) * snake_size
snake_length += 1
# 绘制游戏背景
game_window.fill(white)
# 绘制食物和贪吃蛇
pygame.draw.rect(game_window, red, [food_x, food_y, snake_size, snake_size])
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_body.append(snake_head)
if len(snake_body) > snake_length:
del snake_body[0]
for segment in snake_body[:-1]:
if segment == snake_head:
pygame.quit()
quit()
for segment in snake_body:
pygame.draw.rect(game_window, green, [segment[0], segment[1], snake_size, snake_size])
# 绘制游戏得分
score_text = font.render("得分:" + str(snake_length - 1), True, black)
game_window.blit(score_text, [10, 10])
# 更新游戏窗口
pygame.display.update()
# 控制游戏帧率
pygame.time.Clock().tick(10)
```
程序运行后,可以使用方向键控制贪吃蛇的移动,吃到食物后贪吃蛇长度加1,如果贪吃蛇撞到墙或撞到自己,则游戏结束。程序还会显示当前得分。
阅读全文