Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
  • Loading branch information
ericbusboom committed Sep 30, 2024
1 parent 9a9e3d8 commit 2cf3b6d
Show file tree
Hide file tree
Showing 8 changed files with 372 additions and 6 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Python Games

To get started, open the file `lessons/00_Getting_Started/README.md`. This will give you an overview of the module and how to get started.


## Syllabus

Expand Down
87 changes: 87 additions & 0 deletions examples/01_move.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"""
Moving Square
All this game does is move a square around the screen based on the arrow keys.
The square is constrained to the screen, so it can't go off the edges.
"""
import pygame

# Initialize Pygame
pygame.init()

# Constants
SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
SQUARE_SIZE = 50
SQUARE_COLOR = (0, 128, 255) # Red-Green-Blue color in the range 0-255
BACKGROUND_COLOR = (255, 255, 255) # White
SQUARE_SPEED = 5
FPS = 60

# Initialize the screen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Move the Square")

# Clock to control the frame rate
clock = pygame.time.Clock()

# Main function
def main():
# Initial position of the square
square_x = SCREEN_WIDTH // 2 - SQUARE_SIZE // 2
square_y = SCREEN_HEIGHT // 2 - SQUARE_SIZE // 2

running = True

while running:

# This will clear the screen by filling it
# with the background color. If we didn't do this,
# the square would leave a trail behind it.
screen.fill(BACKGROUND_COLOR)

# Event handling
for event in pygame.event.get():

# Check for clicking the close button
if event.type == pygame.QUIT:
running = False

# Get the keys pressed. Gtes an array of all the keys
# with a boolean value of whether they are pressed or not
keys = pygame.key.get_pressed()

# Move the square based on arrow keys
if keys[pygame.K_LEFT]:
square_x -= SQUARE_SPEED
if keys[pygame.K_RIGHT]:
square_x += SQUARE_SPEED
if keys[pygame.K_UP]:
square_y -= SQUARE_SPEED
if keys[pygame.K_DOWN]:
square_y += SQUARE_SPEED

# Prevent the square from going off the screen
square_x = max(0, min(SCREEN_WIDTH - SQUARE_SIZE, square_x))
square_y = max(0, min(SCREEN_HEIGHT - SQUARE_SIZE, square_y))

# Draw the square
pygame.draw.rect(screen, SQUARE_COLOR, (square_x, square_y, SQUARE_SIZE, SQUARE_SIZE))

# Update the display. Imagine that the screen is two different whiteboards. One
# whiteboard is currently visible to the player, and the other whiteboard is being
# drawn on. When you call pygame.display.flip(), it's like taking the whiteboard
# that was being drawn on and showing it to the player, while taking the whiteboard
# that was visible to the player and giving it to the artist to draw on. This makes
# it so that the player never sees the drawing process, only the final result.
pygame.display.flip()

# Cap the frame rate. This makes the game run at a consistent speed on all computers.
clock.tick(FPS)

# Quit Pygame
pygame.quit()

if __name__ == "__main__":
main()
130 changes: 130 additions & 0 deletions examples/03c_vectors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
"""
Vector Jump
This programs demonstrates how to use vectors. When you hit SPACE, the
player will jump to the end of the green line. The left and right arrows
will rotate the green line, and the up and down arrows will change the
length of the green line.
"""
import pygame
import math

# Initialize Pygame
pygame.init()

# Settings class
class Settings:
"""A class to store all settings for the game."""
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
PLAYER_SIZE = 20
LINE_COLOR = (0, 255, 0)
PLAYER_COLOR = (0, 0, 255)
BACKGROUND_COLOR = (255, 255, 255)
FPS = 60
ANGLE_CHANGE = 3
LENGTH_CHANGE = 5
INITIAL_LENGTH = 100

# Initialize screen
screen = pygame.display.set_mode((Settings.SCREEN_WIDTH, Settings.SCREEN_HEIGHT))
pygame.display.set_caption("Player with Direction Vector")

# Clock to control frame rate
clock = pygame.time.Clock()

# Player class
class Player:
def __init__(self, x, y):
"""Initializes the Player with a position and direction vector.
Args:
x (int): The initial x-coordinate of the player.
y (int): The initial y-coordinate of the player.
"""

# We define two vectors, one for the position and one for the direction
# The position vector is the current position of the player
# The direction vector is the direction the player will move

self.position = pygame.math.Vector2(x, y)
self.direction_vector = pygame.math.Vector2(Settings.INITIAL_LENGTH, 0) # Initial direction vector


