python小游戏-移动木板

article/2025/8/24 1:02:43

文章目录

  • 一、游戏简介
  • 二、编写步骤
    • 1.引入库
    • 2.初始化
    • 3.相关自定义函数
    • 4.相关自定义函数


一、游戏简介

本游戏是通过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 = Truewhile 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] // 2y = SCREEN_SIZE[1] - barsize[1]# ball 初始位置ball_pos_pz = ball_poswhile True:bar_move_left = Falsebar_move_right = False###当每次满X分后,升级等级if count_O != count_N and score % 5 == 0:c_level += 1count_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 = Truex_change = -30else:bar_move_left = False##右移动if event.key == pygame.K_RIGHT:bar_move_right = Truex_change = +30else:bar_move_right = Falseif event.key != pygame.K_LEFT and event.key != pygame.K_RIGHT:bar_move_left = Falsebar_move_right = False##木板的位置移动if bar_move_left == True and bar_move_right == False:x += x_changeif 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 = xpygame.draw.rect(screen, WHITE, bar_pos)## 球移动,并渲染在前台ball_pos_pz.bottom += ball_dir_y * 3pygame.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  # 分数每次加1count_N += 1elif 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 randompygame.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 = Truewhile 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] // 2y = SCREEN_SIZE[1] - barsize[1]# ball 初始位置ball_pos_pz = ball_poswhile True:bar_move_left = Falsebar_move_right = False###当每次满X分后,升级等级if count_O != count_N and score % 5 == 0:c_level += 1count_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 = Truex_change = -30else:bar_move_left = False##右移动if event.key == pygame.K_RIGHT:bar_move_right = Truex_change = +30else:bar_move_right = Falseif event.key != pygame.K_LEFT and event.key != pygame.K_RIGHT:bar_move_left = Falsebar_move_right = False##木板的位置移动if bar_move_left == True and bar_move_right == False:x += x_changeif 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 = xpygame.draw.rect(screen, WHITE, bar_pos)## 球移动,并渲染在前台ball_pos_pz.bottom += ball_dir_y * 3pygame.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  # 分数每次加1count_N += 1elif 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()

http://chatgpt.dhexx.cn/article/41kaIVVp.shtml

相关文章

UDP over Socks5 实现全局透明代理

Socks5代理协议很强大&#xff0c;不光可以实现HTTP/HTTPS代理的TCP隧道代理功能&#xff0c;类似connect&#xff0c;还可以实现HTTP代理不能做到的UDP代理功能。 要知道UDP代理的重要过程&#xff0c;以方便我们排查错误&#xff0c;我们还需要了解Socks5协议对UDP代理方式的…

阿里P7测开岗大手子手把手教你【软件测试秘籍】

本人阿里CTO线测试开发岗&#xff0c;入职阿里系已有两年&#xff0c;从事软件测试岗位五年有余。双非一本计算机系出身&#xff0c;大佬说不上&#xff0c;今天跟学弟学妹分享一下我这几年的学习软件测试心得。 一、 熟练使用SQL 常用的 sql 语句一定会写。比如说增删改查之类…

软件测试人员必备的60个测试工具清单,建议收藏一波~

据统计&#xff0c;中国软件外包市场的潜力和机会已远远超过软件王国印度&#xff0c;不过由于软件人才的严重不足致使我国软件发展遭遇“瓶颈”。国家为了大力培养软件人才&#xff0c;不断采取积极有效的措施。我国对软件测试人才的需求数量还将持续增加&#xff0c;因此软件…

软件测试精华总结,入门到精通全流程(必看,知识点很全)

软件测试基础 软件测试的概念 通过一系列手段去证明软件是符合用户需求的,满足质量要求的。预期结果和实际结果的一个对比。 软件测试分类 按方法分:黑盒测试、白盒测试、灰盒测试 黑盒测试:把软件比作一个“黑匣子”,不考虑具体是内部是如何实现的,只考虑外部功能的运行…

400 页共计 800 道软件测试面试真题汇总,2022年吐血整理

800 道软件测试面试真题&#xff0c;高清打印版打包带走&#xff0c;横扫软件测试面试高频问题&#xff0c;涵盖测试理论、Linux、MySQL、Web 测试、接口测试、App 测试、Python、Selenium、性能测试、LordRunner、计算机网络、数据结构与算法、逻辑思维、人力资源等模块面试题…

软件测试人员必备的60个测试工具清单,果断收藏了!

前言 据统计&#xff0c;中国软件外包市场的潜力和机会已远远超过软件王国印度&#xff0c;不过由于软件人才的严重不足致使我国软件发展遭遇“瓶颈”。国家为了大力培养软件人才&#xff0c;不断采取积极有效的措施。我国对软件测试人才的需求数量还将持续增加&#xff0c;因…

软件测试面试题集(含答案)

