python-pygame与pymunk-台球游戏
大家好,我是涵子。今天我为大家带来pygame-pymunk的台球游戏!
友情提醒:
如果不认识pymunk的同学可以去看看之前的文章:
python-编程宇宙-计算机网络的宇宙https://blog.csdn.net/B20111003/article/details/125540816?spm=1001.2014.3001.5502希望大家可以更加了解pymunk!
目录
一、前面准备
二、中间程序
三、最后程序
四、效果图
五、完整代码
六、总结
一、前面准备
和之前一样,就是加了一个pymunk和一些变量:
# -coding utf-8 -
# import pygame, pymunk and sys
import pygame as pg
import pymunk as pm
import sys# init program
pg.init()
# set screen
screen = pg.display.set_mode((800, 500)) # cannot change the size of the screen
# set title
pg.display.set_caption("Billiards", "4.0")# pymunk Space
space = pm.Space()
# gravity
# gravity and speed
space.gravity = (0, 0) # gravity = 0# colors for draw
white = (236, 240, 241) # white
gray = (123, 125, 125) # gray
stage = (51, 51, 51) # stagepoints = [""] * 16 # particleBallsballs = [""] * 16 # rigid bodiesy = 0 # Yposx = 0 # Xposn = 5 # create n# colors, use for balls
colors = ["yellow", "blue", "red", "purple", "orange", "green", "brown", "black", "yellow", "blue", "red", "purple", "orange", "green", "brown","white"]
pymunk.sapce和gravity是啥?没事,我们来看看:
这就是用pymunk做的一个程序。之前的文章里有代码。
space就是指一个空间,gravity就是重力。我们不需要重力。
二、中间程序
# def draw
def draw():# screen fillscreen.fill(white)# draw stagepg.draw.line(screen, gray, (0, 250), (800, 250), 500)pg.draw.line(screen, stage, (20, 250), (780, 250), 460)# draw a ball in the pygame, pos is the points' and balls'# make the ball has gravity# show the ball# use rangefor i in range(16):# if it appears, then--# if it doesn't, don't draw it, or system wrongif points[i]:# --draw circlepg.draw.circle(screen, colors[i], points[i].position, 10)# update space, can change ball's positionspace.step(0.2) # use space.step# create holes this list
holes = [(20,20),(400,20),(780,20),(20,480),(400,480),(780,480)]# def drawHole
def drawHole():# use loopfor h in holes:# draw circlepg.draw.circle(screen,'gray',h,20)# def dis
def dis():# global firstglobal points,balls# use loopfor i,p in enumerate(points):# check posfor h in holes:# checkif p and (p.position[0]-h[0])**2+(p.position[1]-h[1])**2<400:# make the ball disappearpoints[i] = ""balls[i] = ""# def friction
def friction():# make the balls speed be slower and slower# global first!global pointsfor v in points:# if v is appearif v:# then make the speed slowerv.velocity *= 0.99# def cue
def cue():# get white ball speed(velocity)# it is a little bit difficult# if abs(speed) < 0.1, the do next# because of there will have -num, so we need abs!# first need loop!# staticflagstaticFlag = 1for i in points:# check# switch thinking is on again!if i and (abs(i.velocity[0]) > 0.1 or abs(i.velocity[1]) > 0.1):# there's a ball is running!staticFlag = 0# then checkif points[15] and staticFlag == 1:# get posmPos = pg.mouse.get_pos()# draw cuepg.draw.line(screen,(249,231,159),points[15].position,mPos,5)# get if pressedif pg.mouse.get_pressed()[0]:# move ball and cue, and boom!# wallop!points[15].apply_impulse_at_local_point(((points[15].position[0]-mPos[0]),(points[15].position[1]-mPos[1])),(0,0))# create balls
# def create
def create():# global first, or system errorglobal points,balls# create y, x, ny = 0x = 0n = 5# create balls of particle balls and rigid bodiesfor i in range(15):# creat particle balls and rigid bodiespoints[i] = pm.Body(1,2000)points[i].position = 150+x,250+y-n*10balls[i] = pm.Circle(points[i],10)# elasticityballs[i].elasticity = 0.95space.add(points[i],balls[i])y+=20# check posif y>=20*n:# change yy = 0# change xx +=20# chang nn-=1# create white ballpoints[15] = pm.Body(1,2000)points[15].position = 450,250balls[15] = pm.Circle(points[15],10)balls[15].elasticity = 0.95space.add(points[15],balls[15])# def wall
def wall():# create a wall# it umm... difficult, not very easy for everyone# it just like a air wall# put these static_body wall into a listlines = [pm.Segment(space.static_body,(10,10),(790,10),20),pm.Segment(space.static_body,(10,10),(10,490),20),pm.Segment(space.static_body,(790,10),(790,490),20),pm.Segment(space.static_body,(10,490),(790,490),20)]# use range to check linesfor line in lines:# elasticityline.elasticity = 1# frictionline.friction = 0.9space.add(*lines) # add lines
额,好长是不?
没事,我慢慢讲。(此时我已经开始颤抖)
注释里有,自己去翻译吧!
首先,遇到的问题就是画画。
# def draw
def draw():# screen fillscreen.fill(white)# draw stagepg.draw.line(screen, gray, (0, 250), (800, 250), 500)pg.draw.line(screen, stage, (20, 250), (780, 250), 460)# draw a ball in the pygame, pos is the points' and balls'# make the ball has gravity# show the ball# use rangefor i in range(16):# if it appears, then--# if it doesn't, don't draw it, or system wrongif points[i]:# --draw circlepg.draw.circle(screen, colors[i], points[i].position, 10)# update space, can change ball's positionspace.step(0.2) # use space.step
首先画好外面的边框,填满里面的颜色,然后再画出里面的球(后面的程序衔接上这个函数)。可是有一个问题,为什么要有if points[i],你想想,要是球掉洞里了还会出现吗?
然后面临的问题是画洞和判断球进去了没。
# create holes this list
holes = [(20,20),(400,20),(780,20),(20,480),(400,480),(780,480)]# def drawHole
def drawHole():# use loopfor h in holes:# draw circlepg.draw.circle(screen,'gray',h,20)# def dis
def dis():# global firstglobal points,balls# use loopfor i,p in enumerate(points):# check posfor h in holes:# checkif p and (p.position[0]-h[0])**2+(p.position[1]-h[1])**2<400:# make the ball disappearpoints[i] = ""balls[i] = ""
这里用到了enumerate,额,有难了点哈。
想让球消失,那就把i索引的东西删掉(就是变成一个空字符串)
下面就是噩梦了!(苦痛之路)
# def friction
def friction():# make the balls speed be slower and slower# global first!global pointsfor v in points:# if v is appearif v:# then make the speed slowerv.velocity *= 0.99# def cue
def cue():# get white ball speed(velocity)# it is a little bit difficult# if abs(speed) < 0.1, the do next# because of there will have -num, so we need abs!# first need loop!# staticflagstaticFlag = 1for i in points:# check# switch thinking is on again!if i and (abs(i.velocity[0]) > 0.1 or abs(i.velocity[1]) > 0.1):# there's a ball is running!staticFlag = 0# then checkif points[15] and staticFlag == 1:# get posmPos = pg.mouse.get_pos()# draw cuepg.draw.line(screen,(249,231,159),points[15].position,mPos,5)# get if pressedif pg.mouse.get_pressed()[0]:# move ball and cue, and boom!# wallop!points[15].apply_impulse_at_local_point(((points[15].position[0]-mPos[0]),(points[15].position[1]-mPos[1])),(0,0))# create balls
# def create
def create():# global first, or system errorglobal points,balls# create y, x, ny = 0x = 0n = 5# create balls of particle balls and rigid bodiesfor i in range(15):# creat particle balls and rigid bodiespoints[i] = pm.Body(1,2000)points[i].position = 150+x,250+y-n*10balls[i] = pm.Circle(points[i],10)# elasticityballs[i].elasticity = 0.95space.add(points[i],balls[i])y+=20# check posif y>=20*n:# change yy = 0# change xx +=20# chang nn-=1# create white ballpoints[15] = pm.Body(1,2000)points[15].position = 450,250balls[15] = pm.Circle(points[15],10)balls[15].elasticity = 0.95space.add(points[15],balls[15])# def wall
def wall():# create a wall# it umm... difficult, not very easy for everyone# it just like a air wall# put these static_body wall into a listlines = [pm.Segment(space.static_body,(10,10),(790,10),20),pm.Segment(space.static_body,(10,10),(10,490),20),pm.Segment(space.static_body,(790,10),(790,490),20),pm.Segment(space.static_body,(10,490),(790,490),20)]# use range to check linesfor line in lines:# elasticityline.elasticity = 1# frictionline.friction = 0.9space.add(*lines) # add lines
包含了摩擦力,球杆控制和墙体的定义。
看到了这里,还不点个赞?(非强迫,喜欢就点)
接下来就是干货!(此时要有bgm响起!)
和之前一样用循环遍历所有球,如果有球就减速。没有的话就跳过。接下来$%!)@(*#@$(*&
算了,我已经看见了你们满脸的疑惑。来,我还是慢慢来吧!
这里又一次运用到了开关思维。实在不行的同学直接跳过。到达最后的完整代码就可以了。
太难了是不?
接下来就是用上质点和刚体组成现实(游戏)中的球。相当于用pymunk做出原子核,用pygame泼油漆,做模型。
后面用segment和列表把墙体加入游戏。
后面就是结尾了!
三、最后程序
# use wall
wall()# create balls before loop, or boom, or system wrong
create()
# check fps and events
fps = pg.time.Clock()
while True:# tick fpsfps.tick(60)# quit eventsevent = pg.event.poll()if event.type==pg.QUIT:pg.quit()sys.exit()exit()# main programdis()draw()friction()cue()drawHole()# display programpg.display.update()
好像平平无奇是吗?挺简单的是吗?额,的确是的。
就是调用函数,检查程序退出。
四、效果图
牛皮吧?
五、完整代码
附上完整代码:
# -coding utf-8 -
# import pygame, pymunk and sys
import pygame as pg
import pymunk as pm
import sys# init program
pg.init()
# set screen
screen = pg.display.set_mode((800, 500)) # cannot change the size of the screen
# set title
pg.display.set_caption("Billiards", "4.0")# pymunk Space
space = pm.Space()
# gravity
# gravity and speed
space.gravity = (0, 0) # gravity = 0# colors for draw
white = (236, 240, 241) # white
gray = (123, 125, 125) # gray
stage = (51, 51, 51) # stagepoints = [""] * 16 # particleBallsballs = [""] * 16 # rigid bodiesy = 0 # Yposx = 0 # Xposn = 5 # create n# colors, use for balls
colors = ["yellow", "blue", "red", "purple", "orange", "green", "brown", "black", "yellow", "blue", "red", "purple", "orange", "green", "brown","white"]# def draw
def draw():# screen fillscreen.fill(white)# draw stagepg.draw.line(screen, gray, (0, 250), (800, 250), 500)pg.draw.line(screen, stage, (20, 250), (780, 250), 460)# draw a ball in the pygame, pos is the points' and balls'# make the ball has gravity# show the ball# use rangefor i in range(16):# if it appears, then--# if it doesn't, don't draw it, or system wrongif points[i]:# --draw circlepg.draw.circle(screen, colors[i], points[i].position, 10)# update space, can change ball's positionspace.step(0.2) # use space.step# create holes this list
holes = [(20,20),(400,20),(780,20),(20,480),(400,480),(780,480)]# def drawHole
def drawHole():# use loopfor h in holes:# draw circlepg.draw.circle(screen,'gray',h,20)# def dis
def dis():# global firstglobal points,balls# use loopfor i,p in enumerate(points):# check posfor h in holes:# checkif p and (p.position[0]-h[0])**2+(p.position[1]-h[1])**2<400:# make the ball disappearpoints[i] = ""balls[i] = ""# def friction
def friction():# make the balls speed be slower and slower# global first!global pointsfor v in points:# if v is appearif v:# then make the speed slowerv.velocity *= 0.99# def cue
def cue():# get white ball speed(velocity)# it is a little bit difficult# if abs(speed) < 0.1, the do next# because of there will have -num, so we need abs!# first need loop!# staticflagstaticFlag = 1for i in points:# check# switch thinking is on again!if i and (abs(i.velocity[0]) > 0.1 or abs(i.velocity[1]) > 0.1):# there's a ball is running!staticFlag = 0# then checkif points[15] and staticFlag == 1:# get posmPos = pg.mouse.get_pos()# draw cuepg.draw.line(screen,(249,231,159),points[15].position,mPos,5)# get if pressedif pg.mouse.get_pressed()[0]:# move ball and cue, and boom!# wallop!points[15].apply_impulse_at_local_point(((points[15].position[0]-mPos[0]),(points[15].position[1]-mPos[1])),(0,0))# create balls
# def create
def create():# global first, or system errorglobal points,balls# create y, x, ny = 0x = 0n = 5# create balls of particle balls and rigid bodiesfor i in range(15):# creat particle balls and rigid bodiespoints[i] = pm.Body(1,2000)points[i].position = 150+x,250+y-n*10balls[i] = pm.Circle(points[i],10)# elasticityballs[i].elasticity = 0.95space.add(points[i],balls[i])y+=20# check posif y>=20*n:# change yy = 0# change xx +=20# chang nn-=1# create white ballpoints[15] = pm.Body(1,2000)points[15].position = 450,250balls[15] = pm.Circle(points[15],10)balls[15].elasticity = 0.95space.add(points[15],balls[15])# def wall
def wall():# create a wall# it umm... difficult, not very easy for everyone# it just like a air wall# put these static_body wall into a listlines = [pm.Segment(space.static_body,(10,10),(790,10),20),pm.Segment(space.static_body,(10,10),(10,490),20),pm.Segment(space.static_body,(790,10),(790,490),20),pm.Segment(space.static_body,(10,490),(790,490),20)]# use range to check linesfor line in lines:# elasticityline.elasticity = 1# frictionline.friction = 0.9space.add(*lines) # add lines# use wall
wall()# create balls before loop, or boom, or system wrong
create()
# check fps and events
fps = pg.time.Clock()
while True:# tick fpsfps.tick(60)# quit eventsevent = pg.event.poll()if event.type==pg.QUIT:pg.quit()sys.exit()exit()# main programdis()draw()friction()cue()drawHole()# display programpg.display.update()
六、总结
通过这次学习和实践,我们更加了解了pymunk和pygame,认识到了python的强大。
最后,我希望大家:点个赞!关注一下。
我将持续更新关于编程的优质文章。希望大家可以和我一起学习知识,一起领略知识的力量!
python-pygame与pymunk-台球游戏相关推荐
- 运用Python+Pygame开发坦克大战游戏_版本V1.01
这里写目录标题 一.项目整体说明 二.pygame下载方式 三.项目文件 1.坦克大战_框架_1.py 2.坦克大战_开始游戏_窗口设置_2.py 3.坦克大战_事件检测_3.py 4.坦克大战_基本 ...
- python pygame模块怎么写游戏_使用 Python 和 Pygame 模块构建一个游戏框架
这系列的第一篇通过创建一个简单的骰子游戏来探究 Python.现在是来从零制作你自己的游戏的时间. 在我的这系列的第一篇文章 中, 我已经讲解如何使用 Python 创建一个简单的.基于文本的骰子游戏 ...
- Python Pygame制作简单五子棋游戏(详细代码+解释)
这里只想简单演示下一个简单的五子棋界面和落子等操作,主要为了后面设计AI对战方便演示,AI算法后面设计吧,最近事太多了,,,,. 希望本文有助于你制作自己期望的简单的五子棋. 一.pygame初始化画 ...
- python:pygame制作童年的游戏打砖块
目录 程序源代码 程序源代码 # /usr/bin/python3# Author: 爱编程的章老师 # @Time: 2021/1/9 0009 # E-mail: Bluesand2010@163 ...
- 【四二学堂】基于python+pygame的太空阻击游戏(python版带视频)
csdn课程视频地址:https://edu.csdn.net/course/detail/28487 import pygame from pygame.locals import* from sy ...
- 用Python编了一个鱿鱼游戏
用Python编了一个鱿鱼游戏 关键词:python, pygame, squid game, 鱿鱼游戏 python 源代码下载:点击下载squidgame1.zip文件 python 开源项目地址 ...
- 编写五子棋的完整python代码_python实现五子棋游戏(pygame版)
本文实例为大家分享了python五子棋游戏的具体代码,供大家参考,具体内容如下 目录 简介 实现过程 结语 简介 使用python实现pygame版的五子棋游戏: 环境:Windows系统+pytho ...
- python自己制作节奏大师游戏_使用pygame制作一个简单的游戏
翻译自Will McGugan的<Beginning Game Development with Python and Pygame –From Novice to Professional&g ...
- python贪吃蛇设计目标_基于 pygame 设计贪吃蛇游戏
基于 pygame 设计贪吃蛇游戏 贪吃蛇游戏通过玩家控制蛇移动,不断吃到食物增长,直到碰到蛇身或边界游戏结束.其运行效果如下所示: 游戏开始时,先导入可能需要用到的包. import time im ...
- Python实验,用pygame做飞机大战游戏设计
飞机大战游戏设计 摘 要:根据课程要求,以及面向对象程序设计的编程思想,在Windows操作系统环境下,运用PyCharm编译程序,以Python语言为开发语言,最终实现飞机大战游戏相应的游戏操作功能 ...
最新文章
- Hdu_2063 过山车 -最大匹配(邻接表版)
- 【问题收录】在ubuntu14.04 64位下运行jd-gui
- DEDECMS v5.5 GBK Final 的一个鸡肋漏洞
- [基础]Linux文件说明
- Xavier初始化和He初始化
- 模糊c均值聚类_六种常用的文本聚类方法介绍
- Spring中的Bean的生命周期
- 2018/3/1 省选模拟考试 50分
- MS Script Control的 COM
- c# 再次尝试 连接失败_手机投屏电视连接不上怎么回事?
- jQuery的Select操作集合
- Quartz 触发器(SimpleTriggerCronTrigger )配置说明 cronExpression表达式 转
- [密码学]如何生成PKCS8密钥
- 一个被忽视的强大搜图技能——以图搜图
- js【点击 div 2s 后颜色变成『粉色」】
- 【黑盒测试用例设计方法5】正交试验法及其示例
- 魔兽TBC常用WA字符串收集
- EMI的主要原因-共模电流
- 完美实现无毛边异形窗体
- Java基础篇之利用IO流给文件加密、解密