目录
1. 概述
2. 环境准备
3. 初始化游戏
4. 定义游戏参数
5. 辅助工作
6. 游戏主循环
7. 启动!
8. 后续工作
9. 完整代码
闲来无事,想自己做点游戏玩玩,之前用C写了很多游戏,但都是基于dos窗口的,太枯燥了。
最近都在用python编程,发现pygame还不错,正好练练手。
贪吃蛇是一款经典的游戏,相信很多人都玩过。今天,我将用Python的pygame
库来实现一个简单的贪吃蛇游戏。通过这个项目,你不仅可以学习到如何使用pygame
进行游戏开发,还能掌握一些基本的游戏逻辑设计。
1. 概述
进行项目前,我们先来思考整个游戏的流程是啥。在这个项目中,我们将实现以下功能:
-
蛇的移动控制(上下左右)。
-
食物的随机生成。
-
蛇吃到食物后身体变长。
-
碰撞检测(撞墙或撞到自己时游戏结束)。
-
显示当前得分。
2. 环境准备
首先,确保你已经安装了pygame
库。如果没有安装,可以通过以下命令安装:
pip install pygame
Pygame是被设计用来写游戏的python模块集合,Pygame是在优秀的SDL库之上开发的功能性包。使用python可以导入pygame来开发具有全部特性的游戏和多媒体软件,Pygame是极度轻便的并且可以运行在几乎所有的平台和操作系统上。
3. 初始化游戏
首先,需要做准备工作,例如蛇的颜色,游戏窗口的大小之类
python">import pygame
import time
import random# 初始化pygame
pygame.init()# 定义颜色
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)# 定义屏幕尺寸
width = 600
height = 400# 创建游戏窗口
game_window = pygame.display.set_mode((width, height))# 设置游戏标题
pygame.display.set_caption('贪吃蛇游戏')# 定义时钟
clock = pygame.time.Clock()
4. 定义游戏参数
有了初始化工作,开始考虑蛇身的大小,为了控制游戏的难易程序,这里定义速度的变量
-
snake_block
定义了蛇的身体块的大小。 -
snake_speed
控制了蛇的移动速度。 -
定义了两个字体样式,分别用于显示消息和得分。
python"># 定义蛇的块大小和速度
snake_block = 10
snake_speed = 15# 定义字体样式
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)
5. 辅助工作
当然这些工作还不够,正常的游戏要有分数显示,有游戏输赢的显示,这里通过定义函数解决
-
display_score
函数用于在屏幕上显示当前得分。 -
draw_snake
函数用于绘制蛇的身体。 -
display_message
函数用于在游戏结束时显示提示信息。
python"># 显示得分
def display_score(score):value = score_font.render("得分: " + str(score), True, yellow)game_window.blit(value, [0, 0])# 绘制蛇
def draw_snake(snake_block, snake_list):for x in snake_list:pygame.draw.rect(game_window, green, [x[0], x[1], snake_block, snake_block])# 显示消息
def display_message(msg, color):mesg = font_style.render(msg, True, color)game_window.blit(mesg, [width / 6, height / 3])
6. 游戏主循环
这一步是最重要的工作,负责游戏正常运行
-
游戏初始化:设置蛇的初始位置、食物的位置以及蛇的长度。
-
游戏结束逻辑:当蛇撞墙或撞到自己时,显示提示信息,并允许玩家选择退出或重新开始。
-
用户输入处理:通过键盘控制蛇的移动方向。
-
碰撞检测:检测蛇是否撞墙或撞到自己。
-
食物检测:如果蛇吃到食物,则食物重新生成,蛇的长度增加。
python">def game_loop():game_over = Falsegame_close = Falsex1 = width / 2y1 = height / 2x1_change = 0y1_change = 0snake_list = []length_of_snake = 1food_x = round(random.randrange(0, width - snake_block) / 10.0) * 10.0food_y = round(random.randrange(0, height - snake_block) / 10.0) * 10.0while not game_over:# 游戏结束时的逻辑while game_close:game_window.fill(blue)display_message("你输了! 按 Q 退出游戏或 C 重新开始", red)display_score(length_of_snake - 1)pygame.display.update()for event in pygame.event.get():if event.type == pygame.KEYDOWN:if event.key == pygame.K_q:game_over = Truegame_close = Falseif event.key == pygame.K_c:game_loop()# 处理用户输入for event in pygame.event.get():if event.type == pygame.QUIT:game_over = Trueif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:x1_change = -snake_blocky1_change = 0elif event.key == pygame.K_RIGHT:x1_change = snake_blocky1_change = 0elif event.key == pygame.K_UP:y1_change = -snake_blockx1_change = 0elif event.key == pygame.K_DOWN:y1_change = snake_blockx1_change = 0# 碰撞检测if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:game_close = Truex1 += x1_changey1 += y1_changegame_window.fill(black)pygame.draw.rect(game_window, red, [food_x, food_y, snake_block, snake_block])# 更新蛇的身体snake_head = [x1, y1]snake_list.append(snake_head)if len(snake_list) > length_of_snake:del snake_list[0]# 检测是否撞到自己for x in snake_list[:-1]:if x == snake_head:game_close = Truedraw_snake(snake_block, snake_list)display_score(length_of_snake - 1)pygame.display.update()# 检测是否吃到食物if x1 == food_x and y1 == food_y:food_x = round(random.randrange(0, width - snake_block) / 10.0) * 10.0food_y = round(random.randrange(0, height - snake_block) / 10.0) * 10.0length_of_snake += 1clock.tick(snake_speed)pygame.quit()quit()
7. 启动!
游戏终于可以运行了!
python"># 启动游戏
game_loop()
死亡也会有提示
8. 后续工作
本文,我们实现了一个简单的贪吃蛇游戏。虽然功能比较简单,但它涵盖了游戏开发中的许多核心概念,例如:
-
游戏循环
-
用户输入处理
-
碰撞检测
-
图形绘制
当然游戏没有音效容易枯燥,可以在此基础上进一步扩展,例如:
-
添加音效。
-
增加难度(如障碍物)。
-
实现多人模式。
9. 完整代码
代码如下:
python">import pygame
import random# 初始化pygame
pygame.init()# 定义颜色
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)# 定义屏幕尺寸
width = 600
height = 400# 创建游戏窗口
game_window = pygame.display.set_mode((width, height))# 设置游戏标题
pygame.display.set_caption('贪吃蛇游戏')# 定义时钟
clock = pygame.time.Clock()# 定义蛇的块大小和速度
snake_block = 10
snake_speed = 15# 定义字体样式
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)# 显示得分
def display_score(score):value = score_font.render("score: " + str(score), True, yellow)game_window.blit(value, [0, 0])# 绘制蛇
def draw_snake(snake_block, snake_list):for x in snake_list:pygame.draw.rect(game_window, green, [x[0], x[1], snake_block, snake_block])# 显示消息
def display_message(msg, color):mesg = font_style.render(msg, True, color)game_window.blit(mesg, [width / 6, height / 3])def game_loop():game_over = Falsegame_close = Falsex1 = width / 2y1 = height / 2x1_change = 0y1_change = 0snake_list = []length_of_snake = 1food_x = round(random.randrange(0, width - snake_block) / 10.0) * 10.0food_y = round(random.randrange(0, height - snake_block) / 10.0) * 10.0while not game_over:# 游戏结束时的逻辑while game_close:game_window.fill(blue)display_message("lose ! tap Q exit or C restart", red)display_score(length_of_snake - 1)pygame.display.update()for event in pygame.event.get():if event.type == pygame.KEYDOWN:if event.key == pygame.K_q:game_over = Truegame_close = Falseif event.key == pygame.K_c:game_loop()# 处理用户输入for event in pygame.event.get():if event.type == pygame.QUIT:game_over = Trueif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:x1_change = -snake_blocky1_change = 0elif event.key == pygame.K_RIGHT:x1_change = snake_blocky1_change = 0elif event.key == pygame.K_UP:y1_change = -snake_blockx1_change = 0elif event.key == pygame.K_DOWN:y1_change = snake_blockx1_change = 0# 碰撞检测if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:game_close = Truex1 += x1_changey1 += y1_changegame_window.fill(black)pygame.draw.rect(game_window, red, [food_x, food_y, snake_block, snake_block])# 更新蛇的身体snake_head = [x1, y1]snake_list.append(snake_head)if len(snake_list) > length_of_snake:del snake_list[0]# 检测是否撞到自己for x in snake_list[:-1]:if x == snake_head:game_close = Truedraw_snake(snake_block, snake_list)display_score(length_of_snake - 1)pygame.display.update()# 检测是否吃到食物if x1 == food_x and y1 == food_y:food_x = round(random.randrange(0, width - snake_block) / 10.0) * 10.0food_y = round(random.randrange(0, height - snake_block) / 10.0) * 10.0length_of_snake += 1clock.tick(snake_speed)pygame.quit()quit()# 启动游戏
game_loop()