程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python-pygame與pymunk-倒塌解壓金字塔

編輯:Python
金字塔

 大家好,我是涵子。是不是很久沒有更新了呢?今天,我要來為大家帶來——倒塌金字塔!

百度網盤:鏈接: https://pan.baidu.com/s/1qTjJ0JXwYgQiF_SAAkBFDQ 提取碼: kvqn

Csdn文庫:鏈接:python-pygame與pymunk-倒塌解壓金字塔-其他文檔類資源-CSDN文庫


目錄

一、提前准備

二、中間代碼

三、最後程序

四、完整代碼

五、效果圖

五、總結

六、花絮


一、提前准備

今天,我們要特殊一點了:

# -coding utf-8 -
# author: BruceCodeFarmer
# article:csdn
# py file:csdn
# time: 2022/7/18
# name:code-5-2-10_pygame_FallingBlocks
# version: 1.20
"""
We use pygame, pymunk, pymunk.pygame_util, sys and Vec2d.
Please pip first.
Open setup.bat can pip all packages.
Path:
Open Zip, and open setup.bat, click enter when system needs
Or open cmd, then pip all the things you need.
Packages:
Pygame, Pymunk, sys, math
Need Pip First:
Pygame, Pymunk
Tips for everyone:
# do not transshipment my code or article if you haven't got my permission
# if you want transshipment, please talk with me on csdn
# if you want have code or zip, please download by csdn '涵子碼農-什麼語言都想學的程序員'
# if you see anyone transshipment my article or code, please tell me
#i f you see anything cannot read or know, you can ask me.
@ csdn BruceCodeFarmer 涵子碼農-什麼語言都想學的程序員
You can get my permission in 2022/7/25 to 2023/7/25
"""
# import pygame ,pymunk, pymunk.pygame_util, Vec2d and sys
import pygame as pg
import pymunk as pm
import pymunk.pygame_util as pu
import sys
import math
from pymunk import Vec2d
# we didn't use init again
# set screen
screen = pg.display.set_mode((600, 600)) # cannot change the size of the screen
# pymunk Space
space = pm.Space()
# gravity
# gravity and speed
space.gravity = (0, 900)
# points
points = [(-10,-10),(-10,10),(10,10),(10,-10)]# position

是不是很難。首先,我們不用pygame.init()了,因為我們現在用的是pymunk與pygame的結合體,也就是pymunk.pygame_util了。

然後就是Vec2d,這就是向量!

二、中間代碼

這裡更是像苦痛之路。

# def main
def main():
# global first
global draw_options
"""
In mathematics, a vector (also known as a Euclidean vector, geometric vector, or vector), is a quantity with magnitude and direction.
It can be visually represented as a line segment with an arrow.
Arrow points to: represents the direction of the vector; Segment length: represents the size of the vector.
The quantity corresponding to a vector is called a quantity (scalar in physics), and a quantity (or scalar) has only magnitude and no direction.
Vector notation: Printed as bold letters (such as A, B, U, V), with a small arrow "→" at the top of the letter.
If A vector is given its starting point (A) and ending point (B), we can call the vector AB (and add → to the top).
Vectors can also be expressed as pairs of numbers in the spatial cartesian coordinate system, for example in the xOy plane (2,3) is a vector.
In physics and engineering, geometric vectors are more commonly referred to as vectors.
Many physical quantities are vectors, such as the displacement of an object, the force exerted on a ball when it hits a wall, and so on.
The opposite of this is a scalar, a quantity that has magnitude but no direction.
Some vector-related definitions are also closely related to physical concepts, for example,
vector potential corresponds to potential energy in physics.
The concept of geometric vectors is abstracted in linear algebra to give rise to the more general concept of vectors.
Here vectors are defined as elements of vector space.
It should be noted that these abstract vectors are not necessarily represented by pairs of numbers,
nor do the concepts of size and direction apply.
Therefore, it is necessary to distinguish the concept of "vector" according to the context in daily reading.
However, it is still possible to find a basis for a vector space to set the coordinate system, and it is also possible,
by choosing an appropriate definition, to introduce the norm and inner product on the vector space,
which allows us to compare abstract vectors to concrete geometric vectors.
---From BaiduBaike
---Website path: https://baike.baidu.com/item/%E5%90%91%E9%87%8F/1396519?fr=aladdin
---Translate by YouDao translater
"""
# pm.Segment
ground = pm.Segment(space.static_body, (0, 500), (600, 500), 3)
# friction
ground.friction = 1
# add ground
space.add(ground)
# input
draw_options = pu.DrawOptions(screen)
# use Vec2d
a = Vec2d(540,490)
dx = Vec2d(10,20)
dy = Vec2d(20,0)
# it is difficult here.
# draw a pyramid by range
for i in range(25):
b = Vec2d(*a)
for j in range(25-i):
# create body!
body = pm.Body(1,2000)
body.position = b
rect = pm.Poly(body,points)
rect.friction = 1
# add body
space.add(body,rect)
# check pos
b -= dx
# check pos again
a-=dy
"""
steps:
1. create body
2. set body's pos
3. create poly
4. set poly's friction
5. add these things into pymunk's space
these steps can use to make a thing has gravity
Vec2d is a difficult step.
"""
# these steps must remind
# def draw
def draw():
# fill
screen.fill((255,255,255))
# debug_draw
space.debug_draw(draw_options)
# step
space.step(1/60)
# display
pg.display.update()
# def dis
# use the pythagorean theorem again
def dis(a, b):
return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5
# also can use math.sqrt
# def click
def click():
# get pressed
if pg.mouse.get_pressed()[0]:
# mPos
mPos = pg.mouse.get_pos()
# use range
for i in range(len(space.bodies)):
# check if touch rect...
# analogy and ignores
if dis(mPos, space.bodies[i].position) < 10:
# remove bodies and shapes
space.remove(space.bodies[i])
# need i + 1
space.remove(space.shapes[i+1])
# need break
break

