Preface#
It has been half a year since I put down Python. After the midterm exam, I will soon be involved in the basics of algorithms. I believe that the mindset developed through Python significantly aids in learning algorithms, so I spent a few hours writing this KillAliens mini-game.
The two most important parts are continuous reading and writing of scores and calculations
and generation of random events
. Next, I will detail how to implement the entire KillAliens mini-game and the processes for these two parts.
Based on
This KillAliens mini-game is inspired by a simple script I wrote a long time ago called kill_aliens.py
, which has less than 30 lines of simple text-based gameplay. In KillAliens, the scoring system is something that kill_aliens.py
lacks, and it uses a dictionary to implement a score corresponding to each type of Alien through key-value pairs.
kill_aliens.py
can be found in my Python learning repository.
Supplement#
This mini-game was initially written on 2022/5/14 and modified on 2022/5/19 after research to improve the algorithm and thread performance. The old code is named KillAliens.py
or KillAliens_NoComment.py
in the repository, while the new code is named KillAliens_V2.py
or KillAliens_NoComment_V2.py
.
Output Preview#
Your name:
Magneto
Hello Magneto, let me introduce the Aliens in the game and their corresponding scores!
Killing a Big Alien earns 10 points
Killing a Middle Alien earns 5 points
Killing an A Alien earns 2 points
Killing a Small Alien earns 1 point
Your current score is 0 points
If you want to exit the game, please enter 'quit' to exit, or enter any other value to start (continue) the game.
Start
Please enter the name of the Alien you want to kill to earn the specified score
Name: Big Alien
Corresponding score: 10
Name: Middle Alien
Corresponding score: 5
Name: A Alien
Corresponding score: 2
Name: Small Alien
Corresponding score: 1
Please note that you may not be able to kill the Alien and may end the game as a result, and the higher the corresponding score, the lower the chance of killing.
Please enter the corresponding name:
Small Alien
You chose Small Alien
Congratulations Magneto, you killed successfully and earned 1 point
Current total score: 1 points
Your current score is 1 points
If you want to exit the game, please enter 'quit' to exit, or enter any other value to start (continue) the game.
Continue
Please enter the name of the Alien you want to kill to earn the specified score
Name: Big Alien
Corresponding score: 10
Name: Middle Alien
Corresponding score: 5
Name: A Alien
Corresponding score: 2
Name: Small Alien
Corresponding score: 1
Please note that you may not be able to kill the Alien and may end the game as a result, and the higher the corresponding score, the lower the chance of killing.
Please enter the corresponding name:
Small Alien
You chose Small Alien
Congratulations Magneto, you killed successfully and earned 1 point
Current total score: 2 points
Your current score is 2 points
If you want to exit the game, please enter 'quit' to exit, or enter any other value to start (continue) the game.
Continue
Please enter the name of the Alien you want to kill to earn the specified score
Name: Big Alien
Corresponding score: 10
Name: Middle Alien
Corresponding score: 5
Name: A Alien
Corresponding score: 2
Name: Small Alien
Corresponding score: 1
Please note that you may not be able to kill the Alien and may end the game as a result, and the higher the corresponding score, the lower the chance of killing.
Please enter the corresponding name:
Big Alien
You chose Big Alien
Unfortunately Magneto, you failed to kill the Big Alien, score reset to zero, exiting the game.
Process has ended, exit code 0
Code Preview#
############################
### Date 2022 May 14 ###
### Author Magneto ###
### Name KillAliens <——>
### Facility Windows 11 ###
### Language Python ###
############################
import random
import time
aliens_name_and_mark = {
'Big Alien': 10,
'Middle Alien': 5,
'A Alien': 2,
'Small Alien': 1
}
Data = {'The_name': '', 'The_marks': 0}
state_one = ['1', '2', '3', '4', '5']
print("Welcome to the KillAliens mini-game, the dictionary has been initialized\nPlease enter the content\n")
Data['The_name'] = input("Your name:\n\t")
print(f"Hello \033[94m{Data['The_name']}\033[0m, let me introduce the Aliens in the game and their corresponding scores!\n")
time.sleep(1)
for name, marks in aliens_name_and_mark.items():
print(f"\tKilling {name} earns {marks} points")
time.sleep(1)
while True:
print(f"\nYour current score is \033[35m{Data['The_marks']}\033[0m points")
exit_the_game = input("\nIf you want to exit the game, please enter 'quit' to exit, or enter any other value to start (continue) the game.\n\t")
if exit_the_game == 'quit':
break
print("Please enter the name of the Alien you want to kill \033[94m to earn the specified score")
for name, marks in aliens_name_and_mark.items():
print(f"\tName: {name}\n\t\tCorresponding score: {marks}")
print("Please note that you may not be able to kill the Alien and may end the game as a result, and the higher the corresponding score, the lower the chance of killing.")
time.sleep(1)
ChoiseAliens = input("Please enter the corresponding name:\n\t")
if ChoiseAliens == 'Small Alien':
state_two = ['1', '2', '3', '4', '5', '6', '7', '8']
The_Random = random.choice(state_two)
print("You chose Small Alien")
if The_Random in state_one:
print(f"Congratulations \033[94m{Data['The_name']}\033[0m, you killed successfully and earned 1 point")
Data['The_marks'] += aliens_name_and_mark['Small Alien']
print(f"Current total score: \033[35m{Data['The_marks']}\033[0m points\n\n\n")
else:
print(f"Unfortunately \033[94m{Data['The_name']}\033[0m, you tried to kill Small Alien and failed, score reset to zero, exiting the game.")
break
elif ChoiseAliens == 'A Alien':
state_two = ['1', '2', '3', '6', '7', '8']
The_Random = random.choice(state_two)
print("You chose A Alien")
if The_Random in state_one:
print(f"Congratulations \033[94m{Data['The_name']}\033[0m, you killed successfully and earned 2 points")
Data['The_marks'] += aliens_name_and_mark['A Alien']
print(f"Current total score: \033[35m{Data['The_marks']}\033[0m points\n\n\n")
else:
print(f"Unfortunately \033[94m{Data['The_name']}\033[0m, you tried to kill A Alien and failed, score reset to zero, exiting the game.")
break
elif ChoiseAliens == 'Middle Alien':
state_two = ['1', '2', '6', '7', '8']
The_Random = random.choice(state_two)
print("You chose Middle Alien")
if The_Random in state_one:
print(f"Congratulations \033[94m{Data['The_name']}\033[0m, you killed successfully and earned 5 points")
Data['The_marks'] += aliens_name_and_mark['Middle Alien']
print(f"Current total score: \033[35m{Data['The_marks']}\033[0m points\n\n\n")
else:
print(f"Unfortunately \033[94m{Data['The_name']}\033[0m, you tried to kill Middle Alien and failed, score reset to zero, exiting the game.")
break
elif ChoiseAliens == 'Big Alien':
state_two = ['1', '6', '7', '8']
The_Random = random.choice(state_two)
print("You chose Big Alien")
if The_Random in state_one:
print(f"Congratulations \033[94m{Data['The_name']}\033[0m, you killed successfully and earned 10 points")
Data['The_marks'] += aliens_name_and_mark['Big Alien']
print(f"Current total score: \033[35m{Data['The_marks']}\033[0m points\n\n\n")
else:
print(f"Unfortunately \033[94m{Data['The_name']}\033[0m, you tried to kill Big Alien and failed, score reset to zero, exiting the game.")
break
else:
print("You need to enter the corresponding \033[94mname\033[0m, not something else.")
Code Analysis#
Analysis Explanation#
This code analysis mainly discusses the primary syntax used, without analyzing the function of each line of code, which requires personal understanding.
Comments#
In Python
, comments are marked with a hash
symbol #
. The content after the hash will be ignored by the Python interpreter
. The code provided in this article does not contain functional comments, only author comments.
Module Import
The code in lines 9-10
imports the random
module and the time
module.
import random
import time
The functions of these two modules are random processing and making Python threads sleep for a specified time.
The usage of random
has been discussed in the Python learning diary – Coordinate Movement #random module, so I won't elaborate further here.
The time
module technically makes Python threads sleep for a specified time, and this time is in seconds. Let's try it out:
name = input("Your name:")
time.sleep(1)
print(f"Hello {name}")
This is the output result:
Your name: Magneto
Hello Magneto
In the first line of the above code, after the Python thread starts running, it immediately executes, asking for a name. After receiving the user's input, it executes the second line of code. The Python interpreter receives the instruction in the second line, requiring it to sleep for 1 second, and only after the Python thread has slept for 1 second does it continue executing the third line of code, outputting the name.
Dictionary and for Statement#
In Python, a dictionary is content enclosed in curly braces {}
, which includes two contents: keys (key) and values (value), referred to as key-value pairs. Each key corresponds to a value. In KillAliens, lines 12-17
represent a dictionary, and line 18
is another dictionary. These two dictionaries are written in different formats but are still dictionaries without any difference. The format in lines 12-17
is for aesthetic purposes, as we are required to write code in a standardized manner in Python, which is a good habit.
Using a dictionary makes it convenient for the output of the for statement. Let's write a dictionary and try the output of a for statement:
name_and_money = {
'Mark': '10',
'Tom': '20',
}
for name, money in name_and_money.items():
print(f"{name} has {money} dollars.")
To facilitate viewing and learning, I separated each key-value pair. The output result:
Mark has 10 dollars.
Tom has 20 dollars.
In the for statement, there is a strict correspondence; name
corresponds to the key, and money
corresponds to the value, while items()
is used for looping output until there are no more key-value pairs in the dictionary to print before exiting the loop.
In addition to the for statement, dictionaries can also be read and written directly, but this only applies to reading and writing values.
Let's first look at reading:
# First define the dictionary
name_and_money = {
'Mark': '10',
'Tom': '20',
}
# Let's read the dictionary
print(f"He has {name_and_money['Mark']} dollars")
Using { }
in print
represents reading content from a specific area, while adding [ ]
is to read a specific value within that area.
In the above code, using {name_and_money['Mark']}
reads the value corresponding to the key Mark
in the name_and_money
dictionary, which is 10. Let's see the output result:
He has 10 dollars
Now let's look at writing:
# First define the dictionary
name_and_money = {
'Mark': 10,
'Tom': 20,
}
# Let's read the original dictionary
print(f"He originally had {name_and_money['Mark']} dollars")
# Number +1, i.e., perform calculations
name_and_money['Mark'] += 1
# Let's read the new dictionary
print(f"But now he has {name_and_money['Mark']} dollars")
Let's see the output result:
He originally had 10 dollars
But now he has 11 dollars
It is worth noting that, unlike the reading part, I did not put quotes around this value because adding quotes indicates that this is a string, and we need to convert it to a float to continue calculations. Without quotes, it indicates that this is a pure number that can be calculated directly.
Of course, this is writing through calculations, and we can also write directly:
# First define the dictionary
name_and_boyfriend = {
'Mark': 'Williams',
'Tom': 'Brown',
}
# Let's read the original dictionary
print(f"His ex-boyfriend is {name_and_boyfriend['Mark']}")
# Overwrite the value
name_and_boyfriend['Mark'] = 'Wilson'
# Let's read the new dictionary
print(f"His current boyfriend is {name_and_boyfriend['Mark']}")
Here we used an example of a boyfriend, directly overwriting the value corresponding to the key.
His ex-boyfriend is Williams
His current boyfriend is Wilson
The overwrite uses a string, and the same logic applies to numbers.
It is important to note that such overwriting modifications are permanent.
Let's see what this means:
# First define the dictionary
name_and_boyfriend = {
'Mark': 'Williams',
'Tom': 'Brown',
}
# for statement loop
for name, boyfriend in name_and_boyfriend.items():
print(f'{name}\'s ex-boyfriend was {boyfriend}')
# Let's read the original dictionary
print(f"His ex-boyfriend is {name_and_boyfriend['Mark']}")
# Overwrite the value
name_and_boyfriend['Mark'] = 'Wilson'
# Let's read the new dictionary
print(f"His current boyfriend is {name_and_boyfriend['Mark']}")
# for statement loop
for name, boyfriend in name_and_boyfriend.items():
print(f'{name}\'s current boyfriend is {boyfriend}')
Output result:
Mark's ex-boyfriend was Williams
Tom's ex-boyfriend was Brown
His ex-boyfriend is Williams
His current boyfriend is Wilson
Mark's current boyfriend is Wilson
Tom's current boyfriend is Brown
Tom, as a control group, has not changed; his boyfriend has always been Brown, while Mark, after the change, is also read as the modified value in the for statement.
Advanced if-elif-else#
In KillAliens, advanced if statements are used, where nested if statements are used within the if statement, and the in syntax is employed. Let's modify the code excerpt from KillAliens for explanation.
# Import random module
import random
# Control numbers
state_one = ['1', '2', '3', '4', '5']
# Input the corresponding name, which is written for the names in the following if statements
ChoiseAliens = input("Please enter the corresponding name:\n\t")
# if statement judgment, if the value of ChoiseAliens is Small Alien, then execute the content within the if statement
if ChoiseAliens == 'Small Alien':
# Experimental group, hand over The_Random for random processing.
state_two = ['1', '2', '3', '4', '5', '6', '7', '8']
The_Random = random.choice(state_two)
print("You chose Small Alien")
# Nested if statement, if the generated random number is in the control group, then return the next value
if The_Random in state_one:
print(f"Congratulations, you killed successfully and earned 1 point")
# Nested if statement, sub-statement, if the generated random number is not in the control group, then return the next value
else:
print(f"Unfortunately, you tried to kill Small Alien and failed")
# if statement, sub-statement judgment, if the value of ChoiseAliens is A Alien, then execute
elif ChoiseAliens == 'A Alien':
# Experimental group, hand over The_Random for random processing.
state_two = ['1', '2', '3', '6', '7', '8']
The_Random = random.choice(state_two)
print("You chose A Alien")
# Nested if statement, if the generated random number is in the control group, then return the next value
if The_Random in state_one:
print(f"Congratulations, you killed successfully and earned 2 points")
else:
# Nested if statement, sub-statement, if the generated random number is not in the control group, then return the next value
print(f"Unfortunately, you tried to kill A Alien and failed")
# if statement, sub-statement judgment, if the input content is not in if and elif, then return the next value
else:
print("You need to enter the specified name, not something else.")
To demonstrate different results, I ran it multiple times.
# First time
Please enter the corresponding name:
Small Alien
You chose Small Alien
Congratulations, you killed successfully and earned 1 point
# Second run
Please enter the corresponding name:
A Alien
You chose A Alien
Unfortunately, you tried to kill A Alien and failed
# Third run
Please enter the corresponding name:
Magneto
You need to enter the specified name, not something else.
In the first run, we went through the if
judgment, and the randomly selected number was in the control group state_one
, so we returned success. In the second run, we went through the elif
judgment, and the randomly selected number was not in the control group state_one
, so we returned failure. In the third run, we entered Magneto, and neither the if
nor elif
judgments matched the rules, so it was handed over to else
for processing, returning a prompt.
In KillAliens, this effectively avoids inputting non-existent content, which would lead to program errors.
While Loop#
The while loop in KillAliens is used simply and will not be elaborated further. You can refer to Python3 Loop Statements | Runoob for learning.
Conclusion#
KillAliens is a relatively complex program I wrote, considered a simple text mini-game. The scoring system, judgment system, and killing system completed solely through Python are all well-developed and relatively simple, but this data only exists within the thread, and there is still a lot of potential.
This article is synchronized and updated to xLog by Mix Space
The original link is https://fmcf.cc/posts/technology/Python_Notes_4