软件测试面试题集 一、Bug基本要素 缺陷ID&#xff0c;状态&#xff0c;类型&#xff0c;所属项目&#xff0c;所属模块&#xff0c;缺陷提交时间&#xff0c;缺陷提交人&#xff08;检测者&#xff09;&#xff0c;严重程度&#xff0c;优先级别&#xff0c;缺陷描述信息&…

常用的软件测试工具清单,建议收藏。

常用的测试工具有10类&#xff1a; 1.测试管理工具 2.接口测试工具 3.性能测试工具 4.C/S自动化工具 5.白盒测试工具 6.代码扫描工具 7.持续集成工具 8.网络测试工具 9.app自动化工具 10.web安全测试工具 1.测试管理工具 1&#xff0c;TestDirector(大而全) 2&…

什么是软件测试,软件测试究竟是做什么的

我犹豫了很久&#xff0c;想来想去还是写了一篇文章&#xff0c;这篇文章可以告诉你什么是软件测试&#xff1f; 来看看官方的回答&#xff1a; 软件测试(英语&#xff1a;Software Testing)&#xff0c;描述一种用来促进鉴定软件的正确性、完整性、安全性和质量的过程。换句话…

swiper自定义分页器使用

解决问题&#xff1a;不想使用swiper的自带的圆钮式的分页器&#xff0c;想使用自定义的分页器。 解决方案&#xff1a;利用swiper提供的paginationCustomRender()方法&#xff08;自定义特殊类型分页器&#xff0c;当分页器类型设置为自定义时可用。&#xff09; 下面的代码可…

element-ui 分页器的使用

1. ui组件 1.在element-ui找到Paginaion分页器 打开代码拷贝第四个组件 2. 在vue template里写 //分页区 <el-pagination size-change"handleSizeChange" current-change"handleCurrentChange":current-page"queryInfo.pagenum" :page-size…

分页器的使用-1 自己找的分页器插件

这个插件是自己网上找的&#xff0c;具体代码如下&#xff1a; 具体步骤&#xff1a;1. 先引入css和js2. 分页器放在请求成功之后&#xff0c;3. 最重要的中间件就是currentPage&#xff1a;当前页码。4. 具体代码详情都在里面写清楚了。用到的js文件&#xff1a; https://pa…

vue实战-分页器

vue实战-分页器 1.分页器静态组件 因为是公共全局组件&#xff0c;在components里新建文件夹Pagination&#xff0c;并将分页器的静态组件填入 静态组件 <template><div class"pagination"><button>1</button><button>上一页</b…

html分页器的实现原理,js分页器详解

本文主要和大家分享js分页器详解,我们先来看一下效果,希望能帮助到大家。 依赖于:bootstrap 和 jquery html代码:通过class="pj_pager"引用,pj_total初始化总条数 js代码:/** * 分页器,依赖于bootstrap,jquery */ var pager = {init : function(r) {this.obj …

JavaScript--Swiper自定义分页器

图片是以背景显示的&#xff0c;图片上有一层遮罩&#xff0c;最上面是文字。分页器激活状态下是自定义的图片。代码比较容易进行删改&#xff0c;比如不想要遮罩或者文字可以直接删掉。 分页器的效果&#xff1a; html <!DOCTYPE html> <html lang"en"…

快速实现-简单分页器(上)

首先形形色色的分页器大家肯定都看过,这一次就快速实现一个简单的分页器,应该不会耽搁太久吧~ 先来看一下简洁布局: 瞜一眼这布局: 页码数量总共只有9个当足够显示所有页码的情况就全部显示了那么问题来了,如果不够呢? 第一种情况 第二种情况 第三种情况

完整分页器最骚的讲解(亲测)

咱也不敢问&#xff0c;咱也不敢说。先来个图瞅瞅分页器是个什么鬼叭 就目前来讲&#xff0c;这应该算是功能最全的分页器啦吧 下面我们一步一步研究一下这玩意怎么玩叭 啥也不说了&#xff0c;先去element-ui官网嫖代码吧哈哈哈 <el-paginationsize-change"handleS…

用vue封装分页器,让你的页面简单而不失优雅

前言 当我们在开发 web 应用时&#xff0c;经常需要对大量数据进行分页展示&#xff0c;这时候用到的就是分页器。element 是一款流行的前端 ui 框架&#xff0c;它提供了许多有用的工具和组件&#xff0c;其中就包括分页器组件。在本文中&#xff0c;我们将学习如何使用 vue 基…

js分页器

写分页器的时候引用别人的js总是不能达到自己想要的效果&#xff0c;在这里记录下自制分页器的历程 html部分 <!DOCTYPE html> <html> <head><title></title><meta charset"utf-8" /><script src"https://code.jquery…

flutter自定义分页器

使用flutter自定义一个分页器 最近在写flutter项目&#xff0c;项目刚好需要一个分页器&#xff0c;对数据进行分页处理&#xff0c;一开始想要在网上找有没有已经写好的插件&#xff0c;搜寻一会后还是想着自己写一个。 先看看效果图 思路 首先要准备一个盒子&#xff0c;装载…