def draw(self, show_line = True):
"""Draws the player and the direction vector on the screen."""
# Draw player (as a square)
pygame.draw.rect(screen, Settings.PLAYER_COLOR, (self.position.x - Settings.PLAYER_SIZE // 2, self.position.y - Settings.PLAYER_SIZE // 2, Settings.PLAYER_SIZE, Settings.PLAYER_SIZE))

# Calculate the end point of the direction vector (line)
end_position = self.position + self.direction_vector

# Draw direction vector (line)
if show_line:
pygame.draw.line(screen, Settings.LINE_COLOR, self.position, end_position, 2)


def move(self):
"""Moves the player in the direction of the current angle."""

init_position = self.position

# Calculate the final position. You can just add the vectors!
final_position = self.position + self.direction_vector

#animate the movement
length = self.direction_vector.length()
N = int(length // 3)
step = (final_position - self.position) / N
for i in range(N):
self.position += step

screen.fill(Settings.BACKGROUND_COLOR)
self.draw(show_line=False)
pygame.draw.line(screen, Settings.LINE_COLOR, init_position, final_position, 2)
pygame.display.flip()
clock.tick(Settings.FPS)

def main():
player = Player(Settings.SCREEN_WIDTH // 2, Settings.SCREEN_HEIGHT // 2)
running = True

while running:
screen.fill(Settings.BACKGROUND_COLOR)

for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

keys = pygame.key.get_pressed()
# Change the angle with left and right arrows


if keys[pygame.K_LEFT]:
player.direction_vector = player.direction_vector.rotate(-Settings.ANGLE_CHANGE)
if keys[pygame.K_RIGHT]:
player.direction_vector = player.direction_vector.rotate(Settings.ANGLE_CHANGE)

# Change the length of the direction vector with up and down arrows
if keys[pygame.K_UP]:
player.direction_vector.scale_to_length(player.direction_vector.length() + Settings.LENGTH_CHANGE)
if keys[pygame.K_DOWN]:
new_length = max(10, player.direction_vector.length() - Settings.LENGTH_CHANGE) # Prevent length from going below 10
player.direction_vector.scale_to_length(new_length)
# Move the player when spacebar is pressed

if keys[pygame.K_SPACE]:
player.move()

# Draw the player and the direction vector
player.draw()

pygame.display.flip()
clock.tick(Settings.FPS)

pygame.quit()

if __name__ == "__main__":
main()
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"""
Gravity bounce in Object Oriented style
Gravity bounce using Vectors.
This version of the Gravity Bounce program uses Pygame's Vector2 class to handle
the player's position and velocity. This makes the code more readable and
understandable, and makes it easier to add more complex features to the game.
This version of the gravity bounce program uses an object oriented style to
organize the code. The main game loop is in the Game class, and the player is
a separate class. This makes the code easier to read and understand, and
allows for more complex games with multiple objects.
"""
import pygame
Expand Down Expand Up @@ -114,6 +114,10 @@ def going_right(self):

# Location Fuctions

def at_top(self):
"""Check if the player is at the top of the screen"""
return self.pos.y <= 0

def at_bottom(self):
"""Check if the player is at the bottom of the screen"""
return self.pos.y >= self.game.settings.height - self.height
Expand Down Expand Up @@ -144,6 +148,9 @@ def update_v(self):
self.vel.y = 0
self.is_jumping = False

if self.at_top() and self.going_up():
self.vel.y = -self.vel.y # Bounce off the top.

# If the player hits one side of the screen or the other, bounce the
# player. we are also checking if the player has a velocity going farther
# off the screeen, because we don't want to bounce the player if it's
Expand All @@ -159,10 +166,18 @@ def update_pos(self):
# If the player is at the bottom, stop the player from falling and
# stop the jump

# IMPORTANT! Notice that we don't also check "going_down()" here. This
# is because this code just limits how far off screen the player can go,
# and with the next velocity update, the player will bounce off the
# edge, so we don't need to check direction.

if self.at_bottom():
self.pos.y = self.game.settings.height - self.height

# Don't let the player go off the left side of the screen
if self.at_top():
self.pos.y = 0

# Don't let the player go off the left side of the screen
if self.at_left():
self.pos.x = 0

Expand Down
42 changes: 42 additions & 0 deletions lessons/00_Getting_Started/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Python Games: Getting Started

Welcome to the second module of The LEAGUE's Python curriculum. This module is all about games,
and it works a bit differently than the previous modules. Instead of learning a series of lessons,
you will be building games using PyGame by reading and analysing existing Pygame programs.

## Viewing Markdown Files

First things is that this curriculum will have many lesson files that will be in
the form of a README.md file. THe '.md' extension means "Markdown", which is a
way to format text. Its like a simple verions of HTML. While you can read
Markdown files in a text editor, they are best viewed in a Markdown viewer. If
the first line of this file looks like "# Python Games: Getting Started", then
you are reading this in a text editory, and you should open it in a Markdown
viewer.

To open the Markdown viewer, go to the file entry in the explorer window on the
left of the screen ( in VSCode ) and right click to get the pop up menu. Then
select "Open Preview". This will open the file in the Markdown viewer.

The Markdown files will nearly always becalled "README.md", but sometimes there will be
markdown files with other names.

## Reading Code

There will only be a few traditional lessons in this module, and they will be
short. Most of what you will learn will be from reading and analyzing code. This
is a very important skill for a programmer. Each lesson or assignment will be in
a directory with a README.md file that will explain what you need to do.

You will also need to read the Pygame documentation. You can find it at:

[https://www.pygame.org/docs/](https://www.pygame.org/docs/)


## Assignment

1. Copy `examples/01-move.py` into this directory.
2. Run the program and see what it does.
3. Read the code and try to understand how it works.
4. Read the Pygame documentation for [pygame.draw](https://www.pygame.org/docs/ref/draw.html) and change the program to draw a circle.
5. Read the documentation for [pygame.key](https://www.pygame.org/docs/ref/key.html) and change the program to move the circle with the `W`, `A`, `S`, and `D` keys.
Loading

0 comments on commit 2cf3b6d

Please sign in to comment.