当前位置:网站首页>PyGame tank battle
PyGame tank battle
2022-04-23 18:40:00 【Why is it so difficult to name?】
@Pygame Tanks war
This is a 2019 New year West electricity Python Course assignment , Freshman course , Only part of the simple content
Running effect Baidu cloud extraction code : abcd
Source code and material package https://download.csdn.net/download/weixin_43872532/12496334
Python Preview of tank battle effect .mkv
One , Game architecture design
First, determine the classes that need to appear in the game :Tank(My_tank.Enemy_Tank),Missile,wall. At the same time, considering that the shell will explode when it hits the tank , The essence of explosion is to display pictures of constantly enlarged explosion shapes in turn , Set a class to explode explode. At the same time, consider that all classes have common properties , Such as : It's all pictures , Both have the method of displaying pictures on the screen, etc . So set a parent class of all classes Base_item, Therefore, the overall structure of the game is as follows :
Two , Mainly used in this program pygame function
display
: control pygame Show
pygame.display.set_caption(title)
: Sets the title of the current window ;
If the display has a window title , Then this function will change the name on the window . Some systems support alternate shorter titles for minimizing display .
pygame.display.set_mode
: Initialize screens and windows ;
set_mode(resolution =(0,0),flags = 0,depth = 0)
This function will create a display Surface. The parameter passed in is the request for the display type . The display actually created will be the best match supported by the system .
resolution
The parameter is a pair of numbers representing the width and height .flags Parameters are a collection of other options .depth The parameter represents the number of bits used for the color .
# Open a window on the screen
screen_width=700
screen_height=400
screen=pygame.display.set_mode([screen_width,screen_height])
pygame.display.update
: Update the part of the screen to display the software ;
sprite( Spirit group )
:sprite Class is intended to be used as a base class for different types of objects in the game ;
There's another basic one Group
class , It only stores sprite
. Games can create new types of Group
class , These classes are customized in the special that they contain sprite
Run... On the instance .
Basic sprite Class can include sprite Drawn to the surface.
What is the spirit ?
Elves can be thought of as little pictures , A graphic object that can be moved on a screen , And can interact with other graphic objects . Sprite images can be used pygame
Draw the image drawn by the function , It can also be the original image file .
Write your own elf class ,self.image
It can be a rectangle , It can also be a file ( picture 、 String, etc. ). Among them MoveBall
Added the function of animation , use Sprite Class to do animation effect is more convenient .
pygame.sprite.Group()
: Used to save and manage multiple Sprite Object's container class .
pygame.sprite.spritecollide
: If the sprite intersects anything in the group , Then conduct a simple test ;
spritecollideany(sprite,group,collided = None)
Sprite Collide with the returning spirit
spritecollideany(sprite,group,collided = None)
No conflict
If any one of the elves in the group collides with , Then a wizard in the group will be returned . Returns no if there is no conflict . The collision parameter is a callback function , Used to calculate whether two sprites collide . It should take two sprites as values and return a bool value , Indicates whether they collide . If the collision is not transmitted , Then all elves must have “rect” value , This value is the rectangle of the sprite area , Will be used to calculate collisions .
__init__
: Class has a name __init__()
Special method ( Construction method ), This method is called automatically when the class is instantiated , Like this :
def __init__(self): self.data = []
Class definition __init__()
Method , The instantiation of the class will automatically call __init__()
Method .
3、 ... and , Main function
1. Tank movement method move()
2. collision detection stay() And hit()
Move()
The core of the function is the real-time monitoring and calculation of the coordinates of enemy and our tanks , At the same time, record the previous coordinates . Each moving object needs to select a reference point , For convenience, its upper left corner in any state represents the current position of the object , This is also the idea of using particles to represent objects in Physics . We take the top left of the screen as the coordinate origin , The distance from the left side of the screen is named “left”, The distance from the top of the screen is called “top”, Both values are non negative , That is, neither tank nor shell can move to the outside of the screen . After specifying the size of the screen , The corresponding coordinate system in the first quadrant can be established , Let all objects move in the specified area .
Implementation of mobile mode . The first is the movement of the foundation , It is applied to the movement under the control of the player of our tank , It is also the basis for the movement of enemy tanks under program control . Based on one movement , Move in one direction every time you receive a move command 6 Pixel . The frame rate of the main function is 20FPS, In the duration of one frame , The move command can be executed once , Then the moving speed of the tank is 120 Pixels per second . When pressing different direction keys , Will change the direction of the tank , namely top and left Calculation method of . Enemy tanks will move randomly after generation , The mechanism we set is : Each is executed in the same direction 6 After a move command , Random direction conversion , Directional movement again , cycle , Finish the exercise .
Hit()
Implementation of function ,hit() It is used to judge whether the objects in the game collide . The specific detection mechanism is : adopt pygame.sprite.collide_rect() function , Edge detection between objects , If the edges of two objects overlap or just touch , Call... In time stay() Function to get the previous two positions , Modify their coordinate values , This returns the collided object to a state where it did not collide before .
Stay()
function . The function of this function is to record the previous step (front step) The location of , That is, the cache period is one frame , The cache amount of a single object is its set of coordinates .
Four , Commissioning and Debug
1. The bullet cannot disappear when it hits the edge of the screen or when it hits the tank
Question why : With the spacebar pressed , Generate bullet objects separately , Makes bullet deletion problematic
resolvent : Show the bullets in the form of a list , use delete
Methods , As the screen refreshes, the bullet hits the screen or the tank disappears .
2. The font cannot be displayed properly
Question why :pygame.font.SysFont()
The first parameter of does not use a common font library
Solution : Use “simsunnsimsun”
typeface
3. The tank picture cannot be loaded normally
Question why 1. Tank pictures vary in size
2.load()
The function requires the absolute path of the picture , Because everyone has different file paths, this function cannot be loaded normally
resolvent 1: Change the picture resolution to 136*107
resolvent 2: Put the picture and code in the same folder , You can avoid using absolute paths , Then use screen.blit()
Function to render a picture object onto a window
4. Enemy tanks cannot be created randomly
Question why : Start by using the list to create enemy tanks , List append() Functions can only add members at the end , Can't do random generation or not a real random tank
Solution : Use pygame The spirit group concept , Use groups to create enemy tanks . When there are a lot of entities in a program , It's going to be quite a hassle to manipulate these entities
pygame Use sprite group to manage sprite drawing and updating , The sprite group is a simple container . Use pygame.sprite.Group()
Function to create a sprite group :
group = pygame.sprite.Group()
group.add(sprite_one)
版权声明
本文为[Why is it so difficult to name?]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210609243452.html
边栏推荐
- Daily CISSP certification common mistakes (April 15, 2022)
- Seata handles distributed transactions
- ctfshow-web362(SSTI)
- CISSP certified daily knowledge points (April 19, 2022)
- 实战业务优化方案总结---主目录---持续更新
- In shell programming, the shell file with relative path is referenced
- Actual combat of Nacos as service configuration center
- ESP32 LVGL8. 1 - roller rolling (roller 24)
- 机器学习实战 -朴素贝叶斯
- K210 serial communication
猜你喜欢
[mathematical modeling] - analytic hierarchy process (AHP)
Halo 开源项目学习(七):缓存机制
ESP32 LVGL8. 1. Detailed migration tutorial of m5stack + lvgl + IDF (27)
iptables初探
Hard core parsing promise object (do you know these seven common APIs and seven key questions?)
[popular science] CRC verification (I) what is CRC verification?
os_authent_prefix
The first leg of the national tour of shengteng AI developer creation and enjoyment day was successfully held in Xi'an
教你用简单几个步骤快速重命名文件夹名
QT add external font ttf
随机推荐
STM32: LCD display
纠结
Use of regular expressions in QT
With the use of qchart, the final UI interface can be realized. The control of qweight can be added and promoted to a user-defined class. Only the class needs to be promoted to realize the coordinate
Daily network security certification test questions (April 18, 2022)
Database computer experiment 4 (data integrity and stored procedure)
ESP32 LVGL8. 1 - input devices (input devices 18)
QT excel operation summary
ctfshow-web361(SSTI)
使用 bitnami/postgresql-repmgr 镜像快速设置 PostgreSQL HA
os_ authent_ Prefix
K210 serial communication
Interpretation and compilation of JVM
Loop path
昇腾 AI 开发者创享日全国巡回首站在西安成功举行
K210串口通信
【科普】CRC校验(一)什么是CRC校验?
Stm32mp157 wm8960 audio driver debugging notes
ESP32 LVGL8. 1 - anim animation (anim 16)
Iptables - L executes slowly