帮我写一个python的贪吃蛇脚本
时间: 2024-01-06 19:03:21 浏览: 136
python编写的贪吃蛇
5星 · 资源好评率100%
好的,以下是一个简单的 Python 贪吃蛇脚本:
```python
import pygame
import random
pygame.init()
# 游戏窗口尺寸
width = 500
height = 500
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 创建窗口
game_display = pygame.display.set_mode((width, height))
pygame.display.set_caption('贪吃蛇')
# 定义游戏时钟
clock = pygame.time.Clock()
# 定义贪吃蛇快照列表和初始位置
snake_size = 10
snake_speed = 15
snake_list = []
snake_head = [width / 2, height / 2]
snake_list.append(snake_head)
# 定义食物位置
food_x = round(random.randrange(0, width - snake_size) / 10) * 10
food_y = round(random.randrange(0, height - snake_size) / 10) * 10
# 绘制方块图形函数
def draw_block(surface, color, position):
block = pygame.Rect((position[0], position[1]), (snake_size, snake_size))
pygame.draw.rect(surface, color, block)
# 游戏主循环
game_exit = False
while not game_exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
# 按键操作
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
snake_head[0] -= snake_size
if keys[pygame.K_RIGHT]:
snake_head[0] += snake_size
if keys[pygame.K_UP]:
snake_head[1] -= snake_size
if keys[pygame.K_DOWN]:
snake_head[1] += snake_size
# 更新位置
snake_head = snake_list[-1].copy()
snake_head[0] += snake_size
snake_list.append(snake_head)
if snake_head[0] == food_x and snake_head[1] == food_y:
food_x = round(random.randrange(0, width - snake_size) / 10) * 10
food_y = round(random.randrange(0, height - snake_size) / 10) * 10
else:
snake_list.pop(0)
# 绘制游戏界面
game_display.fill(white)
draw_block(game_display, red, [food_x, food_y])
for position in snake_list:
draw_block(game_display, black, position)
pygame.display.update()
# 设置游戏时钟
clock.tick(snake_speed)
# 退出游戏
pygame.quit()
quit()
```
希望这个脚本可以帮到你!
阅读全文