写一个python贪吃蛇游戏
时间: 2023-05-17 08:06:19 浏览: 109
Python编写一个贪吃蛇游戏
非常感谢您的提问,我可以为您提供一个基本的 Python 贪吃蛇游戏代码,如下所示:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 定义游戏窗口的大小
window_width = 500
window_height = 500
# 创建游戏窗口
game_window = pygame.display.set_mode((window_width, window_height))
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义贪吃蛇的初始位置和大小
snake_block_size = 10
snake_list = []
snake_length = 1
snake_x = window_width / 2
snake_y = window_height / 2
# 定义食物的初始位置和大小
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
# 定义贪吃蛇的移动速度
snake_speed = 15
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 定义游戏结束的函数
def game_over():
message = font_style.render("Game Over!", True, red)
game_window.blit(message, [window_width / 2, window_height / 2])
pygame.display.update()
pygame.time.delay(2000)
# 游戏循环
game_over_flag = False
while not game_over_flag:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over_flag = True
# 获取键盘输入
keys = pygame.key.get_pressed()
# 根据键盘输入移动贪吃蛇
if keys[pygame.K_LEFT]:
snake_x -= snake_block_size
elif keys[pygame.K_RIGHT]:
snake_x += snake_block_size
elif keys[pygame.K_UP]:
snake_y -= snake_block_size
elif keys[pygame.K_DOWN]:
snake_y += snake_block_size
# 绘制贪吃蛇和食物
game_window.fill(white)
pygame.draw.rect(game_window, black, [snake_x, snake_y, snake_block_size, snake_block_size])
pygame.draw.rect(game_window, red, [food_x, food_y, food_block_size, food_block_size])
# 更新贪吃蛇的位置
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
# 检查贪吃蛇是否吃到了食物
for block in snake_list[:-1]:
if block == snake_head:
game_over_flag = True
if snake_x == food_x and snake_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
# 检查贪吃蛇是否撞墙
if snake_x < 0 or snake_x >= window_width or snake_y < 0 or snake_y >= window_height:
game_over_flag = True
# 更新游戏窗口
pygame.display.update()
# 控制游戏速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 游戏结束
game_over()
pygame.quit()
```
希望这个代码能够帮助到您!
阅读全文