Python 贪吃蛇游戏代码示例 - 从入门到精通
以下是一个简单的贪吃蛇代码示例,使用 Python 和 Pygame 库实现:
import pygame
import random
# 初始化pygame
pygame.init()
# 定义常量
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
BLOCK_SIZE = 20
FONT_SIZE = 30
FPS = 10
FONT_COLOR = (255, 255, 255)
BG_COLOR = (0, 0, 0)
# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 创建字体
font = pygame.font.SysFont(None, FONT_SIZE)
# 定义蛇类
class Snake:
def __init__(self):
self.body = [(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)]
self.direction = 'right'
def move(self):
head = self.body[0]
if self.direction == 'right':
new_head = (head[0] + BLOCK_SIZE, head[1])
elif self.direction == 'left':
new_head = (head[0] - BLOCK_SIZE, head[1])
elif self.direction == 'up':
new_head = (head[0], head[1] - BLOCK_SIZE)
elif self.direction == 'down':
new_head = (head[0], head[1] + BLOCK_SIZE)
self.body.insert(0, new_head)
self.body.pop()
def change_direction(self, direction):
if direction == 'right' and self.direction != 'left':
self.direction = 'right'
elif direction == 'left' and self.direction != 'right':
self.direction = 'left'
elif direction == 'up' and self.direction != 'down':
self.direction = 'up'
elif direction == 'down' and self.direction != 'up':
self.direction = 'down'
def grow(self):
tail = self.body[-1]
if self.direction == 'right':
new_tail = (tail[0] - BLOCK_SIZE, tail[1])
elif self.direction == 'left':
new_tail = (tail[0] + BLOCK_SIZE, tail[1])
elif self.direction == 'up':
new_tail = (tail[0], tail[1] + BLOCK_SIZE)
elif self.direction == 'down':
new_tail = (tail[0], tail[1] - BLOCK_SIZE)
self.body.append(new_tail)
# 定义食物类
class Food:
def __init__(self):
self.x = random.randint(0, SCREEN_WIDTH // BLOCK_SIZE - 1) * BLOCK_SIZE
self.y = random.randint(0, SCREEN_HEIGHT // BLOCK_SIZE - 1) * BLOCK_SIZE
def draw(self):
pygame.draw.rect(screen, (255, 0, 0), (self.x, self.y, BLOCK_SIZE, BLOCK_SIZE))
# 创建蛇和食物对象
snake = Snake()
food = Food()
# 定义游戏主循环
clock = pygame.time.Clock()
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
snake.change_direction('right')
elif event.key == pygame.K_LEFT:
snake.change_direction('left')
elif event.key == pygame.K_UP:
snake.change_direction('up')
elif event.key == pygame.K_DOWN:
snake.change_direction('down')
# 移动蛇
snake.move()
# 判断是否吃到食物
if snake.body[0] == (food.x, food.y):
snake.grow()
food = Food()
# 判断游戏是否结束
if snake.body[0][0] < 0 or snake.body[0][0] >= SCREEN_WIDTH or snake.body[0][1] < 0 or snake.body[0][1] >= SCREEN_HEIGHT:
running = False
for i in range(1, len(snake.body)):
if snake.body[0] == snake.body[i]:
running = False
# 绘制游戏界面
screen.fill(BG_COLOR)
snake_rects = [pygame.Rect(x, y, BLOCK_SIZE, BLOCK_SIZE) for x, y in snake.body]
pygame.draw.rect(screen, (255, 255, 255), snake_rects[0])
pygame.draw.rect(screen, (0, 255, 0), snake_rects[1:])
food.draw()
score_text = font.render('Score: {}'.format(len(snake.body) - 1), True, FONT_COLOR)
screen.blit(score_text, (10, 10))
pygame.display.flip()
# 控制游戏帧率
clock.tick(FPS)
# 退出游戏
pygame.quit()
本代码示例展示了如何使用 Python 和 Pygame 库创建一个简单的贪吃蛇游戏。它包括以下关键要素:
- 游戏初始化:初始化 Pygame 库,设置窗口大小、标题、背景颜色等。
- 定义蛇类:
Snake类定义了蛇的属性和行为,包括蛇的身体、方向、移动、改变方向和生长等。 - 定义食物类:
Food类定义了食物的属性和行为,包括随机生成位置和绘制。 - 游戏循环:游戏循环处理事件、移动蛇、判断是否吃到食物、判断游戏是否结束以及绘制游戏界面。
- 事件处理:处理用户输入,例如键盘按键,控制蛇的方向。
- 蛇的移动:根据蛇的方向移动蛇头,并更新蛇的身体。
- 食物生成:随机生成食物的位置。
- 碰撞检测:判断蛇头是否与食物或自身碰撞,以决定是否得分或游戏结束。
- 得分显示:显示当前得分。
- 绘制游戏界面:根据游戏状态绘制蛇、食物和得分等元素。
本代码示例只是一个简单的开始,你可以根据自己的需求进行扩展和改进,例如添加更多游戏难度、关卡、音效等。
原文地址: https://www.cveoy.top/t/topic/kwSs 著作权归作者所有。请勿转载和采集!