Python is a versatile, beginner-friendly programming language renowned for its straightforward, easy-to-read syntax and extensive range of applications, as well as robust community support. With that in mind, you decided to give it a try and learn programming through the lens of the Python programming language.
This article explores core programming concepts by building a simple text-based adventure game that we will call “Evade the Fleet.” Through this program will explore variables, conditional statements, loops, functions, and handling user input. By the end, you should have a basic grasp of programming and Python fundamentals.
Prerequisites
Set up and run Python code
Text-Based Adventure Game Source Code
Below, you will find the entire source code of our project. If you just want to copy and paste, then please see my GitHub Gist.
def show_intro():
print(”Welcome to Evade the Fleet!\n”)
print(”You are the hotshot pilot of the illustrious Starship, The Ember Starlet! But you’ve just stumbled across an evil fleet of ships now looking to capture you!\n”)
print(”Your dashboard starts to light up as they zero in their tractoor beam! You need to take quick action, but which way do you go to escape the fleet?\n”)
print(”Choose wisely: one path leads to safety, one straight to an astroidfield and capture, and another into a fleet ship.\n”)
print(”Type ‘left’, ‘right’, or ‘middle’ to choose a path.”)
def make_choice():
choice = input(”Which path do you choose? (left/right/middle): “).lower()
return choice
def check_path(choice):
if choice == “left”:
print(”You find a gap in the formation of the fleet and you evade capture! You win!”)
return True
elif choice == “right”:
print(”Oh no! You ran straight into an astroid field and weren’t able to evade the fleet!”)
return True
elif choice == “middle”:
print(”Oh no! you ran straight into a fleet ship and there is no where to hide, you lose!”)
return True
else:
print(”Invalid choice. Please type ‘left’, ‘right’, or ‘middle’.”)
return False
if __name__ == ‘__main__’:
game_over = False
show_intro()
while not game_over:
choice = make_choice()
game_over = check_path(choice)
What is a Variable?
Think of a variable as a labeled bucket where you store information you might want to use later. Imagine you’re trying to store water, dirt, or gravel to use in the yard for various reasons. While you could look in the bucket to see what is inside, it is more efficient to label the buckets according to their contents. That way, we can grab the correct bucket (information).
As you are getting started programming, the concept of data types about variables might be foreign at first because Python is a loosely typed language — meaning a Python variable can be any data type.
Check out how we use variables in our game:
choice = input(”Which path do you choose? (left/right/middle): “).lower()
Here, the input() function waits for the user to type something. We store that value (converted to lowercase using .lower()) inside the variable named choice
. Later on, we check what’s inside that box to decide what happens next.
We choose to cast the input to an all-lowercase version of the string because it makes it easier to check for input later on. Think about if the user types in “LeFt”, “lEFT”, or “LEft”, when we do our check later to see what the user chose, we would have to check for all three of those strings individually for the program to register that the user wanted to go left.
Not only that, but we would have to check for every possible combination of uppercase and lowercase letters that could be. However, since we lowercased the string, we only have to do one check for “left”.
What is a function?
A function is like a reusable recipe or instruction booklet. Instead of rewriting the steps every time, you just call the function by its name.
Take this chunk of code:
def show_intro():
print(”Welcome to Evade the Fleet!\n”)
# rest of code below
This defines a function called show_intro(). Whenever we want to display the introduction, we don’t copy-paste all those print() statements again — we just call show_intro().
It’s kind of like saying, “Read the intro script!” instead of reading it all out from memory each time.
Another function in our game is check_path(choice). You may notice that this one looks different than the previous function. Why is there a variable being passed to check_path()?
def check_path(choice):
if choice == “left”:
# rest of code below
You can pass a variable into a function so it can work with different values each time it runs. We’re passing the player’s input (stored in the choice variable) into the function. This lets the function figure out what the player typed and respond accordingly.
You can pass any variable into a function this way — strings, numbers, even other functions! But for now, just know this is how you make your code interactive and dynamic.
Functions help keep our code clean, organized, and reusable — all good habits to start early.
What Are Conditional Statements?
Conditional statements let your program make decisions based on what’s happening.
They answer questions like:
“What should I do if the player goes left?”
“What else should I do if they pick something different?”
This is where if, elif, and else come into play — they’re the core ingredients that give our code its decision-making powers.
Let’s break down the actual code from our game:
if choice == “left”:
print(”You find a gap in the formation of the fleet and you evade capture! You win!”)
return True
elif choice == “right”:
print(”Oh no! You ran straight into an astroid field and weren’t able to evade the fleet!”)
return True
elif choice == “middle”:
print(”Oh no! you ran straight into a fleet ship and there is no where to hide, you lose!”)
return True
else:
print(”Invalid choice. Please type ‘left’, ‘right’, or ‘middle’.”)
return False
The if statement checks the first condition. In our case:
if choice == “left”:
This line means: “If the player typed ‘left’, then run the code inside this block.” So, that means that if the user typed “left”, then the program would print out “You find a gap in the formation... You win!”
Now let’s look at the next statement, elif. Short for “else if”, the elif keyword adds more choices to your decision tree:
elif choice == “right”:
This means: “If the first condition wasn’t true, but this one is, do this instead.”
You can stack as many elif blocks as you need. You can somewhat see that in our code. We have two elif statements, but we could have put in as many as our heart desires.
Finally, we see the else statement. Else is your fallback — the “none of the above” option.
else:
print(”Invalid choice. Please type ‘left’, ‘right’, or ‘middle’.”)
if the user doesn’t type any of the given choices, we want to display some sort of message that tells them their input is invalid and to try again.
How Python Checks Conditions
Python checks conditions in order, from top to bottom:
if
— First checkelif
— Any number of alternative checkselse
— Only runs if all above checks fail
This order matters. Once it finds a true condition, Python stops checking and skips the rest. That’s why you want your most likely or important checks near the top when it makes sense.
What is if __name__ == ‘__main__’
?
I thought about whether or not to include this in the game, but I thought this is a crucial concept to understand, not only for Python, but other programming languages — the main function.
In many programming languages — like C, Java, or C# — the main function is the official entry point of a program. It’s like the front door. When the program runs, it always starts by walking through that door first.
Python, being a bit more flexible, doesn’t require a formal main()
function. You can write code that just runs from top to bottom. But even so, it’s still considered good practice to organize your logic into a “main” function. This helps keep things clean, especially in larger programs or when sharing code with others.
if __name__ == ‘__main__’:
The Game Loop
Now that we have briefly gone over what a main function is, let’s look at the game loop. If you’ve ever played a video game, even something simple like Pong, you’ve experienced a game loop in action.
At its core, a game loop is the heartbeat or engine of a game. It’s a repeating cycle that:
Waits for player input
Processes that input
Updates the game accordingly
Decides whether the game should keep going or end.
It keeps looping over and over until something tells it to stop, like a win, a loss, or a player quitting.
Even though we’re making a text-based adventure, the same idea applies.
Let’s look at the game loop in our Python code:
game_over = False
show_intro()
while not game_over:
choice = make_choice()
game_over = check_path(choice)
We create a variable named game_over and set it to False
. This variable acts as an on/off switch — as long as it’s False
, our game loop will keep running.
Before the loop starts, we show the introduction to set the stage. This only runs once, before we start asking for player input.
while not game_over:
This is where the loop begins. The keyword while is Python’s way of saying: “As long as this condition is true, keep repeating the code below.” In our case, we say to keep repeating the code as long as game_over is not true.
choice = make_choice()
game_over = check_path(choice)
make_choice() waits for the player to type something (left, right, or middle).
check_path(choice) checks their decision and prints the result.
It also returns
True
orFalse
, which updates the game_over on/off switch.
If the player makes a valid choice that ends the game (like winning or crashing into a fleet ship), check_path() returns True, which sets game_over = True, and the loop ends.
Wrapping Up
By building Evade the Fleet, you’ve just walked through:
Declaring and using variables
Writing and calling functions
Making decisions with conditional statements
Understanding what the main function is
Understanding looping
This might seem like a small step, but it’s a massive leap in learning to code. Every complex program you’ll write in the future will still rely on these same basics.
Drop any questions in the comments below! What features do you want to be added to this project?