002.04 Tkinter Star Wars

Time:2021-8-27

Subject: 002.04 Tkinter Star Wars



Filing date: September 5, 2019
Update Date: None

Relevant software information:

Win 10 Python 3.7.2 tkinter 8.6

Note: all contents are welcome to be quoted, just indicate the source and author. If there are errors or improper words in this article, please correct them

002.04 Tkinter Star Wars

In order to be more proficient in Tkinter’s application, I decided to use Tkinter to write a game instead of pyGame. In the process, there were many big problems. Finally, I left some known problems. I didn’t want to spend time looking for them, but the whole program ran smoothly



1. Game requirements:

  • In the starry sky, the stars move relative to each other as the spacecraft advances
  • The enemy aircraft group moves left and right and then down. When they encounter the safety line, the player will lose one life; After the enemy aircraft group is completely eliminated, raise the level and speed up again
  • Players can press the left and right keys to move left and right, the space bar can fire bullets, long press can continue to act, press Q to leave the game at any time, and press ESC to pause and resume the game
  • When the bullet hits the enemy plane, they destroy it together and get a point

  • The number of levels, scores, and the number of lives left by the player are displayed on the screen

2. Description of procedure writing:

  • Star movement: convert 3D star coordinates (x, y, z) / radius (R) to 2D game screen coordinates (x0, Y0) / radius (R0)

    factor = x - here
    x0 = y/factor
    y0 = z/factor
    r0 = r/factor
  • Spacecraft and enemy aircraft

    First, create a background transparent image file (. PNG), and the transparent point value of its alpha layer is 0. Only when the image moves on the background, can only the image body be displayed, and the planet movement of the background will not be obscured. The image can be placed or moved freely in the window. The Tkinter method is as follows:
    Root = TK () # create window
  • Planets and bullets:

    Basically, it is represented by drawing a circle. The coordinates of the upper left corner (x0, Y0) and the lower right corner (x1, Y1) are filled with color
    canvas.create_ Oval (x0, Y0, x1, Y1, fill = color) # draws an ellipse on the canvas
  • Multithreading control:

    After setting the number of milliseconds to execute the function, it can be started and executed regularly in the following ways. It must be noted that multi threads may cause problems with each other and avoid them as much as possible. Otherwise, it is very difficult to find the problem. In addition to the self movement of the planet, enemy aircraft and bullets, the repeated trigger of keys can also be used. For example, the first trigger of the system itself will be slow, Or the trigger interval does not meet the requirements, or it can be masked by multithreading
    def function():
      pass    # do somthing here
      root.after(time, function)
    root.after(time, function)
  • Collision Detection

    Tkinter can find the objects of all images in a certain area and separate the desired objects in the form of tag_ Image and create_ Add the option tags = “tag” to oval, and we can use the “tag” to find the collision between bullets and enemy aircraft, so as to eliminate the collision between bullets and enemy aircraft
    overlap = canvas.find_ Overlapping (x0, Y0, x1, Y1) # find object list
  • Transparent text:

    The text in the canvas cannot be transparent. I meet the requirements by drawing text in a new transparent image
    font = ImageFont.truetype("filename.ttf", font_ Size) # create font and its size

3. Other instructions

  • IDE

    The pyscript was originally used, but there are often errors in the optional writing program, and the root. Mainloop() in Tkinter often causes no response and cannot be stopped. The only way is to stop the pyscript. In addition, after the program is executed in the pyscript, it will still remain in the system, especially in Tkinter. The result of each execution is different, and worse, it cannot be executed. Therefore, spyder is replaced, The problem is solved, but its debugging function is not as good as pyscript, but in Tkinter, its debugging function is also useless
  • In the process of programming, the most common problems encountered

    Library: first of all, we can’t find the most complete specification. Second, there is no completely consistent definition or usage of all parameters. In addition, each library is someone else’s world, so it’s really difficult to understand all the contents. Therefore, when using, definitions, usage and functions often make mistakes, and the functions are limited by the formulated contents. We often go online to find answers from time to time

    Logic problem: the sequence and mode of event handling often cause difficulties or different problems. For example, using class, function and method to write modules one by one will make the whole process clearer and find problems easier. For example, I wrote about six versions of this game and finally set the tone. Naturally, I wasted a lot of time rewriting, finding problems, debugging, modification, etc

    Known problems: sometimes the bullet launch will stop immediately, but it will not affect the progress of the game. There are no fewer bullets; The index of some lists will be out of range, which will not affect the progress of the game

4. Output screen

002.04 Tkinter Star Wars

5. Procedure description

The following is a complete program, which is divided into two parts. One is the game constant to avoid the frequent declaration of global, so it is placed in another file for easy search and modification. Originally, I wanted to declare variables in the way of config.ini in configparser. Later, I thought it was another topic, so I didn’t go on. However, the content is still kept in the main program read_ In configuration(); The expression function is also added. If it is changed to a = ‘@ B + C’, y can be read and processed; The other is to use exec (public) for global declaration, and exec (command) to execute each line of Python input. There is no description in the program, because the author is tired, ha ha! See quantity, but the variable name used has been used to explain the meaning of the variable as much as possible
# Main file StarWar.py
# pre_ init.py                                                

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Jason Yang