banner
Magneto

Magnetoの小屋

Magneto在區塊鏈上の小屋,讓我們的文章在互聯網上永遠熠熠生輝!!

Python Learning Diary – KillAliens Implementation of Continuous Read, Write, and Calculation

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 feel 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 text-based game I wrote a long time ago called KillAliens.py, which has fewer than 30 lines. In KillAliens, the scoring system is something that KillAliens.py does not have, and it uses a dictionary to implement a score corresponding to each type of Alien through key-value pairs.

KillAliens.py can be found in my Python learning repository.

Supplement#

This mini-game was initially written on 2022/5/14. After some research, the algorithm was modified on 2022/5/19 to improve 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 after a successful kill.
    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 after a successful kill.
    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 after a successful kill.
    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, your score is reset to zero, and you exit 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 \033[94m name \033[0m of the Alien you want to kill to earn the specified score after a successful kill")
    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, your score is reset to zero, and you exit 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, your score is reset to zero, and you exit 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, your score is reset to zero, and you exit 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, your score is reset to zero, and you exit the game.")
            break
    else:
        print("You need to enter the corresponding \033[94m name \033[0m, not something else.")

Code Analysis#

Analysis Explanation#

This code analysis mainly discusses the key syntax used and does not analyze 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 Imports
The code on lines 9-10 imports the random module and the time module, respectively.

import random
import time

The functions of these two modules are random processing and making the Python thread 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's function is to make the Python thread 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 above code, the first line is executed immediately after the Python thread starts running, asking for the name. After receiving the user's input, the second line of code is executed. The Python interpreter receives the instruction on the second line, requiring it to sleep for 1 second, and only after the Python thread has slept for 1 second does it continue to execute the third line of code, outputting the name.

Dictionary and for Statement#

In Python, a dictionary is 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 both dictionaries with no differences. The format of 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 easier to output with a for statement. Let's write a dictionary and try outputting it with a for statement:

name_and_money = {
    'Mark': '10',
    'Tom': '20',
}
for name, money in name_and_money.items():
    print(f"{name} has {money} dollars.")

For ease of viewing and learning, I separated each key-value pair. The output result is:

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 to loop through the output until there are no more key-value pairs in the dictionary to print.

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 indicates reading specific content, and adding [ ] is to read a specific value within that specific area.

In the above code, {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")
# Increment the number by 1, i.e., perform a calculation
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, which requires us 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 for calculation writing; you 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 that 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, also reads the modified value in the for statement.

if-elif-else Advanced#

In KillAliens, the advanced use of if statements is employed, where nested if statements are used, along with the in syntax. Let's modify the code excerpt from KillAliens for explanation.

# Import the 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 followed the if judgment, and the randomly selected number was in the control group state_one, so we returned success. In the second run, we followed 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 input Magneto, and since neither if nor elif matched the rules, it was handed over to else for processing, returning a prompt.

In KillAliens, this effectively avoids inputting non-existent content, which would cause the program to report an error.

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.

Epilogue#

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 room for improvement.

This article is synchronized and updated to xLog by Mix Space. The original link is https://fmcf.cc/posts/technology/Python_Notes_4

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.