当前位置:网站首页>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
边栏推荐
- K210串口通信
- Nacos作为服务注册中心
- [mathematical modeling] - analytic hierarchy process (AHP)
- Database computer experiment 4 (data integrity and stored procedure)
- iptables初探
- C language simulates entering and leaving the stack, first in first out, first in first out, shared memory
- Use stm32cube MX / stm32cube ide to generate FatFs code and operate SPI flash
- Seata处理分布式事务
- [popular science] CRC verification (I) what is CRC verification?
- Iptables - L executes slowly
猜你喜欢

Use of regular expressions in QT

Use bitnami / PostgreSQL repmgr image to quickly set up PostgreSQL ha

Multifunctional toolbox wechat applet source code

Creation and use of QT dynamic link library

视频边框背景如何虚化,简单操作几步实现

STM32: LCD display

Ctfshow - web362 (ssti)

Use bitnami / PostgreSQL repmgr image to quickly set up PostgreSQL ha

七、DOM(下) - 章节课后练习题及答案

Kettle paoding jieniu Chapter 17 text file output
随机推荐
程序员如何快速开发高质量的代码?
Nacos as service registry
迁移学习进阶
Use Chenxi bookkeeping book to analyze the balance of revenue and expenditure of each account in a certain period of time
Hard core parsing promise object (do you know these seven common APIs and seven key questions?)
CISSP certified daily knowledge points (April 12, 2022)
Seata处理分布式事务
机器学习理论之(7):核函数 Kernels —— 一种帮助 SVM 实现非线性化决策边界的方式
Introduction to quantexa CDI syneo platform
回路-通路
Nacos作为服务注册中心
使用 bitnami/postgresql-repmgr 镜像快速设置 PostgreSQL HA
ESP32 LVGL8. 1 - BTN button (BTN 15)
特征选择feature_selection--SelectKBest
7、 DOM (Part 2) - chapter after class exercises and answers
使用晨曦记账本,分析某个时间段每个账户收支结余
Interpretation and compilation of JVM
iptables初探
STM32: LCD display
kettle庖丁解牛第17篇之文本文件输出