python小游戏-移动木板

文章目录

  • 一、游戏简介
  • 二、编写步骤
    • 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://xiahunao.cn/news/142950.html

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

MySQL——子查询

来一篇 MySQL-子查询 记录一下这个美好的时光,学习记录篇,下文中所有SQL 语句 均可在 MySQL DB 学习Demo 此处下载SQL语句执行,有相关DB 与 表。 1. 需求分析与问题解决 1.1 实际问题 现有解决方式一: SELECT salary FROM employees WHERE last_name = Abel SELECT last…

谈谈linux网络编程中的应用层协议定制、Json序列化与反序列化那些事

linux【网络编程】之协议定制、序列化与反序列化 一、序列化与反序列化二、应用层协议如何定制三、网络通信中数据流动的本质四、网络版计算器编写4.1 业务流程4.2 核心代码 一、序列化与反序列化 由于socket api的接口&#xff0c;在读写数据的时候是以字符串的方式发送接收的…

python配置arcpy环境

在pycharm配置arcpy让其导入不出现没有arcpy这个模块我们会进行环境配置 。 第一步 第二步 第三步 第四部 然后找到你arcgis安装的位置 记住如果你重名了arcgis安装位置的名字一定要进入到arcpy安装目录中找一个文件 查看Arcgis安装目录下的 E:\ArcGIS\Python27\ArcGIS10.2\L…

Python配置CPLEX

大致的安装步骤如下 1.百度搜索CPLEX&#xff0c;进入官网&#xff0c;获取许可后&#xff0c;下载并安装&#xff08;要能找到自己的安装路径&#xff09; 2.安装完成后&#xff0c;可以直接用ide进行编程&#xff0c;但是&#xff0c;还可以用Python来调用CPLEX 3.给Pytho…

Python:环境变量配置方法 详细教程

最近有人问我如何配置python环境变量&#xff0c;这篇文章就向大家介绍python环境变量配置方法。 python环境变量的配置方法&#xff1a;首先鼠标右键此电脑&#xff0c;选择属性&#xff1b;然后点击高级系统设置&#xff0c;点击环境变量&#xff1b;接着点击path进行编辑&am…

vscode配置python路径_Vscode的python配置(macOS)

1. Vscode是一款开源的跨平台编辑器。默认情况下&#xff0c;vscode使用的语言为英文(en)&#xff0c;以下步骤改为中文 打开vscode工具&#xff0c;使用快捷键组合【CmdShiftp】&#xff0c;在搜索框中输入“configure display language”&#xff0c;点击确定后&#xff0c;…

python环境配置教程

一、下载和安装软件 进入python官网&#xff0c;下载所需的python版本 进入pycharm官网&#xff0c;下载社区版即可 两个软件安装&#xff0c;基本安装默认配置即可&#xff0c;选择环境变量时建议选一下&#xff08;或者后面自行添加&#xff09; 二、建立代码项目 本地建…

pycharm配置python环境

文章目录 安装pycharm安装pythonpycharm配置python,并激活pycharm界面运行一下取消更新 安装pycharm PyCharm 的下载地址&#xff1a;http://www.jetbrains.com/pycharm/download/#sectionwindows 版本分为community(社区版)和professional(专业版) 1.选择专业版安装 点击I…

MacOS配置Python环境

python简介 Python是用来编写应用程序的高级编程语言。 Python就为我们提供了非常完善的基础代码库&#xff0c;覆盖了网络、文件、GUI、数据库、文本等大量内容&#xff0c;被形象地称作“内置电池&#xff08;batteries included&#xff09;”。 用Python开发&#xff0c;许…

Sublime配置Python环境步骤

