用python设计一个贪吃蛇游戏
时间: 2024-05-12 19:20:57 浏览: 85
由于贪吃蛇游戏需要图形界面的支持,因此需要使用一些第三方库,比如Pygame、Tkinter等。下面是使用Pygame库实现贪吃蛇游戏的代码示例:
```python
import pygame
import random
# 定义常量
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
GRID_SIZE = 20
FPS = 10
# 初始化Pygame
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 绘制网格
def draw_grid():
for x in range(0, SCREEN_WIDTH, GRID_SIZE):
pygame.draw.line(screen, WHITE, (x, 0), (x, SCREEN_HEIGHT))
for y in range(0, SCREEN_HEIGHT, GRID_SIZE):
pygame.draw.line(screen, WHITE, (0, y), (SCREEN_WIDTH, y))
# 随机生成食物
def generate_food(snake):
while True:
x = random.randrange(0, SCREEN_WIDTH, GRID_SIZE)
y = random.randrange(0, SCREEN_HEIGHT, GRID_SIZE)
if (x, y) not in snake:
return (x, y)
# 绘制蛇和食物
def draw_snake(snake):
for x, y in snake:
pygame.draw.rect(screen, GREEN, (x, y, GRID_SIZE, GRID_SIZE))
x, y = food
pygame.draw.rect(screen, RED, (x, y, GRID_SIZE, GRID_SIZE))
# 主循环
snake = [(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)]
direction = "RIGHT"
food = generate_food(snake)
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_LEFT and direction != "RIGHT":
direction = "LEFT"
elif event.key == pygame.K_RIGHT and direction != "LEFT":
direction = "RIGHT"
elif event.key == pygame.K_UP and direction != "DOWN":
direction = "UP"
elif event.key == pygame.K_DOWN and direction != "UP":
direction = "DOWN"
# 移动蛇的头部
x, y = snake[0]
if direction == "LEFT":
x -= GRID_SIZE
elif direction == "RIGHT":
x += GRID_SIZE
elif direction == "UP":
y -= GRID_SIZE
elif direction == "DOWN":
y += GRID_SIZE
snake.insert(0, (x, y))
# 判断是否吃到食物
if snake[0] == food:
food = generate_food(snake)
else:
snake.pop()
# 判断是否游戏结束
if (snake[0][0] < 0 or snake[0][0] >= SCREEN_WIDTH or
snake[0][1] < 0 or snake[0][1] >= SCREEN_HEIGHT or
snake[0] in snake[1:]):
pygame.quit()
quit()
# 绘制游戏界面
screen.fill(BLACK)
draw_grid()
draw_snake(snake)
pygame.display.update()
# 控制帧率
clock.tick(FPS)
```
运行以上代码,即可得到一个基本的贪吃蛇游戏。需要注意的是,以上代码只是一个简单的示例,还有很多可以改进和优化的地方。
阅读全文