HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMajor

Turn-based battle simulator

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
turnsimulatorbattlebased

Problem

I am embarking on the daunting journey of learning to program on my own two feet and have created a turn-based battle simulator (think Pokémon). The idea came from here.

It's very crude and could probably use a lot of refinement, so I'm willing to listen to any criticism and advice on improvements.

```
# Turn Based Battle Simulator

# Player and computer take turns to attack each other with different moves
# until one is defeated.

import random

def main():
"""Main function that will welcome the player to the game."""

print("\tWelcome to Battle Sim! This is a turn based combat simulator where")
print("\tthere can only be one winner.")

print("\nHow to play.\n\nPlayers take turn to choose a move. Moves can either deal moderate damage")
print("with a low range, deal high damage but over a wide")
print("range, or they can heal. (Note: Moves can miss, including Heal!)")

print("\nEach player starts with 100 health, and the first")
print("player to reduce their opponent to 0 is the winner.")

print("\nThat's it! Good luck")

play_again = True

# Set up the play again loop
while play_again:
winner = None
player_health = 100
computer_health = 100

# determine whose turn it is
turn = random.randint(1,2) # heads or tails
if turn == 1:
player_turn = True
computer_turn = False
print("\nPlayer will go first.")
else:
player_turn = False
computer_turn = True
print("\nComputer will go first.")

print("\nPlayer health: ", player_health, "Computer health: ", computer_health)

# set up the main game loop
while (player_health != 0 or computer_health != 0):

heal_up = False # determine if heal has been used by the player. Resets false each loop.
miss = False # determine if the chosen move will miss.

# create a dictionary of the possible moves and ra

Solution

Style

You've styled your code very well overall, I just have a few small nitpicky tips and such.

  • First off, when running main, you need run it under an if __name__ == "__main__": block. See this Stack Overflow answer for more information on this.



-
The comment at the top of your code file should be a docstring. It should look something like the below example, with a description of the file and it's contents.

"""
filename.py

Put a description of your file here.
"""


Design

Your design is not as great as your coding style, so I'm going to go more in-depth here on what can be improved.

-
At the top of main you have a lot of print statements on one line. I'd reccomend defining a function to easily print a lot of lines without needing to repeat print statements.

def print_lines(*lines):
    """
    A helpful function for printing many
    separate strings on separate lines.
    """
    print("\n".join([line for line in lines]))

# EXAMPLE USAGE
print_lines(
    "Hello.",
    "Goodbye"
)


-
Your current design using variables to manage different statistics and attributes about a player and an enemy begs for Object-Oriented-Programming. I'd recommend setting up something like this, a Character class with methods like, do_damage, or take_damage.

class Character:
    """
    Base class used to create playable
    characters
    """
    def __init__(self, health: int, damage: int, name: str):
        self.health = health
        self.damage = damage
        self.name = name

    ...


-
Another thing I'd recommend is using dictionaries for getting certain inputs, rather than creating if/elif/else chains. Here's an example.

CHOICES = {
    "a choice": a_function,
    ...
}

user_input = raw_input("> ")
if user_input in CHOICES:
    CHOICES[user_input]()


-
Finally, I'd recommend trimming of useless whitespace from user input, in addition to lowering the input. This makes user input more forgiving.

Anyways, that's about all I can come up with. if there's anything else that you want me to cover, just mention it in the comments, and I'll see what I can do. I hope this helps!

Code Snippets

"""
filename.py

Put a description of your file here.
"""
def print_lines(*lines):
    """
    A helpful function for printing many
    separate strings on separate lines.
    """
    print("\n".join([line for line in lines]))


# EXAMPLE USAGE
print_lines(
    "Hello.",
    "Goodbye"
)
class Character:
    """
    Base class used to create playable
    characters
    """
    def __init__(self, health: int, damage: int, name: str):
        self.health = health
        self.damage = damage
        self.name = name

    ...
CHOICES = {
    "a choice": a_function,
    ...
}

user_input = raw_input("> ")
if user_input in CHOICES:
    CHOICES[user_input]()

Context

StackExchange Code Review Q#94116, answer score: 20

Revisions (0)

No revisions yet.