零、配置python3环境 打开 Tools > Build System > New Build System 输入以下内容 {//"shell_cmd": "make""cmd": ["D:/Python/python.exe","-u","$file"],"file_regex": "^[ ]*File \&…

python配置Anaconda3环境运行python

1.安装Anaconda3 链接&#xff1a;Anaconda | Anaconda Distribution 点击NXET 点击I Agree 选择第一个 自己更改存储位置 选择第二个 2.下载Pycharm 我目前使用的是2021.1专业版&#xff0c;下载去官网&#xff0c;安装也很简单&#xff0c;就不多说了。 配置 1、打开…

神器 VS Code,超详细Python配置使用指南

作者&#xff1a;Lemon 出品&#xff1a;Python数据之道 神器 VS Code&#xff0c; 超详细Python配置使用指南 大家好&#xff0c;我是 Lemon。 之前在公众号发了关于 PyCharm 与 VS Code 对比的文章&#xff0c;大家也是很有感慨。 鉴于 PyCharm 是收费的工具&#xff0c;不少…

Python配置镜像源的三种方法

1.常用镜像源 先分享一些比较好的镜像源&#xff1a; 清华&#xff1a;https://pypi.tuna.tsinghua.edu.cn/simple 阿里云&#xff1a;http://mirrors.aliyun.com/pypi/simple/ 中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/ 华中理工大学&#xff1a;http://pypi.…

Mac下终端 pip及 Python 配置

文章目录 1、Mac两个bin目录2、Mac的终端的用户可配置文件3、查看位置命令实例 4、Python 相关配置5、删除/usr/local/bin 目录下指向的Python3.7 的连接&#xff1a;6、将Python3设置为系统默认Python Python 三方库地址&#xff1a;https://pypi.org 1、Mac两个bin目录 相同点…

手把手教你们Python配置OpenCV环境,小白看一遍就会了☀️《❤️记得收藏❤️》

手把手教你们Python配置OpenCV环境&#xff0c;小白看一遍就会了☀️《❤️记得收藏❤️》 &#x1f3f3;️‍&#x1f308;目录&#x1f3f3;️‍&#x1f308;1、简介&#x1f648;1.1、Opecv介绍&#x1f649;1.2、Opecv应用的行业 &#x1f3f3;️‍&#x1f308;2、Python…

python环境变量配置

python现在的版本&#xff0c;主要是python2和python3两个大版本&#xff0c;这两个版本有很大的不同。 当我们在自己电脑上同时安装了python2.x和python3.x版本的解释器的时候&#xff0c;就需要对环境变量的配置进行一定的修改。 【大概解释一下&#xff0c;我对环境变量的…

python配置到系统环境中

作者介绍&#xff1a; ♥️作者&#xff1a;小刘在C站 ♥️每天分享课堂笔记&#xff0c;一起努力&#xff0c;共赴美好人生&#xff01; ♥️夕阳下&#xff0c;是最美的绽放。 目录 一.回顾 二.解释 三.将python配置到环境中 步骤1 步骤2 步骤3 步骤4 步骤5 步骤6 步骤…

python环境配置不成功_怎么解决python配置环境变量不成功

怎么解决python配置环境变量不成功 发布时间&#xff1a;2020-08-25 16:02:46 来源&#xff1a;亿速云 阅读&#xff1a;94 这期内容当中小编将会给大家带来有关怎么解决python配置环境变量不成功&#xff0c;文章内容丰富且以专业的角度为大家分析和叙述&#xff0c;阅读完…

已解决Python配置环境变量失效问题

已解决&#xff08;安装python解释器配置环境变量后&#xff0c;在cmd内运行报错问题&#xff09;‘pyhton‘不是内部或外部命令&#xff0c;也不是可运行的程序或批处理文件。 文章目录 报错代码报错原因解决方法千人全栈VIP答疑群联系博主帮忙解决报错 报错代码 粉丝群里面的…

Sublime下的python配置

Sublime下的python配置 1. python配置 打开Sublime选择工具下的编译系统&#xff0c;点击新建编译系统 复制下面的代码&#xff0c;CtrlS保存文件&#xff0c;保存到默认的文件夹命名为python3.sublime-build {"cmd":["python.exe", "-u", &q…