python小游戏贪吃蛇代码
时间: 2023-07-02 17:22:43 浏览: 132
以下是一个简单的 Python 贪吃蛇游戏示例代码:
```python
import pygame
import random
# 游戏界面的宽和高
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
# 贪吃蛇每个方块的大小
BLOCK_SIZE = 20
# 贪吃蛇的移动速度
SPEED = 5
# 定义颜色常量
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 初始化 Pygame
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 定义字体
font = pygame.font.SysFont('arial', 36)
# 定义游戏结束的函数
def game_over():
text = font.render('Game Over', True, RED)
text_rect = text.get_rect()
text_rect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
screen.blit(text, text_rect)
pygame.display.update()
pygame.time.delay(2000)
pygame.quit()
quit()
# 定义画贪吃蛇的函数
def draw_snake(snake):
for block in snake:
rect = pygame.Rect(block[0], block[1], BLOCK_SIZE, BLOCK_SIZE)
pygame.draw.rect(screen, GREEN, rect)
# 定义生成食物的函数
def generate_food():
x = random.randint(0, SCREEN_WIDTH // BLOCK_SIZE - 1) * BLOCK_SIZE
y = random.randint(0, SCREEN_HEIGHT // BLOCK_SIZE - 1) * BLOCK_SIZE
return x, y
# 初始化贪吃蛇和食物
snake = [[SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2]]
food = generate_food()
# 定义贪吃蛇的移动方向
direction = 'right'
# 游戏循环
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'
# 移动贪吃蛇
if direction == 'left':
snake.insert(0, [snake[0][0] - BLOCK_SIZE, snake[0][1]])
elif direction == 'right':
snake.insert(0, [snake[0][0] + BLOCK_SIZE, snake[0][1]])
elif direction == 'up':
snake.insert(0, [snake[0][0], snake[0][1] - BLOCK_SIZE])
elif direction == 'down':
snake.insert(0, [snake[0][0], snake[0][1] + BLOCK_SIZE])
# 判断是否吃到食物
if snake[0] == list(food):
food = generate_food()
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:]:
game_over()
# 绘制游戏界面
screen.fill(BLACK)
draw_snake(snake)
pygame.draw.rect(screen, RED, pygame.Rect(food[0], food[1], BLOCK_SIZE, BLOCK_SIZE))
pygame.display.update()
# 控制游戏帧率
pygame.time.Clock().tick(SPEED)
```
运行该代码,即可开始游戏。其中,使用 Pygame 库来实现游戏界面的绘制和事件处理,贪吃蛇的移动和碰撞检测等逻辑由代码来实现。
阅读全文