
Jump to:
Day 1 – introduction to python
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
OBJECTIVE
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 da
Worksheet 3 – Control Flow and Loops
INTRODUCTION TO PYGAME
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
INTRODUCTION
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
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.
Day 2 – Text-based games
Worksheet 1 – Text-Based Games Sample Code
Here is the code just for the combat:
enemy_health = 10
player_health = 12 # Starting health for the player
while enemy_health > 0:
print("The goblin attacks! What do you do? (attack/run)")
action = raw_input("> ").lower()
if action == "attack":
print("You hit the goblin!")
enemy_health -= 2 # Simplified damage calculation
# Simulate the goblin fighting back
print("The goblin strikes back!")
player_health -= 2 # Player loses health when attacking
if enemy_health <= 0:
print("You defeated the goblin!")
break # Exit the loop after defeating the goblin
elif action == "run":
print("You run away safely.")
break # Exit the loop
else:
print("Invalid action. The goblin strikes you!")
player_health -= 2 # Damage to the player for an invalid action
if player_health <= 0:
print("You have been defeated by the goblin!")
break # Exit the loop if the player is defeated
# Optionally, display the current health of the player and the goblin
print("Your health:", player_health)
print("Goblin's health:", enemy_health)
Here is a complete minigame:
import random
class Character:
def __init__(self, name, health, attack_power):
self.name = name
self.health = health
self.attack_power = attack_power
def attack(self, other):
damage = random.randint(1, self.attack_power)
other.health -= damage
print "%s attacks %s for %d damage." % (self.name, other.name, damage)
if other.health <= 0:
print "%s has defeated %s." % (self.name, other.name)
def choose_location():
print "You stand at the crossroads. Do you go to the (F)orest or the (C)ave?"
choice = raw_input("> ").lower()
if choice == "f":
return "forest"
elif choice == "c":
return "cave"
else:
print "Confused, you decide to head back home."
return None
def encounter(location):
if location == "forest":
print "You encounter a wild goblin in the forest!"
return Character("Goblin", 30, 5)
elif location == "cave":
print "The cave is quiet and empty. You find a treasure chest."
return None
def game_loop():
player = Character("Hero", 100, 10)
companion = Character("Companion", 80, 8)
enemy = Character("Bandit", 50, 6)
print "Welcome to the Adventure Game!"
location = choose_location()
if location:
adversary = encounter(location)
if adversary:
while player.health > 0 and adversary.health > 0:
player.attack(adversary)
if adversary.health > 0:
adversary.attack(player)
if player.health <= 0:
print "You have been defeated. Game over."
else:
print "You emerge victorious!"
else:
print "You explore the area and find nothing else of interest."
else:
print "Maybe another time then."
game_loop()
Day 3 – Programming Games in Pygame
Pygame allows you to write games and rich multimedia Python programmes for every platform that supports them.
Worksheet 1 – Pygame
STEP 0: IMPORT
Python wrapper for the SDL library, which stands for Simple DirectMedia Layer. SDL provides cross-platform access to your system’s underlying multimedia hardware components, such as sound, video, mouse, keyboard, and joystick. pygame started life as a replacement for the stalled PySDL project. The cross-platform nature of both SDL and pygame means you can write games and rich multimedia Python programs for every platform that supports them!
To install pygame on your platform, use the appropriate pip command:
pip install pygame
Pygames has many modules that provide abstract access to specific hardware on your system, as well as uniform methods to work with that hardware. For example, display allows uniform access to your video display, while joystick allows abstract control of your joystick.
STEP 1: Setting Up the Game Environment
Introduction
Create a simple window with a circle. This code provides you the starting point of Pygames, where we are creating a simple window with fixed size
Coding Example
# Import and initialize the pygame library
import pygame
pygame.init()
# Define constants for the screen width and height
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# Set up the drawing window
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# Run until the user asks to quit
running = True
while running:
# Did the user click the window close button?
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Fill the background with white
screen.fill((255, 255, 255))
# Draw a solid blue circle in the center
pygame.draw.circle(screen, (0, 0, 255), (250, 250), 75)
# Flip the display
pygame.display.flip()
# Done! Time to quit.
pygame.quit()
Step 2: Rendering
In Pygame, drawing on the screen involves understanding the coordinate system used to position elements. The screen is treated as a grid with coordinates that help place objects precisely where you want them.
Coordinate System in Pygame
- Origin (0, 0): The top-left corner of the window or screen is the origin, where the coordinate (0, 0) is located.
- X-Axis: The x-axis runs horizontally across the screen. Increasing values on the x-axis move from left to right.
- Y-Axis: The y-axis runs vertically. Increasing values on the y-axis move from top to bottom.
The call to pygame.display.flip() is made after the call to blit(). This updates the entire screen with everything that’s been drawn since the last flip. Without the call to .flip(), nothing is shown.
1. blit()
The blit() function is an abbreviation of “block transfer.” It is used to copy the contents of one surface to another. In the context of Pygame, a “surface” represents an off-screen buffer where you can draw or manipulate images. Here’s what blit() is primarily used for:
2. flip() and update()
flip() is used to update the entire screen. In double-buffering, which Pygame uses by default, all drawing operations are done on a hidden buffer (not visible on the screen). Once all drawing is completed (using blit()), flip() is called to make the hidden buffer visible, effectively updating the entire display.
- Efficiency: This method is efficient because it prevents partial and frequent screen updates, which can cause flickering and performance issues. Instead, the screen is updated all at once.
- Double Buffering:
flip()is part of the double buffering technique where two buffers are used: one for displaying on the screen and the other for drawing. When you callflip(), Pygame swaps these buffers, making the drawing buffer visible.
Alternatively, pygame.display.update() can be used to update only parts of the screen (instead of the entire area), which is more efficient if only small portions of the screen change between frames.
Code
import pygame
import random
import sys
# Helps us access system folders
import os
# Define constants for the screen width and height
SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 600
# Times/sec screen is updated
FPS = 60
# Define colours to reuse again and again (RGB ntotation)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# Import pygame.locals for easier access to key coordinates
from pygame.locals import (
K_UP,
K_DOWN,
K_LEFT,
K_RIGHT,
K_ESCAPE,
KEYDOWN,
QUIT,
)
# Initialize the pygame library
pygame.init()
# Initialize the pygame sound library
pygame.mixer.init()
# Set up the drawing window
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# Set up in-game clock for FPS and deltatime
clock = pygame.time.Clock()
# Set title for the game window
pygame.display.set_caption("CodeCrafters")
## GAME LOOP
game_over = True
running = True
while(running):
# Keep loop running at the right speed
clock.tick(FPS)
# Look for any events happening in the game
for event in pygame.event.get():
#Check for closing the window
if(event.type == pygame.QUIT):
running = False
# Check for inputs in the game
elif(event.type == KEYDOWN):
# Check for Escape Key
if(event.key == K_ESCAPE):
running = False
# Check for Up Key
elif(event.key == K_UP):
print("Pressed up!")
# Fill the screen with white
screen.fill(WHITE)
# Create a surface and pass in a tuple containing its length and width
surf = pygame.Surface((50, 50))
# Give the surface a color to separate it from the background
surf.fill(BLACK)
rect = surf.get_rect()
# This line says "Draw surf onto the screen at the center"
screen.blit(surf, (SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
# *After* drawing everything, flip the display
pygame.display.flip()
# Closing everything related to Pygames and freeing up memory
pygame.quit()
sys.exit()
Day 4 – Collisions and coding
Introduction
Collisions are fundamental to the majority of video games. In the snake game we program into the game that it should detect when it has come to a wall to end the game or to grow in length when it eats some food. Neither of these incidents result in us having to accurately code physics. But what if we were coding something like pong where a ball is hitting a paddle and we want it to bounce back accurately – how do we input the physics for that collision.
PowerPoint Presentation
PowerPoint Presentation – Collisions
Worksheets
Now let’s apply what we have learned to some coding. The worksheet below creates a text based collision with a ball and a paddle.
Ball and Paddle Game
# Initial position and velocity of the ball
ball_position = 0
ball_velocity = 1 # Positive is rightward, negative is leftward
# Position of the stationary paddle
paddle_position = 10
# Ensure the initialization of variables happens before this point in your script
# Example loop to simulate movement (make sure this part is not before variable initialization)
for step in range(20):
print "Step {}: Ball at position {}".format(step, ball_position)
# Move the ball according to its velocity
ball_position += ball_velocity
# Check for collision with the paddle and bounce back
if ball_position >= paddle_position:
ball_velocity = -ball_velocity # Reverse direction
ball_position = paddle_position # Ensure the ball isn't beyond the paddle
print "Simulation complete."
This is not a lot of fun and not very game like though. We are going to change platforms now to Web Vpython which is a language that is very much based on Python but specifically created to create physics simulations.
Worksheet 1 – Setting up the Scene
Objective: Learn how to set up the basic 3D scene for the game.
Introduction to Display Function: GlowScript provides a display function to create a visual environment for your projects. This is where all your game objects will appear.
Code Walkthrough:
scene = display(title="BOUNCE GAME:", width=450)
sceneis a variable where we store our game window.display(title="BOUNCE GAME:", width=450)creates a new window with a title “BOUNCE GAME:” and a width of 450 pixels.
Assignment: Create a game window with a title you want to go with and a width of 600 pixels. Experiment with changing the title and width to see what happens.
Worksheet 2 – Creating Game Objects
Objective: Introduce basic 3D objects and properties.
Basic 3D Objects: In GlowScript, you can create various 3D objects. We will focus on sphere for the ball and box for the paddle and boundaries.
Code Walkthrough:
ball = sphere(pos=vec(0,0,0), size=vector(3,3,1), color=vector(1,0,0), radius=5)
paddle = box(pos=vec(0,-20,0), size=vec(10,2,.2), color=vec(100,10,2))
ballis aspherepositioned at the origin(0,0,0), red in color. Itssizeandradiusdetermine its appearance.paddleis aboxplaced below the ball aty = -20. Itssizeandcolorare specified to distinguish it from the ball.
Assignment: Create a ball and a paddle. Experiment with changing their positions, sizes, and colors.
Worksheet 3 – Movement and Interaction
Objective: Learn about updating object positions and basic interactions through code that moves an object and detects basic conditions like boundaries.
Background: In computer graphics and games, objects move by changing their position over time. This can be simulated by updating the position of an object in a loop, which runs continuously during the game.
Starter Code and Walkthrough:
First, let’s focus on moving the ball in a horizontal direction (left and right) and bouncing it off the walls. We’ll use a simple control structure (if statement) to reverse the ball’s direction when it hits a boundary.
# Initialize ball position and velocity
ball.pos = vec(0,0,0) # Starting position at the center
ball.velocity = vec(5,0,0) # Moving 5 units per time step to the right
# Main game loop
while True:
rate(30) # Controls the speed of the loop, making it run 30 times per second
# Update the ball's position
ball.pos = ball.pos + ball.velocity * dt
# Check for collision with the right wall
if ball.pos.x > 23: # Assuming the right boundary is at x=23
ball.velocity.x = -ball.velocity.x # Reverse the x velocity
# Check for collision with the left wall
if ball.pos.x < -23: # Assuming the left boundary is at x=-23
ball.velocity.x = -ball.velocity.x # Reverse the x velocity
Explanation:
ball.posrepresents the current position of the ball.ball.velocityis how much the ball moves each time the loop runs. Here, it’s set to move to the right (x=5).- The
while Trueloop is the game loop, constantly running to update the game state.rate(30)limits the loop to run 30 times per second, making our game’s animations smoother. - Within the loop,
ball.pos = ball.pos + ball.velocity * dtupdates the ball’s position based on its velocity.dtis a small time step (e.g.,dt = 1.0 / 30to match the rate of the loop). - The if statements check whether the ball has hit a boundary. If it has, the ball’s horizontal velocity (
ball.velocity.x) is reversed, causing the ball to bounce back.
Assignment:
Make the ball also move vertically and bounce off the top and bottom edges of the scene.
Use the provided code as a starting point to make the ball move horizontally across the screen and bounce off the left and right edges.
Experiment with changing the ball’s initial velocity and the rate to see how it affects the movement and the smoothness of the animation.
Worksheet 4 – Ball Physics
Objective: Implement basic physics to simulate gravity and make the ball bounce off the bottom of the scene.
Background: Physics in games often involves simulating real-world phenomena like gravity, which accelerates objects towards the Earth. By applying a constant acceleration to the ball’s vertical velocity and inverting its direction when it collides with the ground, we can simulate bouncing.
# Define initial ball properties
ball.pos = vec(0, 10, 0) # Start 10 units above the bottom
ball.velocity = vec(2, 0, 0) # Initial horizontal velocity
gravity = vec(0, -9.8, 0) # Gravity acceleration vector
dt = 0.01 # Time step
# Main game loop
while True:
rate(100) # Run this loop 100 times per second
# Apply gravity to the ball's velocity
ball.velocity = ball.velocity + gravity * dt
# Update ball position
ball.pos = ball.pos + ball.velocity * dt
# Check for collision with the bottom
if ball.pos.y < 0: # Assuming the bottom is at y=0
ball.velocity.y = -ball.velocity.y # Invert y velocity to bounce
# Optional: Add side boundaries collision for a complete example
if ball.pos.x > 23 or ball.pos.x < -23:
ball.velocity.x = -ball.velocity.x # Bounce off side walls
Explanation:
- The ball starts 10 units above the bottom of the scene, with an initial horizontal velocity.
- Gravity is defined as a vector pointing downwards (
y = -9.8), simulating Earth’s gravity. In games, you might need to adjust the magnitude for a more enjoyable experience. - In each iteration of the loop, gravity is applied to the ball’s velocity, accelerating it downwards.
- The ball’s position is updated based on its velocity.
- When the ball “collides” with the bottom (
y < 0), its vertical velocity is inverted (ball.velocity.y = -ball.velocity.y), simulating a bounce. The exact position where this should happen depends on your scene’s setup. - Additional conditionals are added to simulate bouncing off the side walls for a more comprehensive demonstration.
Assignment:
Consider what might happen if you apply gravity continuously without reversing the ball’s velocity on collision. How does this affect the realism of the ball’s movement?
Implement the provided physics code in your game. Observe how gravity affects the ball’s movement.
Adjust the magnitude of gravity and the initial velocity to see how they change the ball’s trajectory and bouncing behavior.
Worksheet 5 – User Input
Objective: Capture and respond to user input.
Capturing Mouse Movements: You can control the paddle’s position with the mouse’s x-position.
Code Walkthrough:
if scene.mouse.pos.x < 21 and scene.mouse.pos.x > -21:
paddle.pos.x = scene.mouse.pos.x
Explanation:
- The
scene.mouse.pos.xgives the current X position of the mouse within the game window. - In the main game loop, we continuously check the mouse’s position. The paddle’s X position (
paddle.pos.x) is updated to follow the mouse, but we use conditional statements to ensure it doesn’t exceed the defined left and right limits.
Assignment:
As an additional challenge, try implementing functionality that only moves the paddle when the mouse is within the game scene area. This might involve checking the mouse’s Y position and determining whether it falls within the vertical bounds of the scene.
Incorporate this code into your game, ensuring the paddle follows the mouse’s movement horizontally.
Experiment with different limits for the paddle’s movement and observe how constraining the paddle’s position affects gameplay.
Worksheet 6 – Collision Detection
Objective: Implement collision detection between objects.
Code Walkthrough: Check if the ball’s position intersects with the paddle’s position. If so, reverse the ball’s y-velocity to simulate a bounce.
if (ball.pos.x >= paddle.pos.x - paddle.length/2) and (ball.pos.x <= paddle.pos.x + paddle.length/2) and (ball.pos.y <= -18):
ball.velocity.y = -ball.velocity.y
Assignment: Implement collision detection for the ball and paddle. Extend this to detect collisions with the game’s top and side boundaries.
Worksheet 7 – Game Mechanics
Objective: Implement scoring, game states (winning and losing conditions), and display dynamic messages based on the game’s state.
Background: A crucial aspect of game development is creating clear objectives and feedback for the player. This involves tracking their progress through scores, providing win or lose conditions, and giving immediate visual or textual feedback based on their actions and the game state.
Part 1: Setting Up Score and Game State Variables
Before the game loop starts, initialize variables to track the score, game state, and acceleration (for later use).
score = 0 # Tracks the player's score
gameState = True # True while the game is ongoing, False when the game ends
acceleration = 0.1 # Initial acceleration value for the ball's movement
Part 2: Displaying the Score and Acceleration
At the beginning of the game loop, update the scene’s caption to display the current score and acceleration. This provides real-time feedback to the player.
scene.caption = "Score: " + str(score) + "\nAcceleration: " + "{:.2f}".format(acceleration)
Part 3: Incrementing Score on Successful Hits
Within the game loop, check if the ball collides with the paddle. If so, increment the score and optionally increase the ball’s acceleration to raise the difficulty.
if (ball.pos.x >= paddle.pos.x - paddle.size.x/2) and \
(ball.pos.x <= paddle.pos.x + paddle.size.x/2) and \
(ball.pos.y <= paddle.pos.y + ball.radius):
ball.velocity.y = -abs(ball.velocity.y) # Ensure the ball bounces upwards
score += 1 # Increment score
acceleration += 0.1 # Increase acceleration
Part 4: Implementing Win and Lose Conditions
After handling the ball-paddle collision, check if the player has reached a winning score or a losing condition (e.g., the ball falls below the paddle).
# Win condition
if score >= 5: # Adjust the target score as needed
gameState = False
scene.caption = "You Win! Final Score: " + str(score)
# Display a win message
win_message = text(text='YOU WON!', pos=vec(0, 5, 0), align='center', color=color.green)
# Lose condition
if ball.pos.y < paddle.pos.y - 10: # Assuming the lose condition is when the ball is far below the paddle
gameState = False
scene.caption = "Game Over. Final Score: " + str(score)
# Display a game over message
game_over_message = text(text='GAME OVER', pos=vec(0, 5, 0), align='center', color=color.red)
Assignment:
Experiment with adjusting the target score for winning and the acceleration increment to find a balance that’s challenging yet attainable.
Implement the scoring system by updating the score each time the ball hits the paddle. Reflect these changes in real-time by updating the scene’s caption.
Introduce a win condition (e.g., reaching a certain score) and a lose condition (e.g., the ball falls below a certain point). Display appropriate messages for both conditions.
Worksheet 8 – Polish and Finishing Touches
Objective: Finalize the game with additional features and polish.
Adding a Countdown: Before the game starts, a countdown can enhance the player’s readiness.
def countdown():
for i in range(3, 0, -1):
countdown_text = text(pos=vector(0,5,0), text=str(i), align='center', color=color.green)
sleep(1)
countdown_text.visible = False
countdown()
This function creates a countdown from 3 to 1 at the center of the scene. Each number is displayed for one second before the next number appears.
Assignment: Implement the countdown function in your game. Make sure the game starts (or resumes) right after the countdown finishes.
Win and Game Over Conditions: To conclude the game logically, define conditions for winning and losing.
# Win Condition
if score == 5:
gameState = False
label(text='YOU WON', pos=vector(0,5,0), height=10, color=color.green)
# Game Over Condition
if ball.pos.y < -21: # Assuming -21 is below the paddle
gameState = False
label(text='GAME OVER', pos=vector(0,5,0), height=10, color=color.red)
These snippets check if the player has met the win condition (score of 5) or the game over condition (ball falls below the paddle). It then displays an appropriate message.
Assignment: Incorporate win and game over conditions in your game. Display a “Game Over” message if the ball falls below the paddle and a “You Win” message if the player reaches a score of 5.#
Tom’s Complete Paddle Game
Web VPython 3.2
from vpython import *
scene = canvas(title="BOUNCE GAME:", width=450, height=450)
ball = sphere(pos=vector(0, 0, 0), size=vector(3, 3, 1), color=vector(1, 0, 0), radius=5)
paddle = box(pos=vector(0, -20, 0), size=vector(10, 2, .2), color=vector(100, 10, 2))
# Initialize ball position and velocity
ball.pos = vector(0, 0, 0) # Starting position at the center
ball.velocity = vector(5, 5, 0) # Moving 5 units per time step to the right
def countdown():
for i in range(3, 0, -1):
countdown_text = text(pos=vector(0,5,0), text=str(i), align='center', color=color.green)
sleep(1)
countdown_text.visible = False
countdown()
score = 0 # Tracks the player's score
gameState = True # True while the game is ongoing, False when the game ends
acceleration = 0.1 # Initial acceleration value for the ball's movement
scene.caption = "Score: " + str(score) + "\nAcceleration: " + "{:.2f}".format(acceleration)
# Main game loop
while gameState:
rate(30) # Controls the speed of the loop, making it run 30 times per second
dt = 1 / 30
# Increase velocity gradually
ball.velocity.y += acceleration * dt
# Update the ball's position
ball.pos = ball.pos + ball.velocity * dt
# Check for collision with the right wall
if ball.pos.x > 23: # Assuming the right boundary is at x=23
ball.velocity.x = -ball.velocity.x # Reverse the x velocity
# Check for collision with the left wall
if ball.pos.x < -23: # Assuming the left boundary is at x=-23
ball.velocity.x = -ball.velocity.x # Reverse the x velocity
# Check for collision with the top wall
if ball.pos.y > 23: # Assuming the top boundary is at y=23
ball.velocity.y = -ball.velocity.y # Reverse the y velocity
# Check for collision with the paddle
if (ball.pos.y < -19) and (ball.pos.x < paddle.pos.x + 5) and (ball.pos.x > paddle.pos.x - 5):
ball.velocity.y = -ball.velocity.y # Reverse the y velocity
score += 1 # Increment score
acceleration += 0.05 # Increase acceleration gradually
scene.caption = "Score: " + str(score) + "\nAcceleration: " + "{:.2f}".format(acceleration)
# Paddle control
if scene.mouse.pos.x < 21 and scene.mouse.pos.x > -21:
paddle.pos.x = scene.mouse.pos.x
# Check if the ball has passed the paddle (missed)
if ball.pos.y < -30: # Assuming the threshold is at y=-30
print("Game Over! Final Score: ", score)
gameState = False
break
# Win condition
if score >= 5: # Adjust the target score as needed
print("You Win! Final Score: ", score)
gameState = False
break
Day 5 – Blender
Blender is a ‘free and open source 3D creation suite’ [1]. Complete the worksheets below to learn more about the software and start animating in Blender.
Worksheet 1 – Getting Started in Blender
Task 1: Interface Familiarization
- Open Blender and start a new general project.
- Layout Overview:
- 3D Viewport: Where you view and interact with your model.
- Outliner: Shows all objects in your scene.
- Properties Panel: Change settings for objects, materials, world settings, etc.
- Navigation:
- Rotate View: Hold the Middle Mouse Button and move the mouse.
- Zoom: Scroll the Middle Mouse Wheel.
- Pan: Hold Shift + Middle Mouse Button and move the mouse.
Task 2: Basic Controls
- Selecting Objects: Right-click to select an object.
- Adding Objects: Press Shift + A, select Mesh for shapes.
- Deleting Objects: With an object selected, press Delete and confirm.
Task 3: Creating the Torso
- Add a Cube: The base of your character’s torso.
- Enter Edit Mode: Press Tab with the cube selected.
- Scale the Cube: Press S, then Z to scale it along the Z-axis.
Task 4: Adding Arms and Legs
- Add Cylinders for arms and legs with Shift + A > Mesh > Cylinder.
- Position the Limbs: Use G to move, R to rotate, and S to scale.
- Duplicate for Symmetry: Use Shift + D for the opposite limbs.
Task 5: Creating the Head
- Add a Sphere for the head with Shift + A > Mesh > UV Sphere.
- Scale and Position the Head: Use S to scale and G to position it.
Task 6: Adding Hands and Feet
- Use scaled cubes or spheres as hands and feet.
- Attach to Limbs: Position at the ends of arms and legs.
Task 7: Creating a Material
- Select Your Character, go to Material Properties.
- Add a New Material: Click New and name it (e.g., “Skin”).
- Change the Base Color: Click the color box to select a color.
Task 8: Applying Different Materials
- Create new materials for clothes, eyes, etc.
- Assign Materials to Specific Parts: In Edit Mode, select faces, and click Assign in Material Properties.
Task 9: Setting Up the Camera
- Position the Camera: Use G and R to face it towards your character.
- Camera View: Press Numpad 0 to see through the camera.
Task 10: Lighting and Rendering
Render the Image: Go to Render > Render Image.
Adjust the Light: Select the light source and use G to position.
Helpful Notes and Troubleshooting:
- Navigational Difficulties: If navigating the 3D viewport is challenging, check your mouse settings or consider using a mouse with a scroll wheel and middle button.
- Object Not Appearing: If an object you added isn’t visible, it might be too large or too small, or outside your current view. Try using the “.” key on the numpad to center the view on the selected object.
- Editing Issues: Make sure you’re in the correct mode (Object or Edit Mode) for the action you’re trying to perform.
- Material Colors Not Showing: Ensure you’re in Material Preview or Rendered viewport shading mode to see textures and materials.
- Rendering Looks Dark: Adjust the scene’s lighting or add more light sources if your render appears too dark.
Worksheet 2 – Animation in Blender
Animation in Blender involves changing an object’s properties (like location, rotation, and scale) over time and creating keyframes that Blender interpolates between to create motion.
Task 1: Understanding the Timeline and Keyframes
- Timeline: Located at the bottom of the Blender window. It shows the current frame, start and end frames, and playback controls.
- Keyframes: Mark the values of an object’s properties at a specific point in time. They appear as yellow diamonds on the timeline.
Task 2: Setting Up for Animation
- Set Frame Range: Decide the length of your animation (e.g., 60 frames for 2 seconds at 30fps). Set the End Frame in the Timeline.
- Choose a Simple Action: Start with something manageable, like a hand wave.
Rigging Your Character (Optional)
Rigging is the process of creating a skeleton for your character so you can animate its movements more naturally. For simplicity, this task can be skipped for first-time animators, focusing on basic object animation instead.
Task 3: Inserting Keyframes
- Select Your Character: Ensure you’re in Object Mode.
- Pose for Start Position: Use G (grab) and R (rotate) to position your character at the start of the wave.
- Insert Keyframe:
- Move to Frame 1 in the Timeline.
- Press
Iand select “Location” and “Rotation” to insert a keyframe.
Task 4: Creating Movement
- Move to Another Frame: For a wave, go to Frame 30.
- Change the Pose: Adjust the arm’s position to the peak of the wave.
- Insert Another Keyframe: Press
Iand select “Location” and “Rotation” again.
Task 5: Completing the Action
- Final Position: Move to the last frame (e.g., Frame 60). Return the arm to the original position or a resting pose.
- Insert Final Keyframe: Press
Iand select “Location” and “Rotation”.
Task 6: Previewing the Animation
- Use Playback Controls: Use the play button in the Timeline to review your animation. Adjust keyframes as needed for smoother motion.
Task 7: Rendering the Animation
- Set Output Properties:
- Go to the Output Properties tab (printer icon).
- Set your desired resolution, frame start and end, and frame rate.
- Choose your file format under Output. For animations, MPEG or AVI are common.
- Render Animation: Go to Render > Render Animation or press
Ctrl + F12.
Helpful Notes and Troubleshooting:
Playback Performance: If playback is slow, reduce the viewport shading quality or render resolution for previews.
Smoothness: If the animation seems jerky, consider adding more keyframes between the start and end points for a smoother transition.
Rigging for Complex Characters: For characters with more complex movements, learning basic rigging will provide better results and control over animations.
Animation Principles: Study basic animation principles like anticipation, follow-through, and easing for more natural movements.
