当前位置:网站首页>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
边栏推荐
- Excel intercept text
- ESP32 LVGL8. 1 - slider slider (slider 22)
- 深入理解 Golang 中的 new 和 make 是什么, 差异在哪?
- 教你用简单几个步骤快速重命名文件夹名
- STM32: LCD显示
- Keil RVMDK compiled data type
- After CANopen starts PDO timing transmission, the heartbeat frame time is wrong, PDO is delayed, and CANopen time axis is disordered
- Sentinel rule persistence into Nacos
- C language simulates entering and leaving the stack, first in first out, first in first out, shared memory
- Interpretation and compilation of JVM
猜你喜欢
On iptables
七、DOM(下) - 章节课后练习题及答案
昇腾 AI 开发者创享日全国巡回首站在西安成功举行
函数递归以及趣味问题的解决
Setting up keil environment of GD single chip microcomputer
Introduction to quantexa CDI syneo platform
Summary of actual business optimization scheme - main directory - continuous update
Kettle paoding jieniu Chapter 17 text file output
Résolution: cnpm: impossible de charger le fichier... Cnpm. PS1 parce que l'exécution de scripts est désactivée sur ce système
ctfshow-web361(SSTI)
随机推荐
Fundamentals of machine learning theory -- some terms about machine learning
Druid SQL和Security在美团点评的实践
ESP32 LVGL8. 1 - slider slider (slider 22)
ESP32 LVGL8. 1. Detailed migration tutorial of m5stack + lvgl + IDF (27)
CISSP certified daily knowledge points (April 11, 2022)
Hard core parsing promise object (do you know these seven common APIs and seven key questions?)
STM32: LCD显示
Setting up keil environment of GD single chip microcomputer
Excel intercept text
Mysql database backup command -- mysqldump
Ionic 从创建到打包指令集顺序
CANopen usage method and main parameters of object dictionary
Creation and use of QT dynamic link library
If condition judgment in shell language
Machine learning practice - naive Bayes
Database computer experiment 4 (data integrity and stored procedure)
WiFi ap6212 driver transplantation and debugging analysis technical notes
iptables -L执行缓慢
函数递归以及趣味问题的解决
数据库上机实验四(数据完整性与存储过程)