写一份贪吃蛇的Python代码
时间: 2024-06-14 20:01:56 浏览: 58
当然可以,编写一个简单的贪吃蛇游戏的Python代码通常会涉及到基本的图形用户界面(GUI)、游戏循环、键盘监听以及蛇和食物的移动。以下是一个基本的框架示例:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置窗口尺寸和标题
screen_width = 600
screen_height = 600
window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
# 蛇的初始设置
snake_speed = 15
snake_pos = [(100, 100), (90, 100), (80, 100)] # 起始位置和头部
snake_direction = "right" # 向右
# 食物的随机生成
food_pos = [random.randint(0, screen_width-10), random.randint(0, screen_height-10)]
food_spawn = True
# 游戏主循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif 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"
# 更新蛇的位置
new_head = list(snake_pos[-1])
if snake_direction == "up":
new_head -= snake_speed
elif snake_direction == "down":
new_head += snake_speed
elif snake_direction == "left":
new_head -= snake_speed
elif snake_direction == "right":
new_head += snake_speed
# 检查边界和碰撞
if new_head in snake_pos[:-1] or new_head == food_pos:
running = False
else:
snake_pos.insert(0, new_head)
# 移动食物
if food_spawn:
food_pos = [random.randint(0, screen_width-10), random.randint(0, screen_height-10)]
else:
food_pos = snake_pos[0] + snake_speed
food_pos = snake_pos
# 绘制
window.fill(black)
for pos in snake_pos:
pygame.draw.rect(window, white, pygame.Rect(pos, pos, 10, 10))
pygame.draw.rect(window, red, pygame.Rect(food_pos, food_pos, 10, 10))
# 更新屏幕
pygame.display.flip()
# 结束游戏
pygame.quit()
```
阅读全文