编写Python贪吃蛇代码
时间: 2023-11-05 17:20:05 浏览: 52
当然可以!下面是一个简单的Python贪吃蛇游戏代码示例:
```python
import pygame
import random
# 游戏窗口尺寸
WINDOW_WIDTH = 600
WINDOW_HEIGHT = 400
# 蛇身单元格大小和速度
CELL_SIZE = 20
SNAKE_SPEED = 10
# 颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 初始化pygame模块
pygame.init()
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 蛇的初始位置和初始长度
snake_head = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
# 食物的初始位置
food_pos = [random.randrange(1, (WINDOW_WIDTH//CELL_SIZE)) * CELL_SIZE,
random.randrange(1, (WINDOW_HEIGHT//CELL_SIZE)) * CELL_SIZE]
food_spawn = True
# 初始方向(向右)
direction = 'RIGHT'
change_to = direction
# 蛇移动的函数
def move_snake():
global direction
if direction == 'UP':
snake_head[1] -= CELL_SIZE
elif direction == 'DOWN':
snake_head[1] += CELL_SIZE
elif direction == 'LEFT':
snake_head[0] -= CELL_SIZE
elif direction == 'RIGHT':
snake_head[0] += CELL_SIZE
# 游戏结束的函数
def game_over():
pygame.quit()
quit()
# 游戏主循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
change_to = 'UP'
elif event.key == pygame.K_DOWN:
change_to = 'DOWN'
elif event.key == pygame.K_LEFT:
change_to = 'LEFT'
elif event.key == pygame.K_RIGHT:
change_to = 'RIGHT'
# 确保蛇不会掉头走
if change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
elif change_to == 'DOWN' and direction ! 'UP':
direction = 'DOWN'
elif change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
elif change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
# 移动蛇
move_snake()
# 蛇头与食物的碰撞检测
if snake_head[0] == food_pos[0] and snake_head[1] == food_pos[1]:
food_spawn = False
else:
snake_body.pop()
# 生成新的食物
if not food_spawn:
food_pos = [random.randrange(1, (WINDOW_WIDTH//CELL_SIZE)) * CELL_SIZE,
random.randrange(1, (WINDOW_HEIGHT//CELL_SIZE)) * CELL_SIZE]
food_spawn = True
# 绘制游戏窗口
window.fill(BLACK)
for pos in snake_body:
pygame.draw.rect(window, GREEN, pygame.Rect(pos[0], pos[1], CELL_SIZE, CELL_SIZE))
pygame.draw.rect(window, RED, pygame.Rect(food_pos[0], food_pos[1], CELL_SIZE, CELL_SIZE))
# 边界和自身碰撞检测
if snake_head[0] < 0 or snake_head[0] >= WINDOW_WIDTH or snake_head[1] < 0 or snake_head[1] >= WINDOW_HEIGHT:
game_over()
for block in snake_body[1:]:
if snake_head[0] == block[0] and snake_head[1] == block[1]:
game_over()
# 更新蛇的位置
snake_body.insert(0, list(snake_head))
# 更新游戏窗口
pygame.display.update()
# 控制游戏速度
pygame.time.Clock().tick(SNAKE_SPEED)
```
希望这个代码能满足你的需求!如果有任何问题,请随时提问。