首先,我們要搞懂什麼是向量。下面內容又來自百度百科。

在數學中,向量(也稱為歐幾裡得向量、幾何向量、矢量),指具有大小(magnitude)和方向的量。它可以形象化地表示為帶箭頭的線段。箭頭所指:代表向量的方向;線段長度:代表向量的大小。與向量對應的量叫做數量(物理學中稱標量),數量(或標量)只有大小,沒有方向。

向量的記法:印刷體記作黑體(粗體)的字母(如abuv),書寫時在字母頂上加一小箭頭“→”。  如果給定向量的起點(A)和終點(B),可將向量記作AB(並於頂上加→)。在空間直角坐標系中,也能把向量以數對形式表示,例如xOy平面中(2,3)是一向量。

在物理學和工程學中,幾何向量更常被稱為矢量。許多物理量都是矢量,比如一個物體的位移,球撞向牆而對其施加的力等等。與之相對的是標量,即只有大小而沒有方向的量。一些與向量有關的定義亦與物理概念有密切的聯系,例如向量勢對應於物理中的勢能。

幾何向量的概念在線性代數中經由抽象化,得到更一般的向量概念。此處向量定義為向量空間的元素,要注意這些抽象意義上的向量不一定以數對表示,大小和方向的概念亦不一定適用。因此,平日閱讀時需按照語境來區分文中所說的"向量"是哪一種概念。不過,依然可以找出一個向量空間的基來設置坐標系,也可以透過選取恰當的定義,在向量空間上介定范數和內積,這允許我們把抽象意義上的向量類比為具體的幾何向量。

 額,是很難。Vec就是向量,2D就是指2維平面中的向量。

然後從右下角往上畫小方塊。小方塊的創建方法和之前的台球一樣。

好了,我們接下來定義畫函數。裡面用了debug_draw等*@#()@)()¥*!@#¥()*

好吧,我看到了你們疑惑的眼神了。

 接下來我們看看click函數

click函數可以判斷是否按下左鍵,按下了就可以刪掉球。用for循環來判斷,如果判斷到了附近的正方形。如果用dis函數判斷到了距離在10裡就刪掉。然後break,否則要報錯。

dis函數老相識了。就是勾股定理。這次可以用**0.5來代替math.sqrt

三、最後程序

# check fps and events
fps = pg.time.Clock()
# use main
main()
while True:
# tick fps
fps.tick(60)
# quit events
event = pg.event.poll()
if event.type==pg.QUIT:
pg.quit()
sys.exit()
# if pressed
if pg.mouse.get_pressed()[2]:
# delete
# must use *list, or wrong
space.remove(*space.bodies)
space.remove(*space.shapes)
main()
# set title with fps:n
# must use string
pg.display.set_caption("fps: " + str(fps.get_fps()))
# use draw
draw()
# use click
click()

和之前的差不多,就是之前要提前用一下main,然後在判斷右鍵,按下了就remove所有的正方形,還要重組一遍,但要記住,在remove的時候要在前面加一個*,否則要報錯。然後再給標題更改一下,改成fps:n,最後就是用draw和click。pygame.display.update()不用寫了!

四、完整代碼

奉上完整代碼:

