Tank game made with python About the behavior of tanks

I'm studying python and I've been able to make tank behavior very well, so I'll introduce it. The behavior is like how to transcribe the movement of a tank into code. I used python, but I think it's very easy to apply in other languages.

environment

-Python 3.9.0 -I am using pygame (library).

Knowledge to use

・ A little programming knowledge ・ High school physics (mechanics)

Rest assured that high school physics is very easy.


This time, I made two steps to make the movement of the tank. It is ** speed ** and ** direction **. Also, in this game, the w key moves up, the a key moves left, the d key moves right, and the s key moves down.

Speed ​​(position)

When asked what speed is, most people probably think of it as "the distance traveled per unit of time." That's right. It causes this in the code. The formula to learn in physics is

x=a*t^2+b*t+x_0

It's like that. t is the time, x_0 is the first position, and a and b are constants. How can this be expressed in programming? As a general premise, this program calculates the tank position difference for each while loop. Let's call it velocity. Returning to the story, to express this formula in programming, it is a good solution to think of t as the time when the arrow keys are pressed. By using this formula, you will be able to write movements that start slowly. But when I get here, I want you to stop slowly so that there is inertia, so I will play with this formula a little more.

x=a*t^2+b*t+x_0-c*t_stop^2

Added a new section at the end. t_stop is a variable that counts when the key is not pressed and the speed is not 0. By adding this, it will start to move slowly and smoothly as in reality and stop slowly and smoothly.

            pressed_key=pygame.key.get_pressed()
            if speed == 0:
                if pressed_key[K_a]:
                    power_left = 1
                if pressed_key[K_d]:
                    power_right = 1
                if pressed_key[K_w]:
                    power_up = 1
                if pressed_key[K_s]:
                    power_down = 1

            if(pressed_key[K_a] or pressed_key[K_s] or pressed_key[K_d] or pressed_key[K_w]):       #When you press a key
                t += 0.1  #Start measuring time
                t_stop = 0

            else:  #To use inertia when the tank is moving and has speed t_Start measuring stop.
                if speed > 0:
                    t_stop += 0.01
                else:  #Initialize when speed is 0 and no key is pressed
                    t = 0
                    speed = 0
            speed = 20*t*t+1*t-18*t_stop*t_stop  #Calculation of movement speed
            if(speed > 7):  #Maximum speed setting
                speed = 7

Direction

Now that we have calculated the speed in the speed section, we will consider in which direction to allocate that speed. By considering this process, I expressed the inertia when bending. But this formula doesn't follow the laws of physics, so I think there is a better way. However, I think that the inertia of the curve can be expressed with a high degree of accuracy, so please refer to it. First,

    power_left = 1  
    power_right = 1
    power_up = 1
    power_down = 1

And prepare four variables. And

            #Achieve a smooth turn by calculating which rampage the speed is heading for
            #Start processing
            if pressed_key[K_a]:
                power_left += 0.1
                last_key = 2
            elif(power_left > 1):
                power_left -= 0.1
            if pressed_key[K_d]:
                power_right += 0.1
                last_key = 3
            elif(power_right > 1):
                power_right -= 0.1
            if pressed_key[K_w]:
                power_up += 0.1
                last_key = 0
            elif(power_up > 1):
                power_up -= 0.1
            if pressed_key[K_s]:
                power_down += 0.1
                last_key = 1
            elif(power_down > 1):
                power_down -= 0.1
            #Processing Exit

In this way, while the arrow keys are pressed, the values ​​of the four variables are incremented. And finally,

            x -= speed*hit[0]*power_left / \
                (power_left+power_right+power_up+power_down)  #Calculation of actual position
            x += speed*hit[1]*power_right / \
                (power_left+power_right+power_up+power_down)
            y -= speed*hit[2]*power_up/ \
(power_left+power_right+power_up+power_down)
            y += speed*hit[3]*power_down / \
                (power_left+power_right+power_up+power_down)
            #End of tank movement process

x and y are the coordinates of the tank (player). Also, the array called hit here is the return value of the collision judgment, and if it hits an obstacle, this value will be 0 and you will not be able to move. By doing this, we were able to achieve a smooth curve. I was able to transcribe that inertia into the code that wouldn't bend even if I went straight and tried to bend suddenly.

Summary

I made it with great care, so I hope you find it helpful.

Recommended Posts

Tank game made with python About the behavior of tanks
About the behavior of Model.get_or_create () of peewee in Python
About the ease of Python
About the features of Python
Othello game development made with Python
Life game with Python! (Conway's Game of Life)
About the behavior of yield_per of SqlAlchemy
About the basics list of Python basics
Life game with Python [I made it] (on the terminal & Tkinter)
Save the result of the life game as a gif with python
Difference in behavior of transparent Frame made with tkinter in pyinstaller [Python]
[Talking about the drawing structure of plotly] Dynamic visualization with plotly [python]
Calculated the ease of stopping the house of the board game "Bunkers" with Python
Check the behavior of destructor in Python
About the behavior of enable_backprop of Chainer v2
Check the existence of the file with python
About the virtual environment of python version 3.7
I made a roguelike game with Python
Prepare the execution environment of Python3 with Docker
About the behavior of copy, deepcopy and numpy.copy
2016 The University of Tokyo Mathematics Solved with Python
[Note] Export the html of the site with python.
Calculate the total number of combinations with python
Check the date of the flag duty with Python
A note about the python version of python virtualenv
[Note] About the role of underscore "_" in Python
Visualize the behavior of the sorting algorithm with matplotlib
Convert the character code of the file with Python3
About the behavior of Queue during parallel processing
About the * (asterisk) argument of python (and itertools.starmap)
[Python] Determine the type of iris with SVM
I made a bin picking game with Python
[python] behavior of argmax
the zen of Python
Coordinates of the right end of Label made with tkinter
I made a Christmas tree lighting game with Python
Destroy the intermediate expression of the sweep method with Python
Visualize the range of interpolation and extrapolation with python
Calculate the regression coefficient of simple regression analysis with python
Summary of the basic flow of machine learning with Python
Get the operation status of JR West with Python
A reminder about the implementation of recommendations in Python
Extract the band information of raster data with python
I thought about why Python self is necessary with the feeling of a Python interpreter
I tried to find the entropy of the image with python
Try scraping the data of COVID-19 in Tokyo with Python
I made a simple typing game with tkinter in Python
A note about hitting the Facebook API with the Python SDK
The story of implementing the popular Facebook Messenger Bot with python
Unify the environment of the Python development team starting with Poetry
Visualize the results of decision trees performed with Python scikit-learn
About the Python module venv
I made blackjack with python!
Calculate the square root of 2 in millions of digits with python
I wrote the basic grammar of Python with Jupyter Lab
Run the intellisense of your own python library with VScode.
About the enumerate function (python)
I evaluated the strategy of stock system trading with Python.
About various encodings of Python 3
Check the scope of local variables with the Python locals function.
Let's touch the API of Netatmo Weather Station with Python. #Python #Netatmo