如何用Python制作游戏?内附代码!详细教学
off999 2024-11-06 11:24 14 浏览 0 评论
今天为大家带来的内容是实战:用python写个小游戏!(详细解释,建议收藏)本文具有不错的参考意义及学习意义,希望大家会喜欢!要是觉得不错记得点赞,转发关注,不迷路哦!
一、游戏简介
本游戏是通过python编写的小游戏,给初学者熟悉python编程语言抛砖引玉,希望有所帮助。
成型的效果图如下:
二、编写步骤
1.引入库
代码如下:
###### AUTHOR:破茧狂龙 ######
###### DATE:20201002 ######
###### DESCRIPTION:移动的木板 ######
import pygame
from pygame.locals import *
import sys
import time
import random
2.初始化
代码如下:
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”即可领取。
本文的文字及图片来源于网络加上自己的想法,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。
相关推荐
- 推荐一款Python的GUI可视化工具(python 可视化工具)
-
在Python基础语法学习完成后,进一步开发应用界面时,就需要涉及到GUI了,GUI全称是图形用户界面(GraphicalUserInterface,又称图形用户接口),采用图形方式显示的计算机操...
- 教你用Python绘制谷歌浏览器的3种图标
-
前两天在浏览matplotlib官方网站时,笔者无意中看到一个挺有意思的图片,就是用matplotlib制作的火狐浏览器的logo,也就是下面这个东东(网页地址是https://matplotlib....
- 小白学Python笔记:第二章 Python安装
-
Windows操作系统的python安装:Python提供Windows、Linux/UNIX、macOS及其他操作系统的安装包版本,结合自己的使用情况,此处仅记录windows操作系统的python...
- Python程序开发之简单小程序实例(9)利用Canvas绘制图形和文字
-
Python程序开发之简单小程序实例(9)利用Canvas绘制图形和文字一、项目功能利用Tkinter组件中的Canvas绘制图形和文字。二、项目分析要在窗体中绘制图形和文字,需先导入Tkinter组...
- 一文吃透Python虚拟环境(python虚拟环境安装和配置)
-
摘要在Python开发中,虚拟环境是一种重要的工具,用于隔离不同项目的依赖关系和环境配置。本文将基于windows平台介绍四种常用的Python虚拟环境创建工具:venv、virtualenv、pip...
- 小白也可以玩的Python爬虫库,收藏一下
-
最近,微软开源了一个项目叫「playwright-python」,作为一个兴起项目,出现后受到了大家热烈的欢迎,那它到底是什么样的存在呢?今天为你介绍一下这个传说中的小白神器。Playwright是...
- python环境安装+配置教程(python安装后怎么配置环境变量)
-
安装python双击以下软件:弹出一下窗口需选择一些特定的选项默认选项不需要更改,点击next勾选以上选项,点击install进度条安装完毕即可。到以下界面,证明安装成功。接下来安装库文件返回电脑桌面...
- colorama,一个超好用的 Python 库!
-
大家好,今天为大家分享一个超好用的Python库-colorama。Github地址:https://github.com/tartley/coloramaPythoncolorama库是一...
- python制作仪表盘图(python绘制仪表盘)
-
今天教大家用pyecharts画仪表盘仪表盘(Gauge)是一种拟物化的图表,刻度表示度量,指针表示维度,指针角度表示数值。仪表盘图表就像汽车的速度表一样,有一个圆形的表盘及相应的刻度,有一个指针...
- 总结90条写Python程序的建议(python写作)
-
1.首先 建议1、理解Pythonic概念—-详见Python中的《Python之禅》 建议2、编写Pythonic代码 (1)避免不规范代码,比如只用大小写区分变量、使用容易...
- [oeasy]python0137_相加运算_python之禅_import_this_显式转化
-
变量类型相加运算回忆上次内容上次讲了是从键盘输入变量input函数可以有提示字符串需要有具体的变量接收输入的字符串输入单个变量没有问题但是输入两个变量之后一相加就非常离谱添加图片注释,不超过1...
- Python入门学习记录之一:变量(python中变量的规则)
-
写这个,主要是对自己学习python知识的一个总结,也是加深自己的印象。变量(英文:variable),也叫标识符。在python中,变量的命名规则有以下三点:>变量名只能包含字母、数字和下划线...
- 掌握Python的"魔法":特殊方法与属性完全指南
-
在Python的世界里,以双下划线开头和结尾的"魔法成员"(如__init__、__str__)是面向对象编程的核心。它们赋予开发者定制类行为的超能力,让自定义对象像内置类型一样优雅工...
- 11个Python技巧 不Pythonic 实用大于纯粹
-
虽然Python有一套强大的设计哲学(体现在“Python之禅”中),但总有一些情况需要我们“打破规则”来解决特定问题。这触及了Python哲学中一个非常核心的理念:“实用主义胜于纯粹主义”...
- Python 从入门到精通 第三课 诗意的Python之禅
-
导言:Python之禅,英文名是TheZenOfPython。最早由TimPeters在Python邮件列表中发表,它包含了影响Python编程语言设计的20条软件编写原则。它作为复活节彩蛋...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python字典遍历 (54)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (60)
- python读取文件夹下所有文件 (59)
- java调用python脚本 (56)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)