帮我用python写一个贪吃蛇
时间: 2023-03-27 14:00:37 浏览: 63
如何用Python写一个贪吃蛇AI.docx
很高兴回答您的问题。以下是一个简单的贪吃蛇游戏的 Python 代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置游戏窗口大小
window_width = 500
window_height = 500
window = pygame.display.set_mode((window_width, window_height))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇游戏")
# 定义颜色
white = (255, 255, 255)
black = (, , )
red = (255, , )
# 定义贪吃蛇的初始位置和大小
snake_block_size = 10
snake_speed = 15
snake_list = []
snake_length = 1
snake_x = window_width / 2
snake_y = window_height / 2
# 定义食物的初始位置和大小
food_block_size = 10
food_x = round(random.randrange(, window_width - food_block_size) / 10.) * 10.
food_y = round(random.randrange(, window_height - food_block_size) / 10.) * 10.
# 定义函数,用于显示贪吃蛇和食物
def draw_snake(snake_block_size, snake_list):
for x in snake_list:
pygame.draw.rect(window, black, [x[], x[1], snake_block_size, snake_block_size])
def draw_food(food_block_size, food_x, food_y):
pygame.draw.rect(window, red, [food_x, food_y, food_block_size, food_block_size])
# 游戏循环
game_over = False
clock = pygame.time.Clock()
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]:
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
# 判断贪吃蛇是否吃到了食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(, window_width - food_block_size) / 10.) * 10.
food_y = round(random.randrange(, window_height - food_block_size) / 10.) * 10.
snake_length += 1
# 更新贪吃蛇的位置
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[]
# 判断贪吃蛇是否碰到了边界或自己的身体
for x in snake_list[:-1]:
if x == snake_head:
game_over = True
if snake_x < or snake_x >= window_width or snake_y < or snake_y >= window_height:
game_over = True
# 绘制游戏界面
window.fill(white)
draw_snake(snake_block_size, snake_list)
draw_food(food_block_size, food_x, food_y)
pygame.display.update()
# 控制游戏帧率
clock.tick(snake_speed)
# 退出 Pygame
pygame.quit()
```
希望这个代码能够帮助您完成贪吃蛇游戏的编写。
阅读全文