python实现移动木板小游戏


Posted in Python onOctober 09, 2020

本文实例为大家分享了python实现移动木板小游戏的具体代码,供大家参考,具体内容如下

一、游戏简介

本游戏是通过python编写的小游戏,给初学者熟悉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模块顶层运行的代码引起的一个Bug
Jul 04 Python
Python线程详解
Jun 24 Python
Python中的模块导入和读取键盘输入的方法
Oct 16 Python
python实现按任意键继续执行程序
Dec 30 Python
python入门前的第一课 python怎样入门
Mar 06 Python
python实现几种归一化方法(Normalization Method)
Jul 31 Python
Python 下载及安装详细步骤
Nov 04 Python
nginx+uwsgi+django环境搭建的方法步骤
Nov 25 Python
python 在sql语句中使用%s,%d,%f说明
Jun 06 Python
Python如何设置指定窗口为前台活动窗口
Aug 12 Python
python引入其他文件夹下的py文件具体方法
May 23 Python
python3中apply函数和lambda函数的使用详解
Feb 28 Python
详解Python中Pyyaml模块的使用
Oct 08 #Python
Python实现七个基本算法的实例代码
Oct 08 #Python
python自动化测试三部曲之request+django实现接口测试
Oct 07 #Python
python自动化测试三部曲之unittest框架的实现
Oct 07 #Python
浅谈anaconda python 版本对应关系
Oct 07 #Python
简述python&amp;pytorch 随机种子的实现
Oct 07 #Python
详解基于python的全局与局部序列比对的实现(DNA)
Oct 07 #Python
You might like
ThinkPHP利用PHPMailer实现邮件发送实现代码
2013/09/26 PHP
PHP获取一年有几周以及每周开始日期和结束日期
2015/08/06 PHP
设置下载不需要倒计时cookie(倒计时代码)
2008/11/19 Javascript
JavaScript的Module模式编程深入分析
2013/08/13 Javascript
JS复制到剪贴板示例代码
2013/10/30 Javascript
javascript常见用法总结
2014/05/22 Javascript
jquery delay()介绍及使用指南
2014/09/02 Javascript
javascript自定义右键弹出菜单实现方法
2015/05/25 Javascript
jquery+CSS实现的水平布局多级网页菜单效果
2015/08/24 Javascript
js滑动提示效果代码分享
2016/03/10 Javascript
使用jQuery制作Web页面遮罩层插件的实例教程
2016/05/26 Javascript
Angularjs 实现一个幻灯片示例代码
2016/09/08 Javascript
JavaScript原生节点操作小结
2017/01/17 Javascript
JavaScript 事件流、事件处理程序及事件对象总结
2017/04/01 Javascript
解决ztree搜索中多级菜单展示不全问题
2017/07/05 Javascript
bootstrap基本配置_动力节点Java学院整理
2017/07/14 Javascript
Node调用Java的示例代码
2017/09/20 Javascript
如何将你的AngularJS1.x应用迁移至React的方法
2018/02/01 Javascript
JavaScript常见鼠标事件与用法分析
2019/01/03 Javascript
[07:57]DOTA2热力大趴狂欢夜 广州站活动回顾
2013/11/27 DOTA
python每隔N秒运行指定函数的方法
2015/03/16 Python
通过数据库向Django模型添加字段的示例
2015/07/21 Python
致Python初学者 Anaconda入门使用指南完整版
2018/04/05 Python
Python函数的参数常见分类与用法实例详解
2019/03/30 Python
TensorFlow基于MNIST数据集实现车牌识别(初步演示版)
2019/08/05 Python
Pycharm内置终端及远程SSH工具的使用教程图文详解
2020/03/19 Python
python安装后的目录在哪里
2020/06/21 Python
HTML5 常见面试题之PC端和移动端区别介绍
2018/01/22 HTML / CSS
高级方案规划工程师岗位职责
2013/11/29 职场文书
宣传策划类求职信范文
2014/01/31 职场文书
商铺租赁意向书
2014/04/01 职场文书
企业文化口号
2014/06/12 职场文书
优秀团员事迹材料
2014/12/25 职场文书
违规违纪检讨书范文
2015/05/06 职场文书
实施意见格式范本
2015/06/05 职场文书
SQL Server表分区降低运维和维护成本
2022/04/08 SQL Server