Preface
I had put Python aside for half a year. After the midterm exams, we'll soon be covering the basics of algorithms. I believe that thinking in Python significantly helps with learning algorithms, so I spent a few hours writing this little game called KillAliens.
The two most important parts are persistent reading/writing and computation of scores and generation of random events. Next, I'll explain in detail how to implement the entire KillAliens game and these two parts.
Based on
This KillAliens game is inspired by a simple text-based game I wrote long ago called 击杀外星人.py, which was less than 30 lines. In KillAliens, the scoring system is something 击杀外星人.py didn't have. It also uses dictionaries, mapping each type of Alien to its own score via key-value pairs.
You can find 击杀外星人.py in my Python learning repository.
Supplement
This little game was first written on 2022/5/14. After some research, I modified the algorithm on 2022/5/19 to improve thread performance. The old code is named KillAliens.py or KillAliens_NoComment.py in the repository, and the new code is named KillAliens_V2.py or KillAliens_NoComment_V2.py.
Output Preview
Code Preview
Code Analysis
Analysis Notes
The code analysis in this article mainly covers the key syntax used; it won't analyze every line in detail—that's for you to figure out.
Comments
In Python, comments are marked with the hash symbol, i.e., #. Everything after the hash is ignored by the Python interpreter. The code included in this article has no functional comments, only author comments.
Module Imports
Lines 9-10 import the random and time modules.
import random
import time
These two modules are used for random processing and making the Python thread sleep for a specified time, respectively.
The usage of random was covered in Python Learning Diary – Coordinate Movement #random module, so I won't go into it again here.
The time module's function is to make the Python thread sleep for a specified time, measured in seconds. Let's try it:
name = input("你的名字:")
time.sleep(1)
print(f"你好{name}")
Here's the output:
In the code above, the first line executes immediately when the Python thread starts, asking for the name. After getting the user's input, the second line executes, and the Python interpreter receives the instruction to sleep for 1 second. After the thread sleeps for 1 second, it continues to the third line and prints the name.
Dictionaries and the for Statement
In Python, a dictionary is enclosed in curly braces { } and contains two parts: keys and values, which we call key-value pairs. Each key corresponds to a value. In KillAliens, lines 12-17 form a dictionary, and line 18 is another dictionary. These two dictionaries are written differently but are both dictionaries with no difference. The format in lines 12-17 is for aesthetics, as we are required to write code in a standardized way in Python—a good habit.
Using a dictionary makes it convenient for the for statement to output. Let's write a dictionary and a for statement to output:
For easier viewing and learning, I've written each key-value pair on separate lines. Output:
In the for statement, there is a strict order: name corresponds to the key, money to the value, and items() is used to loop through until there are no more key-value pairs to print.
The print inside the for loop can use the names assigned to the key-value pairs, i.e., name and money, to read the keys and values in the dictionary.
Besides the for statement, dictionaries can also be read and written directly, but this only applies to reading and writing values.
Let's look at reading first:
In print, using { } means reading the content in a specific area, and adding [ ] inside reads a specific value within that area.
In the code above, {name_and_money['Mark']} reads the value 10 corresponding to the key Mark in the name_and_money dictionary. Let's see the output:
Now let's look at writing:
Let's see the output:
Note that, unlike the reading part, I didn't put quotes ' ' around the value. This is because quotes indicate a string, which would require conversion to a float for arithmetic, while no quotes mean it's a pure number that can be used directly in calculations.
Of course, this is arithmetic writing; you can also write directly:
Here we gave an example with a boyfriend, directly overwriting the value associated with the key.
The overwrite uses a string, but numbers work the same way.
Note that such overwrites are permanent.
Let's see what that means:
Output:
Tom serves as a control group; his boyfriend remains Brown. After Mark's change, the for loop reads the updated value.
Advanced if-elif-else
KillAliens uses an advanced form of the if statement, nesting if statements and using the in syntax. Let's take a snippet from KillAliens and modify it for explanation.
To show different results, I ran it multiple times.
In the first run, we went through the if branch, and the randomly picked number was in the control group state_one, so we got success. In the second run, we went through the elif branch, and the random number was not in state_one, so we got failure. In the third run, we entered Magneto, which didn't match any if or elif condition, so it went to else and returned a prompt.
In KillAliens, this effectively prevents the program from crashing when non-existent input is entered.
While Loop
The While loop in KillAliens is used simply; I won't explain it in detail. You can refer to Python3 Loop Statements | Runoob Tutorial for learning.
Conclusion
KillAliens is a relatively complex program I wrote—a simple text-based mini-game. The scoring system, judgment system, and kill system are all implemented purely in Python and are quite complete yet simple. However, these data only exist within the thread, and there's still a lot of room for improvement.