写一个py贪吃蛇代码
时间: 2024-10-03 13:01:20 浏览: 34
编写一个简单的Python贪吃蛇游戏需要一些基本的图形库,比如`pygame`。以下是一个非常基础的版本,包含了游戏的基本框架:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置窗口大小
window_width = 400
window_height = 600
win = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("贪吃蛇")
snake_speed = 15
snake_direction = "right"
# 蛇的位置和长度
snake_pos = [[100, 100], [90, 100], [80, 100]]
snake_body = pygame.Surface((10, 10)) # 单元格尺寸
snake_color = (0, 255, 0) # 绿色
food_pos = [random.randint(0, window_width - 10), random.randint(0, window_height - 10)]
food = pygame.Rect(food_pos[0] * 10, food_pos[1] * 10, 10, 10)
food_color = (255, 0, 0) # 红色
def move_snake():
global snake_direction
if snake_direction == "up":
snake_pos.insert(0, [snake_pos[0][0], snake_pos[0][1] - 10])
elif snake_direction == "down":
snake_pos.insert(0, [snake_pos[0][0], snake_pos[0][1] + 10])
elif snake_direction == "left":
snake_pos.insert(0, [snake_pos[0][0] - 10, snake_pos[0][1]])
else: # right
snake_pos.insert(0, [snake_pos[0][0] + 10, snake_pos[0][1]])
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"
# 清除屏幕
win.fill((0, 0, 0))
# 移动并绘制蛇
move_snake()
for pos in snake_pos[:-1]:
win.blit(snake_body, pos)
# 判断蛇是否吃到食物
if snake_pos[0] == food_pos:
food_pos = [random.randint(0, window_width - 10), random.randint(0, window_height - 10)]
snake_body.fill(snake_color)
snake_len += 1
else:
snake_pos.pop()
# 绘制食物
win.blit(food, food_pos)
# 更新屏幕
pygame.display.update()
# 游戏结束
pygame.quit()
```
这个代码只是一个起点,如果你想让游戏更复杂,可以添加边界检查、碰撞检测、得分系统等功能。同时,为了提高可读性和维护性,建议将游戏逻辑拆分成单独的函数。
阅读全文