
TEXT-BASED GAMES
WORKSHEET 1 – INTRODUCTION TO PYTHON BASICS
Objective:
This worksheet introduces you to the fundamental concepts of Python programming, focusing on variables, basic data types, and simple input/output operations. By the end of this lesson, you’ll understand how to create simple Python scripts that can interact with the user, perform calculations, and display results.
Part 1: Understanding Variables and Data Types
Variables in Python are used to store information that can be referenced and manipulated in a program. They can hold different types of data, such as text (strings), numbers (integers and floats), and more.
- String: A sequence of characters, enclosed in quotes. Example:
"Hello, World!" - Integer: A whole number, positive or negative, without decimals. Example:
25 - Float: A number that includes a decimal point. Example:
3.14
name = "Alice" # String
age = 30 # Integer
height = 5.5 # Float
Part 2: Simple Input/Output
Input allows your program to receive information from the user. The input() function pauses your program and waits for the user to type something and press enter.
Output is how your program communicates information to the user. The print() function displays the specified message to the screen.
# Ask the user for their name
user_name = input("What is your name? ")
print("Hello, {}!".format(user_name)) # This prints a personalized greeting
Activity 1: Create a Simple Greeting Program
- Write a program that asks the user for their name and their favorite color.
- Then, print a message back to them, using the information they provided.
Part 3: Basic Arithmetic Operations
Python supports the usual mathematical operations for numbers, allowing you to perform calculations using addition (+), subtraction (-), multiplication (*), and division (/).
# Basic arithmetic operations
number1 = 10
number2 = 5
sum = number1 + number2 # Addition
difference = number1 - number2 # Subtraction
product = number1 * number2 # Multiplication
quotient = number1 / number2 # Division
print("Sum:", sum)
print("Difference:", difference)
print("Product:", product)
print("Quotient:", quotient)
Activity 2: Calculator Program
- Ask the user to enter two numbers.
- Perform addition, subtraction, multiplication, and division on those numbers.
- Print the results of each operation to the screen.
AcTIVITY 3: Create an intro for your Text BASED Game
The first step of your text based adventure game is to create an introduction to your game that asks your player for their name. Create this in a new trinket that will be your text based game.
- Ask the player what their name is?
WORKSHEET 2 – FUNCTIONS AND BASIC CLASSES
This worksheet aims to introduce you to functions and classes in Python, essential building blocks of programming that enhance modularity, reusability, and organization in code. By the end of this lesson, you will understand how to define and use functions, create basic classes, and understand the principles of object-oriented programming (OOP).
Part 1: Introduction to Functions
Functions are defined blocks of code designed to perform a specific task. Functions allow you to write reusable pieces of code, keep your program organized, and improve readability.
Defining a Function:
To create a function, use the def keyword, followed by the function name and parentheses. If your function needs input to do its job, you specify parameters within these parentheses.
def greet(name):
print("Hello, {}!".format(name))
# Call the function with a name
greet("Alice")
Calling a Function:
After defining a function, you can execute it by calling its name followed by parentheses. If the function expects parameters, you provide the values (arguments) within these parentheses.
greet("Alice")
Activity 1: Create a Function to Calculate Area
- Write a function named
calculate_areathat takes two parameters,lengthandwidth, and prints the area of a rectangle. - Call your function with different sets of numbers to test it.
Part 2: Introduction to Classes and Object-Oriented Programming
Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Classes can also have methods (defined by its functions) for modifying its state.
Defining a Class:
A class is defined using the class keyword, followed by the class name and a colon. Inside the class, an __init__ method defines the attributes.
Creating an Instance of a Class:
To create an instance of a class, you call the class using its name and pass the arguments that its __init__ method expects.
Example:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print("Woof!")
# Example method to demonstrate string formatting without f-strings
def print_info(self):
print("My name is {} and I am {} years old.".format(self.name, self.age))
# Create an instance of Dog
my_dog = Dog("Buddy", 4)
# Call the print_info method
my_dog.print_info()
Activity 2: Create a Class for a Book
- Define a class named
Bookthat has two attributes:titleandauthor. - Add a method to the class named
display_infothat prints a sentence including the title and author of the book. - Create two instances of your
Bookclass with different book titles and authors, and call thedisplay_infomethod for both.
Conclusion
You’ve now learned how to define and use functions to perform specific tasks and how to create classes that encapsulate data and functionality. These concepts are crucial for writing organized and reusable code.
APPLY TO TEXT BASED GAME
In the document where you created the intro asking for the players name you should attempt the following:
Create the foundational classes for the game and facilitate a basic interaction that doesn’t require conditional logic. Set up the Character class and simulate a simple “attack” action that prints the outcome.
1. Define the Character Class:
Define a Character class focusing on attributes that are important for use in the game (for example: name, health, attack power).
2. Implement a Simple Interaction Method:
Implement a method that simulates a character performing an action, such as “attack,” which, for now, will only print a message instead of affecting another character’s health. We will need to understand and know how to use conditional statements before we will be able to simulate an attack that impacts character health.
3. Instantiate Characters:
Create instances of your characters for both the player and an enemy, setting attributes like name, health, and attack power. In define character class you indicated the different attributes a character could have. Now create a character and give them values in those attributes.
4. Simulate a Basic Interaction:
Create an interaction, call the attack method for both the player and the enemy, which will print the attack action to the console.
The final structure should align with object-oriented programming principles, where objects (in this case, characters) have data (attributes like name, health, and attack power) and operations (methods like display_health and attack) that can act on that data.
WORKSHEET 3 – CONTROL FLOW AND LOOPS
Objective:
This worksheet is tailored to introduce control flow with conditional statements and loops in Python. By the end of this worksheet you should be able to add decision-making capabilities and repetitive actions to your Python scripts, essential for creating dynamic and interactive applications.
Part 1: Conditional Statements
Conditional statements let your program choose different paths of execution based on certain conditions. In Python, the fundamental conditional statements are if, elif (short for “else if”), and else.
age = int(raw_input("Enter your age: ")) # Note: raw_input() in Python 2
if age >= 18:
print "You are an adult."
elif age > 13:
print "You are a teenager."
else:
print "You are a child."
Part 2: Loops
Loops are a way to execute a block of code repeatedly. Python supports two main types of loops: for loops and while loops.
- For Loop: Executes a block of code for each item in a sequence (like a list, tuple, dictionary, set, or string).
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print fruit
While Loop: Continues executing a block of code as long as a given condition is true.
count = 0
while count < 5:
print count
count += 1 # Important to modify the loop condition inside the loop
Activity 1: Using Conditional Statements
- Prompt the user to input a number.
- Write a program that outputs “Positive” if the number is greater than 0, “Negative” if less than 0, and “Zero” if equal to 0.
Activity 2: Creating a Guessing Game with Loops
- Implement a simple guessing game where the program selects a random number between 1 and 10, and the player tries to guess it.
- Use a
whileloop to allow unlimited guesses until the correct number is guessed.
import random
number = random.randint(1, 10)
guess = None
You will need a special package called ‘random’ in order for the computer to randomly choose a number in a range. The above sample code should help you construct the guessing game.
APPLY TO TEXT BASED GAME
After completing Worksheet 3, which introduces control flow and loops, hopefully you should now be able to implement more interactive and dynamic elements into the text-based game. The next task should involve applying these concepts to enhance the game with decision-making capabilities and repetitive actions. This can significantly improve the game’s playability and narrative depth.
Task: Enhancing the Text-Based Game with Decision-Making and Repetitive Actions
Objective:
Use conditional statements to introduce decision-making in the game’s storyline and incorporate loops for repetitive actions, such as allowing the player to make multiple choices or attempts at solving puzzles or engaging in combat until a condition is met.
Assignment Overview:
- Introduce Branching Paths:
Implement conditional statements to offer the player choices that lead to different outcomes or paths within the game. This could involve deciding whether to explore a certain area, which item to use in a situation, or how to respond to a character. - Develop a Combat or Challenge Loop:
Incorporate awhileloop for a combat or challenge section where the player must continue to make decisions (e.g., attack, defend, use item) until the challenge is overcome or the player decides to flee.