用Python写一个贪吃蛇小游戏,请给出代码
时间: 2024-05-09 12:21:01 浏览: 134
以下是一个简单的贪吃蛇小游戏的 Python 代码:
```
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置游戏窗口大小和标题
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Snake Game")
# 设置颜色
white = (255, 255, 255)
black = (0, 0, 0)
green = (0, 255, 0)
red = (255, 0, 0)
# 设置字体
font = pygame.font.SysFont(None, 25)
# 设置蛇的初始位置和大小
snake_block_size = 10
snake_list = []
snake_length = 1
snake_head_x = window_width / 2
snake_head_y = window_height / 2
snake_x_change = 0
snake_y_change = 0
# 设置食物的初始位置和大小
food_block_size = 10
food_x = round(random.randrange(0, window_width - food_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - food_block_size) / 10.0) * 10.0
# 设置游戏结束的变量
game_over = False
# 定义函数:显示分数
def show_score(score):
score_text = font.render("Score: " + str(score), True, white)
window.blit(score_text, [0, 0])
# 定义函数:显示蛇
def draw_snake(snake_block_size, snake_list):
for x in snake_list:
pygame.draw.rect(window, green, [x[0], x[1], snake_block_size, snake_block_size])
# 游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snake_x_change = -snake_block_size
snake_y_change = 0
elif event.key == pygame.K_RIGHT:
snake_x_change = snake_block_size
snake_y_change = 0
elif event.key == pygame.K_UP:
snake_y_change = -snake_block_size
snake_x_change = 0
elif event.key == pygame.K_DOWN:
snake_y_change = snake_block_size
snake_x_change = 0
# 移动蛇的位置
snake_head_x += snake_x_change
snake_head_y += snake_y_change
# 如果蛇吃到了食物,增加分数,重新生成食物,增加蛇的长度
if snake_head_x == food_x and snake_head_y == food_y:
food_x = round(random.randrange(0, window_width - food_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - food_block_size) / 10.0) * 10.0
snake_length += 1
# 添加蛇头的位置到蛇的列表中
snake_head = []
snake_head.append(snake_head_x)
snake_head.append(snake_head_y)
snake_list.append(snake_head)
# 如果蛇的长度大于最大长度,删除蛇尾的位置
if len(snake_list) > snake_length:
del snake_list[0]
# 如果蛇的头部撞到了边界,游戏结束
if snake_head_x >= window_width or snake_head_x < 0 or snake_head_y >= window_height or snake_head_y < 0:
game_over = True
# 如果蛇的头部撞到了蛇的身体,游戏结束
for x in snake_list[:-1]:
if x == snake_head:
game_over = True
# 清空窗口
window.fill(black)
# 绘制食物
pygame.draw.rect(window, red, [food_x, food_y, food_block_size, food_block_size])
# 绘制蛇
draw_snake(snake_block_size, snake_list)
# 显示分数
show_score(snake_length - 1)
# 刷新窗口
pygame.display.update()
# 退出 Pygame
pygame.quit()
```
这个代码使用 Pygame 库创建了一个游戏窗口,并在其中实现了贪吃蛇的基本逻辑。运行代码即可开始游戏。
阅读全文