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

Python pyGame and pymunk collapse decompression pyramid

編輯:Python
The pyramid

  Hello everyone , I'm Hanzi . Hasn't it been updated for a long time ? today , I want to bring you —— Collapse pyramid !

Baidu SkyDrive : link : https://pan.baidu.com/s/1qTjJ0JXwYgQiF_SAAkBFDQ Extraction code : kvqn

Csdn library : link :python-pygame And pymunk- Collapse decompression pyramid - Other document resources -CSDN library


Catalog

One 、 Prepare in advance

Two 、 Intermediate code

3、 ... and 、 Final procedure

Four 、 Complete code

5、 ... and 、 design sketch

5、 ... and 、 summary

6、 ... and 、 trivia


One 、 Prepare in advance

today , We need to be special :

# -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 ' Han zi Ma Nong - Programmers who want to learn any language '
# 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 Han zi Ma Nong - Programmers who want to learn any language
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

Isn't it hard . First , We don't have to pygame.init() 了 , Because we're using pymunk And pygame The combination of , That is to say pymunk.pygame_util 了 .

Then is Vec2d, This is the vector !

Two 、 Intermediate code

It's more like the road of pain .

# 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

First , We need to understand what a vector is . The following content comes from Baidu Encyclopedia .

In mathematics , vector ( Also known as Euclidean vectors 、 Geometric vectors 、 vector ), Of having size (magnitude) And the amount of direction . It can be visualized as a line with an arrow . The 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 quantity ( In physics, it is called Scalar ), Number ( Or scalar ) Only in size , No direction .

Notation of vectors : Print is marked in bold ( bold ) The letter of ( Such as abuv), When writing, add a small arrow at the top of the letter “→”.   If you give the starting point of the vector (A) And the end (B), The vector can be written as AB( And add →). stay Space rectangular coordinate system in , You can also take a vector as Number pair The form , for example xOy In plane (2,3) Is a vector .

In physics and engineering in , Geometric vectors are more often called vectors . many physical quantity All vectors , For example, of an object Displacement , The force exerted by the ball hitting the wall force wait . The opposite is Scalar , That is, the quantity with only size but no direction . Some definitions related to vectors are also closely related to physical concepts , For example, the vector potential corresponds to potential energy .

The concept of geometric vector is linear algebra Through abstraction , Get a more general concept of vector . Here the vector is defined as Vector space The elements of , Note that these abstract vectors are not necessarily expressed in pairs , The concepts of size and direction are not necessarily applicable . therefore , When reading on weekdays, you need to distinguish what is said in the text according to the context " vector " What kind of concept is it . however , You can still find a base of vector space to set Coordinate system , You can also choose an appropriate definition , Define in vector space norm and Inner product , This allows us to compare a vector in the abstract sense to a specific geometric vector .

  forehead , It's hard .Vec It's a vector ,2D Is refers to 2 Vector in dimensional plane .

Then draw a small square from the lower right corner . The method of creating small squares is the same as that of billiards before .

Okay , Next, we define the drawing function . It's used inside. debug_draw etc. *@#()@)()¥*!@#¥()*

ok , I saw your confused eyes .

  Now let's see click function

click Function can determine whether to press the left key , Press it to delete the ball . use for Loop to judge , If you judge the square nearby . If you use dis The function judges that the distance is 10 Delete in . then break, Otherwise, an error will be reported .

dis Functions are familiar . It's the Pythagorean theorem . This time you can use **0.5 Instead of math.sqrt

3、 ... and 、 Final procedure

# 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()

It's about the same as before , Just use it in advance main, Then right click on the judgment , Press it remove All squares , We need to reorganize again , But remember, , stay remove When adding a *, Otherwise, an error will be reported . Then change the title , Change to fps:n, In the end, I use draw and click.pygame.display.update() Don't write !

Four 、 Complete code

With the full code :

# -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 ' Han zi Ma Nong - Programmers who want to learn any language '
# 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 Han zi Ma Nong - Programmers who want to learn any language
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()

5、 ... and 、 design sketch

The pyramid

5、 ... and 、 summary

Through this study  , We have learned more python-pymunk and pygame Universe and power . We not only learned how to combine these two unrelated libraries . I hope you can have a good time , Learn more !

6、 ... and 、 trivia

Computers and networks -day3-“ The Empire of silicon and computers ”—— Silicon valley (2) Will be updated soon !

Mysterious man : Are you looking forward to ? I hope I can bring you more surprises !

Okay , Goodbye, everyone ! 


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