我需要贪吃蛇小游戏的python代码
时间: 2024-10-07 17:06:38 浏览: 26
当然可以,贪吃蛇是一个经典的文本冒险游戏,这里提供一个基本的Python版本作为起点,使用了`pygame`库来创建图形界面:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置窗口大小
window_size = (400, 600)
screen = pygame.display.set_mode(window_size)
pygame.display.set_caption("贪吃蛇")
snake_speed = 15
snake_pos = [[100, 100], [90, 100], [80, 100]] # 初始蛇身位置
direction = 'right' # 起始方向:右
food_pos = [random.randint(0, window_size[0] - 1), random.randint(0, window_size[1] - 1)] # 食物位置
def draw_snake():
for pos in snake_pos:
pygame.draw.rect(screen, (0, 255, 0), [pos[0], pos[1], 10, 10])
def move_snake():
if direction == 'up':
snake_pos.insert(0, [snake_pos[0][0] - 10, snake_pos[0][1]])
elif direction == 'down':
snake_pos.insert(0, [snake_pos[0][0] + 10, snake_pos[0][1]])
elif direction == 'left':
snake_pos.insert(0, [snake_pos[0][0], snake_pos[0][1] - 10])
else:
snake_pos.insert(0, [snake_pos[0][0], snake_pos[0][1] + 10])
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction != 'down':
direction = 'up'
elif event.key == pygame.K_DOWN and direction != 'up':
direction = 'down'
elif event.key == pygame.K_LEFT and direction != 'right':
direction = 'left'
elif event.key == pygame.K_RIGHT and direction != 'left':
direction = 'right'
screen.fill((0, 0, 0))
draw_snake()
food_pos = [random.choice(range(window_size[0])) * 10, random.choice(range(window_size[1])) * 10]
if snake_pos[0] == food_pos:
snake_pos.append([snake_pos[-1][0], snake_pos[-1][1]])
snake_speed += 5
else:
snake_pos.pop()
move_snake()
pygame.display.update()
pygame.time.delay(snake_speed)
阅读全文