# -coding utf-8 -
# author: BruceCodeFarmer
# article:csdn
# py file:csdn
# time: 2022/7/18
# name:code-5-2-10_pygame_FallingBlocks
# version: 1.20
"""
We use pygame, pymunk, pymunk.pygame_util, sys and Vec2d.
Please pip first.
Open setup.bat can pip all packages.
Path:
Open Zip, and open setup.bat, click enter when system needs
Or open cmd, then pip all the things you need.
Packages:
Pygame, Pymunk, sys, math
Need Pip First:
Pygame, Pymunk
Tips for everyone:
# do not transshipment my code or article if you haven't got my permission
# if you want transshipment, please talk with me on csdn
# if you want have code or zip, please download by csdn '涵子碼農-什麼語言都想學的程序員'
# if you see anyone transshipment my article or code, please tell me
#i f you see anything cannot read or know, you can ask me.
@ csdn BruceCodeFarmer 涵子碼農-什麼語言都想學的程序員
You can get my permission in 2022/7/25 to 2023/7/25
"""
# import pygame ,pymunk, pymunk.pygame_util, Vec2d and sys
import pygame as pg
import pymunk as pm
import pymunk.pygame_util as pu
import sys
import math
from pymunk import Vec2d
# we didn't use init again
# set screen
screen = pg.display.set_mode((600, 600)) # cannot change the size of the screen
# pymunk Space
space = pm.Space()
# gravity
# gravity and speed
space.gravity = (0, 900)
# points
points = [(-10,-10),(-10,10),(10,10),(10,-10)]# position
# def main
def main():
# global first
global draw_options
"""
In mathematics, a vector (also known as a Euclidean vector, geometric vector, or vector), is a quantity with magnitude and direction.
It can be visually represented as a line segment with an arrow.
Arrow points to: represents the direction of the vector; Segment length: represents the size of the vector.
The quantity corresponding to a vector is called a quantity (scalar in physics), and a quantity (or scalar) has only magnitude and no direction.
Vector notation: Printed as bold letters (such as A, B, U, V), with a small arrow "→" at the top of the letter.
If A vector is given its starting point (A) and ending point (B), we can call the vector AB (and add → to the top).
Vectors can also be expressed as pairs of numbers in the spatial cartesian coordinate system, for example in the xOy plane (2,3) is a vector.
In physics and engineering, geometric vectors are more commonly referred to as vectors.
Many physical quantities are vectors, such as the displacement of an object, the force exerted on a ball when it hits a wall, and so on.
The opposite of this is a scalar, a quantity that has magnitude but no direction.
Some vector-related definitions are also closely related to physical concepts, for example,
vector potential corresponds to potential energy in physics.
The concept of geometric vectors is abstracted in linear algebra to give rise to the more general concept of vectors.
Here vectors are defined as elements of vector space.
It should be noted that these abstract vectors are not necessarily represented by pairs of numbers,
nor do the concepts of size and direction apply.
Therefore, it is necessary to distinguish the concept of "vector" according to the context in daily reading.
However, it is still possible to find a basis for a vector space to set the coordinate system, and it is also possible,
by choosing an appropriate definition, to introduce the norm and inner product on the vector space,
which allows us to compare abstract vectors to concrete geometric vectors.
---From BaiduBaike
---Website path: https://baike.baidu.com/item/%E5%90%91%E9%87%8F/1396519?fr=aladdin
---Translate by YouDao translater
"""
# pm.Segment
ground = pm.Segment(space.static_body, (0, 500), (600, 500), 3)
# friction
ground.friction = 1
# add ground
space.add(ground)
# input
draw_options = pu.DrawOptions(screen)
# use Vec2d
a = Vec2d(540,490)
dx = Vec2d(10,20)
dy = Vec2d(20,0)
# it is difficult here.
# draw a pyramid by range
for i in range(25):
b = Vec2d(*a)
for j in range(25-i):
# create body!
body = pm.Body(1,2000)
body.position = b
rect = pm.Poly(body,points)
rect.friction = 1
# add body
space.add(body,rect)
# check pos
b -= dx
# check pos again
a-=dy
"""
steps:
1. create body
2. set body's pos
3. create poly
4. set poly's friction
5. add these things into pymunk's space
these steps can use to make a thing has gravity
Vec2d is a difficult step.
"""
# these steps must remind
# def draw
def draw():
# fill
screen.fill((255,255,255))
# debug_draw
space.debug_draw(draw_options)
# step
space.step(1/60)
# display
pg.display.update()
# def dis
# use the pythagorean theorem again
def dis(a, b):
return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5
# also can use math.sqrt
# def click
def click():
# get pressed
if pg.mouse.get_pressed()[0]:
# mPos
mPos = pg.mouse.get_pos()
# use range
for i in range(len(space.bodies)):
# check if touch rect...
# analogy and ignores
if dis(mPos, space.bodies[i].position) < 10:
# remove bodies and shapes
space.remove(space.bodies[i])
# need i + 1
space.remove(space.shapes[i+1])
# need break
break
# check fps and events
fps = pg.time.Clock()
# use main
main()
while True:
# tick fps
fps.tick(60)
# quit events
event = pg.event.poll()
if event.type==pg.QUIT:
pg.quit()
sys.exit()
# if pressed
if pg.mouse.get_pressed()[2]:
# delete
# must use *list, or wrong
space.remove(*space.bodies)
space.remove(*space.shapes)
main()
# set title with fps:n
# must use string
pg.display.set_caption("fps: " + str(fps.get_fps()))
# use draw
draw()
# use click
click()

五、效果圖

金字塔

五、總結

通過這次學習 ,我們有進一步了解了python-pymunk和pygame的宇宙和厲害。我們不僅學習了如何把這兩個毫不相關的庫結合在了一起。希望大家可以玩得快樂,學得更深!

六、花絮

計算機與網絡-day3-“硅與電腦的帝國”——硅谷(2)即將更新!

神秘人:你期待嗎?希望我可以為你帶來更多驚喜!

好了,大家再見! 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved