使用python生成一个贪吃蛇游戏
时间: 2024-03-17 07:46:16 浏览: 68
好的,下面是一个简单的 Python 贪吃蛇游戏的代码示例:
```python
import pygame, sys
import random
pygame.init()
# 定义窗口大小和格子大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
CELL_SIZE = 20
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 设置窗口大小
WINDOW_SIZE = (WINDOW_WIDTH, WINDOW_HEIGHT)
screen = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption('Snake Game')
# 定义字体
font = pygame.font.Font(None, 36)
# 定义贪吃蛇的初始位置和大小
snake = [(100, 100), (80, 100), (60, 100)]
snake_direction = 'right'
# 定义食物的初始位置
food = (random.randint(0, (WINDOW_WIDTH - CELL_SIZE) // CELL_SIZE) * CELL_SIZE,
random.randint(0, (WINDOW_HEIGHT - CELL_SIZE) // CELL_SIZE) * CELL_SIZE)
# 定义游戏循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
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'
# 移动贪吃蛇
if snake_direction == 'up':
new_head = (snake[0][0], snake[0][1] - CELL_SIZE)
elif snake_direction == 'down':
new_head = (snake[0][0], snake[0][1] + CELL_SIZE)
elif snake_direction == 'left':
new_head = (snake[0][0] - CELL_SIZE, snake[0][1])
elif snake_direction == 'right':
new_head = (snake[0][0] + CELL_SIZE, snake[0][1])
snake.insert(0, new_head)
# 判断是否吃到食物
if snake[0] == food:
food = (random.randint(0, (WINDOW_WIDTH - CELL_SIZE) // CELL_SIZE) * CELL_SIZE,
random.randint(0, (WINDOW_HEIGHT - CELL_SIZE) // CELL_SIZE) * CELL_SIZE)
else:
snake.pop()
# 判断是否撞到墙或自己的身体
if snake[0][0] < 0 or snake[0][0] >= WINDOW_WIDTH or snake[0][1] < 0 or snake[0][1] >= WINDOW_HEIGHT:
pygame.quit()
sys.exit()
for i in range(1, len(snake)):
if snake[0] == snake[i]:
pygame.quit()
sys.exit()
# 绘制界面
screen.fill(WHITE)
pygame.draw.rect(screen, GREEN, (food[0], food[1], CELL_SIZE, CELL_SIZE))
for x, y in snake:
pygame.draw.rect(screen, BLUE, (x, y, CELL_SIZE, CELL_SIZE))
# 显示得分
score = len(snake) - 3
score_text = font.render('Score: %d' % score, True, BLACK)
screen.blit(score_text, (10, 10))
pygame.display.update()
pygame.time.delay(100)
```
运行上面的代码,即可开始游戏。玩家可以使用方向键控制贪吃蛇的移动方向,吃到食物后贪吃蛇会变长,如果撞到墙或者自己的身体,游戏结束。
阅读全文