如何用Python制作游戏?内附代码!详细教学
off999 2024-11-06 11:24 22 浏览 0 评论
今天为大家带来的内容是实战:用python写个小游戏!(详细解释,建议收藏)本文具有不错的参考意义及学习意义,希望大家会喜欢!要是觉得不错记得点赞,转发关注,不迷路哦!
一、游戏简介
本游戏是通过python编写的小游戏,给初学者熟悉python编程语言抛砖引玉,希望有所帮助。
成型的效果图如下:
二、编写步骤
1.引入库
代码如下:
###### AUTHOR:破茧狂龙 ######
###### DATE:20201002 ######
###### DESCRIPTION:移动的木板 ######
import pygame
from pygame.locals import *
import sys
import time
import random2.初始化
代码如下:
pygame.init()
BLACK = (0, 0, 0) # 黑色
WHITE = (255, 255, 255) # 白色
bg_color = (0,0,70) # 背景颜色
red = (200, 0, 0)
green = (0, 200, 0)
bright_red = (255, 0, 0)
bright_green = (0, 255, 0)
smallText = pygame.font.SysFont('SimHei', 20) #comicsansms
midlText = pygame.font.SysFont('SimHei', 50)
barsize = [30, 10]
SCREEN_SIZE = [400, 500] # 屏幕大小
BALL_SIZE = [15, 15] # 球的尺寸
fontcolor = (255,255,255) # 定义字体的颜色
myimg = r"img\b1.jpg"
background = pygame.image.load(myimg) # 图片位置
background = pygame.transform.scale(background, SCREEN_SIZE)
# ball 初始位置
ball_pos_x = SCREEN_SIZE[0] // 2 - BALL_SIZE[0] / 2
ball_pos_y = 0
# ball 移动方向
ball_dir_y = 1 # 1:down
ball_pos = pygame.Rect(ball_pos_x, ball_pos_y, BALL_SIZE[0], BALL_SIZE[1])
clock = pygame.time.Clock() # 定时器
screen = pygame.display.set_mode(SCREEN_SIZE)
# 设置标题
pygame.display.set_caption('python小游戏-移动木板')
# 设置图标
image = pygame.image.load(myimg)
pygame.display.set_icon(image)3.相关自定义函数
代码如下:
###### 自定义函数 ######
def button(msg, x, y, w, h, ic, ac, action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + w > mouse[0] > x and y + h > mouse[1] > y:
pygame.draw.rect(screen, ac, (x, y, w, h))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(screen, ic, (x, y, w, h))
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ((x + (w / 2)), (y + (h / 2)))
screen.blit(textSurf, textRect)
def text_objects(text, font):
textSurface = font.render(text, True, fontcolor)
return textSurface, textSurface.get_rect()
def quitgame():
pygame.quit()
quit()
def message_diaplay(text):
largeText = pygame.font.SysFont('SimHei', 115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((screen[0] / 2), (screen[1] / 2))
screen.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()4.相关自定义函数
代码如下:
def game_first_win():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.fill(bg_color)
###游戏名称
TextSurf, TextRect = text_objects('移动木板', midlText)
TextRect.center = ((SCREEN_SIZE[0] / 2), (SCREEN_SIZE[1] / 2 - 70 ))
screen.blit(TextSurf, TextRect)
###作者
TextSurf_ZZ, TextRect_ZZ = text_objects('AUTHOR:破茧狂龙', smallText)
TextRect_ZZ.center = ((SCREEN_SIZE[0] / 2), (SCREEN_SIZE[1] / 2 + 30))
screen.blit(TextSurf_ZZ, TextRect_ZZ)
button("开始", 60, 400, 100, 50, green, bright_green, game_loop)
button("取消", 230, 400, 100, 50, red, bright_red, quitgame)
pygame.display.update()
clock.tick(15)
###### 移动的木板游戏类 ######
def game_loop():
pygame.mouse.set_visible(1) # 移动鼠标不可见
###变量###
score = 0 #分数
count_O = 0 #循环的次数变量1 用于统计等级
count_N = 0 #循环的次数变量2 用于统计等级
c_level = 1 #等级
x_change = 0 #移动的变量
x = SCREEN_SIZE[0] // 2 - barsize[0] // 2
y = SCREEN_SIZE[1] - barsize[1]
# ball 初始位置
ball_pos_pz = ball_pos
while True:
bar_move_left = False
bar_move_right = False
###当每次满X分后,升级等级
if count_O != count_N and score % 5 == 0:
c_level += 1
count_O = count_N
###### 获取键盘输入 ######
for event in pygame.event.get():
if event.type == QUIT: # 当按下关闭按键
pygame.quit()
sys.exit() # 接收到退出事件后退出程序
elif event.type == KEYDOWN:
##按键盘Q键 暂停
if event.key == pygame.K_q:
time.sleep(10)
##左移动
if event.key == pygame.K_LEFT:
bar_move_left = True
x_change = -30
else:
bar_move_left = False
##右移动
if event.key == pygame.K_RIGHT:
bar_move_right = True
x_change = +30
else:
bar_move_right = False
if event.key != pygame.K_LEFT and event.key != pygame.K_RIGHT:
bar_move_left = False
bar_move_right = False
##木板的位置移动
if bar_move_left == True and bar_move_right == False:
x += x_change
if bar_move_left == False and bar_move_right == True:
x += x_change
##填充背景
screen.blit(background, (0, 0)) # (0,0)代表图片位置起点x 轴 Y轴
##获取最新的木板位置,并渲染在前台
bar_pos = pygame.Rect(x, y, barsize[0], BALL_SIZE[1])
bar_pos.left = x
pygame.draw.rect(screen, WHITE, bar_pos)
## 球移动,并渲染在前台
ball_pos_pz.bottom += ball_dir_y * 3
pygame.draw.rect(screen, WHITE, ball_pos_pz)
## 判断球是否落到板上
if bar_pos.top <= ball_pos_pz.bottom and (
bar_pos.left <= ball_pos_pz.right and bar_pos.right >= ball_pos_pz.left):
score += 1 # 分数每次加1
count_N += 1
elif bar_pos.top <= ball_pos_pz.bottom and (
bar_pos.left > ball_pos_pz.right or bar_pos.right < ball_pos_pz.left):
print("Game Over: ", score)
return score
## 更新球下落的初始位置
if bar_pos.top <= ball_pos_pz.bottom:
ball_x = random.randint(0, SCREEN_SIZE[0] - BALL_SIZE[0])
ball_pos_pz = pygame.Rect(ball_x, ball_pos_y, BALL_SIZE[0], BALL_SIZE[1])
######### 显示游戏等级 #########
TextSurf_lev, TextRect_lev = text_objects("等级 : " + str(c_level), smallText)
TextRect_lev.center = (60, 20)
screen.blit(TextSurf_lev, TextRect_lev)
######### 显示分数结果 #########
TextSurf_sco, TextRect_sco = text_objects("分数 : " + str(score), smallText)
TextRect_sco.center = (60, 50)
screen.blit(TextSurf_sco, TextRect_sco)
pygame.display.update() # 更新软件界面显示
clock.tick(60)# 三、完整的代码
代码如下:
###### AUTHOR:破茧狂龙 ######
###### DATE:20201002 ######
###### DESCRIPTION:移动的木板 ######
import pygame
from pygame.locals import *
import sys
import time
import random
pygame.init()
BLACK = (0, 0, 0) # 黑色
WHITE = (255, 255, 255) # 白色
bg_color = (0,0,70) # 背景颜色
red = (200, 0, 0)
green = (0, 200, 0)
bright_red = (255, 0, 0)
bright_green = (0, 255, 0)
smallText = pygame.font.SysFont('SimHei', 20) #comicsansms
midlText = pygame.font.SysFont('SimHei', 50)
barsize = [30, 10]
SCREEN_SIZE = [400, 500] # 屏幕大小
BALL_SIZE = [15, 15] # 球的尺寸
fontcolor = (255,255,255) # 定义字体的颜色
myimg = r"img\b1.jpg"
background = pygame.image.load(myimg) # 图片位置
background = pygame.transform.scale(background, SCREEN_SIZE)
# ball 初始位置
ball_pos_x = SCREEN_SIZE[0] // 2 - BALL_SIZE[0] / 2
ball_pos_y = 0
# ball 移动方向
ball_dir_y = 1 # 1:down
ball_pos = pygame.Rect(ball_pos_x, ball_pos_y, BALL_SIZE[0], BALL_SIZE[1])
clock = pygame.time.Clock() # 定时器
screen = pygame.display.set_mode(SCREEN_SIZE)
# 设置标题
pygame.display.set_caption('python小游戏-移动木板')
# 设置图标
image = pygame.image.load(myimg)
pygame.display.set_icon(image)
###### 自定义函数 ######
def button(msg, x, y, w, h, ic, ac, action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + w > mouse[0] > x and y + h > mouse[1] > y:
pygame.draw.rect(screen, ac, (x, y, w, h))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(screen, ic, (x, y, w, h))
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ((x + (w / 2)), (y + (h / 2)))
screen.blit(textSurf, textRect)
def text_objects(text, font):
textSurface = font.render(text, True, fontcolor)
return textSurface, textSurface.get_rect()
def quitgame():
pygame.quit()
quit()
def message_diaplay(text):
largeText = pygame.font.SysFont('SimHei', 115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((screen[0] / 2), (screen[1] / 2))
screen.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def game_first_win():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.fill(bg_color)
###游戏名称
TextSurf, TextRect = text_objects('移动木板', midlText)
TextRect.center = ((SCREEN_SIZE[0] / 2), (SCREEN_SIZE[1] / 2 - 70 ))
screen.blit(TextSurf, TextRect)
###作者
TextSurf_ZZ, TextRect_ZZ = text_objects('AUTHOR:破茧狂龙', smallText)
TextRect_ZZ.center = ((SCREEN_SIZE[0] / 2), (SCREEN_SIZE[1] / 2 + 30))
screen.blit(TextSurf_ZZ, TextRect_ZZ)
button("开始", 60, 400, 100, 50, green, bright_green, game_loop)
button("取消", 230, 400, 100, 50, red, bright_red, quitgame)
pygame.display.update()
clock.tick(15)
###### 移动的木板游戏类 ######
def game_loop():
pygame.mouse.set_visible(1) # 移动鼠标不可见
###变量###
score = 0 #分数
count_O = 0 #循环的次数变量1 用于统计等级
count_N = 0 #循环的次数变量2 用于统计等级
c_level = 1 #等级
x_change = 0 #移动的变量
x = SCREEN_SIZE[0] // 2 - barsize[0] // 2
y = SCREEN_SIZE[1] - barsize[1]
# ball 初始位置
ball_pos_pz = ball_pos
while True:
bar_move_left = False
bar_move_right = False
###当每次满X分后,升级等级
if count_O != count_N and score % 5 == 0:
c_level += 1
count_O = count_N
###### 获取键盘输入 ######
for event in pygame.event.get():
if event.type == QUIT: # 当按下关闭按键
pygame.quit()
sys.exit() # 接收到退出事件后退出程序
elif event.type == KEYDOWN:
##按键盘Q键 暂停
if event.key == pygame.K_q:
time.sleep(10)
##左移动
if event.key == pygame.K_LEFT:
bar_move_left = True
x_change = -30
else:
bar_move_left = False
##右移动
if event.key == pygame.K_RIGHT:
bar_move_right = True
x_change = +30
else:
bar_move_right = False
if event.key != pygame.K_LEFT and event.key != pygame.K_RIGHT:
bar_move_left = False
bar_move_right = False
##木板的位置移动
if bar_move_left == True and bar_move_right == False:
x += x_change
if bar_move_left == False and bar_move_right == True:
x += x_change
##填充背景
screen.blit(background, (0, 0)) # (0,0)代表图片位置起点x 轴 Y轴
##获取最新的木板位置,并渲染在前台
bar_pos = pygame.Rect(x, y, barsize[0], BALL_SIZE[1])
bar_pos.left = x
pygame.draw.rect(screen, WHITE, bar_pos)
## 球移动,并渲染在前台
ball_pos_pz.bottom += ball_dir_y * 3
pygame.draw.rect(screen, WHITE, ball_pos_pz)
## 判断球是否落到板上
if bar_pos.top <= ball_pos_pz.bottom and (
bar_pos.left <= ball_pos_pz.right and bar_pos.right >= ball_pos_pz.left):
score += 1 # 分数每次加1
count_N += 1
elif bar_pos.top <= ball_pos_pz.bottom and (
bar_pos.left > ball_pos_pz.right or bar_pos.right < ball_pos_pz.left):
print("Game Over: ", score)
return score
## 更新球下落的初始位置
if bar_pos.top <= ball_pos_pz.bottom:
ball_x = random.randint(0, SCREEN_SIZE[0] - BALL_SIZE[0])
ball_pos_pz = pygame.Rect(ball_x, ball_pos_y, BALL_SIZE[0], BALL_SIZE[1])
######### 显示游戏等级 #########
TextSurf_lev, TextRect_lev = text_objects("等级 : " + str(c_level), smallText)
TextRect_lev.center = (60, 20)
screen.blit(TextSurf_lev, TextRect_lev)
######### 显示分数结果 #########
TextSurf_sco, TextRect_sco = text_objects("分数 : " + str(score), smallText)
TextRect_sco.center = (60, 50)
screen.blit(TextSurf_sco, TextRect_sco)
pygame.display.update() # 更新软件界面显示
clock.tick(60)
####程序执行顺序######
game_first_win()
game_loop()
pygame.quit()结尾
最后多说一句,小编是一名python开发工程师,这里有我自己整理了一套最新的python系统学习教程,包括从基础的python脚本到web开发、爬虫、数据分析、数据可视化、机器学习等。想要这些资料的可以关注小编,并在后台私信小编:“01”即可领取。
本文的文字及图片来源于网络加上自己的想法,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。
相关推荐
- 戴尔官网保修查询入口(戴尔售后保质期查询)
-
可以按照以下步骤查询戴尔笔记本电脑的保修期:1.打开戴尔官网:https://www.戴尔.com/zh-cn/售后服务/保修政策.html2.点击页面上方的“服务与支持”按钮,进入戴尔的服务支持...
- 手机号邮箱登录入口(手机号邮箱官网)
-
手机163邮箱登录入口如下:163邮箱官网入口:https://smart.mail.163.com/login.htm点击进入登录或者注册邮箱即可。手机浏览器访问进入官网http://www.123...
- sd卡(sd卡无法读取怎么修复)
-
SD卡是大卡,相机用的;普通的手机内存卡,是小卡,正规的名称是macrosd卡,也就是微型SD卡。可以通过卡套转为普通的SD卡的大小。 其实就是大小不同。但手机上的内存卡,人们经常也俗称为SD...
- windows7蓝牙功能在哪里打开
-
点击搜索框在windows7系统主界面点击开始菜单,点击打开搜索框。输入命令输入services.msc后回车,在列表中找到并右击BluetoothSupportS...点击属性选择进入属性菜单,...
-
- 2010激活密钥(microsoft2010激活密钥)
-
步骤/方式1officeprofessionalplus2010:(office专业版)6QFdx-pYH2G-ppYFd-C7RJM-BBKQ8Bdd3G-xM7FB-Bd2HM-YK63V-VQFdKVYBBJ-TRJpB-QFQ...
-
2025-11-19 04:03 off999
- 联想官方刷新bios工具(联想电脑刷新bios)
-
刷新BIOS需要使用联想的官方网站或授权维修中心来进行操作。以下是一些基本步骤:1.访问联想的官方网站,找到BIOS更新程序并下载。在下载过程中,请确保选择与您计算机型号匹配的版本。2.将下载的B...
-
- 苹果ios14系统下载(苹果ios14.1下载)
-
1方法一步骤/方式一打开Appstore。步骤/方式二在搜索栏点击搜索框。步骤/方式三搜索并点击需要下载的软件。步骤/方式四点击获取。步骤/方式五最后验证ID密码即可。1.在应用商店搜索你要下载的应用名称。2.点击下载按钮,如果要求登...
-
2025-11-19 03:03 off999
- office2010怎么免费永久激活密钥
-
用这个试试,一个KMS激活工具可以激活2010到2019的Office自家的目前用的就是这个microsoft6477.moe/1716.html直接使用这个Microsoftoffice2010...
-
- 类似爱加速的国内ip(类似爱加速的app)
-
推荐“V8盒子”。这一款免费无广告的模拟器,不同于其它软件盒子,而是类似于X8沙箱,满足游戏多开,画中画,悬浮球操作,熄屏后台运行等多功能的沙箱盒子.支持一键root,一键安装xposed框架,能在安卓/苹果手机上运行多个安卓/ios虚拟系...
-
2025-11-19 02:03 off999
- 阿里旺旺手机客户端(阿里旺旺手机app)
-
手机淘宝的旺旺在打开商品后,会看到左下角有个旺旺的图标,点击就可以联系了。 阿里旺旺是将原先的淘宝旺旺与阿里巴巴贸易通整合在一起的一个新品牌。它是淘宝和阿里巴巴为商人量身定做的免费网上商务沟通软件,...
- 最纯净的pe装机工具(pe工具哪个纯净)
-
U盘装系统步骤:1.制作U盘启动盘。这里推荐大白菜U盘启动盘制作工具,在网上一搜便是。2.U盘启动盘做好了,我们还需要一个GHOST文件,可以从网上下载一个ghost版的XP/WIN7/WIN8系统,...
- 装一个erp系统多少钱(wms仓库管理软件)
-
现在主流有客户端ERP和云端ERP两种客户端通常一次买断,价格在万元左右,但是还有隐性费用,你需要支付服务器、数据管理员,此外如果系统需要更新维护,你还需要支付另外一笔不菲的费用。云端ERP:优势...
- cad2014序列号和密钥永久(autocad2014序列号和密钥)
-
1在cad2014中修改标注样式后,需要将其保存2单击“样式管理器”按钮,在弹出的窗口中选择修改后的标注样式,然后单击“设置为当前”按钮,再单击“保存当前样式”按钮,将其保存为新的样式名称3为了...
- qq修改密保手机号(qq修改密保手机号是什么意思)
-
QQ更改绑定的手机号码操作步骤如下:1、打开手机主界面,找到“QQ”软件点击打开。2、输入正确的QQ账户和密码登录到qq主界面。3、点击左上角的头像“图片”,进入到个人中心界面。4、进入到个人中心界面...
欢迎 你 发表评论:
- 一周热门
-
-
抖音上好看的小姐姐,Python给你都下载了
-
全网最简单易懂!495页Python漫画教程,高清PDF版免费下载
-
Python 3.14 的 UUIDv6/v7/v8 上新,别再用 uuid4 () 啦!
-
python入门到脱坑 输入与输出—str()函数
-
飞牛NAS部署TVGate Docker项目,实现内网一键转发、代理、jx
-
宝塔面板如何添加免费waf防火墙?(宝塔面板开启https)
-
Python三目运算基础与进阶_python三目运算符判断三个变量
-
(新版)Python 分布式爬虫与 JS 逆向进阶实战吾爱分享
-
慕ke 前端工程师2024「完整」
-
失业程序员复习python笔记——条件与循环
-
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)
