View on GitHub

Making a Game of IT

Michigan State University - Summer 2019

Camper Games!

Team - Aperture Science

Game: Portal2D

'''
2D Portal Game
'''
import time
import sys
import random
import pygame
import math

# Constants
FPS = 60
SCREEN_WIDTH = 1200
SCREEN_HEIGHT = 615
BTN_PADDING = 10    # How much padding are we going to put around a button?
BTN_MARGIN = 10     # How much space do we want around button text?

# Colors
GREEN = [10, 230, 20]
WHITE = [255, 255, 255]
GREY = [175, 175, 175]
BLACK = [0, 0, 5]
YELLOW = [255, 229, 153]
DARKER_YELLOW = [255, 217, 102]
ORANGE = [255, 165, 0]
ASCREEN = pygame.image.load("title.png")


pygame.init() # As always, initialize pygame

screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
clock = pygame.time.Clock()
menu_font = pygame.font.SysFont('impact', 32)   # Here's our button font
print("Loaded the font!")
screen_mode = 'title'   # Modes: title, menu

menu_btn_color = WHITE
menu_btn_hover_color = GREY


################################################################################
# Title screen components
################################################################################
title_screen_bg = pygame.image.load("title.png")

##############################################################################
                # Level Menu
##############################################################################

Levels_screen_bg = pygame.image.load("Levels.png")

Levels_screen_buttons = ['Level One', 'Level Two', 'Level Three', 'back'] # Available buttons
cur_menu_btn_id = 0                                # What button are we currently on?
btn_color = YELLOW
# === Title text ===
title_font = pygame.font.SysFont('impact', 128)
title_surface = title_font.render('PORTAL', True, WHITE)
title_rect = title_surface.get_rect()
title_rect.x = 50
title_rect.y = 300
# === Open menu button ===
Levels_btn_txt_surface = menu_font.render('back', True, BLACK)
menu_btn_txt_surface = menu_font.render('Start', True, BLACK)
Levels_btn_bg_rect = Levels_btn_txt_surface.get_rect()
menu_btn_bg_rect = menu_btn_txt_surface.get_rect()
#size correctly
menu_btn_bg_rect.width += (2*BTN_MARGIN)
menu_btn_bg_rect.height += (2*BTN_MARGIN)
#position it
menu_btn_bg_rect.x = title_rect.midbottom[0] - (menu_btn_bg_rect.width / 2)
menu_btn_bg_rect.y = title_rect.midbottom[1] + BTN_PADDING

menu_btn_txt_rect = menu_btn_txt_surface.get_rect()
menu_btn_txt_rect.x = title_rect.midbottom[0] - (menu_btn_txt_rect.width / 2)
menu_btn_txt_rect.y = title_rect.midbottom[1] + BTN_PADDING + BTN_MARGIN

# === Level One button ===
# Render Level_One btn text onto surface
Level_One_btn_txt_surface = menu_font.render('Level One', True, BLACK)
# Setup Level_One button background
Level_One_btn_bg_rect = Level_One_btn_txt_surface.get_rect()
Level_One_btn_bg_rect.width += 2 * BTN_MARGIN
Level_One_btn_bg_rect.height += 2 * BTN_MARGIN
Level_One_btn_bg_rect.x = (SCREEN_WIDTH / 2) - (0.5 * Level_One_btn_bg_rect.width)
Level_One_btn_bg_rect.y = 50
# Setup the Level_One button text
Level_One_btn_txt_rect = Level_One_btn_txt_surface.get_rect()
Level_One_btn_txt_rect.x = Level_One_btn_bg_rect.x + BTN_MARGIN
Level_One_btn_txt_rect.y = Level_One_btn_bg_rect.y + BTN_MARGIN

# === Level_Two button ===
# Render Level_Two btn text onto surface
Level_Two_btn_txt_surface = menu_font.render('Level Two (not done)', True, BLACK)
# Setup Level_Two button background
Level_Two_btn_bg_rect = Level_Two_btn_txt_surface.get_rect()
Level_Two_btn_bg_rect.width += 2 * BTN_MARGIN
Level_Two_btn_bg_rect.height += 2 * BTN_MARGIN
Level_Two_btn_bg_rect.x = (SCREEN_WIDTH / 2) - (0.5 * Level_Two_btn_bg_rect.width)
Level_Two_btn_bg_rect.y = Level_One_btn_bg_rect.y + (Level_One_btn_bg_rect.height + BTN_PADDING)
# Setup the Level_Two button text
Level_Two_btn_txt_rect = Level_Two_btn_txt_surface.get_rect()
Level_Two_btn_txt_rect.x = Level_Two_btn_bg_rect.x + BTN_MARGIN
Level_Two_btn_txt_rect.y = Level_Two_btn_bg_rect.y + BTN_MARGIN

# === Level Three button ===
# Render quit btn text onto surface
Level_Three_btn_txt_surface = menu_font.render('Level Three (in progress)', True, BLACK)
# Setup quit button background
Level_Three_btn_bg_rect = Level_Three_btn_txt_surface.get_rect()
Level_Three_btn_bg_rect.width += 2 * BTN_MARGIN
Level_Three_btn_bg_rect.height += 2 * BTN_MARGIN
Level_Three_btn_bg_rect.x = (SCREEN_WIDTH / 2) - (0.5 * Level_Three_btn_bg_rect.width)
Level_Three_btn_bg_rect.y = Level_Two_btn_bg_rect.y + (Level_One_btn_bg_rect.height + BTN_PADDING)
# Setup the quit button text
Level_Three_btn_txt_rect = Level_Three_btn_txt_surface.get_rect()
Level_Three_btn_txt_rect.x = Level_Three_btn_bg_rect.x + BTN_MARGIN
Level_Three_btn_txt_rect.y = Level_Three_btn_bg_rect.y + BTN_MARGIN

# === Back Button =======
# Render back btn text onto surface
back_btn_txt_surface = menu_font.render('back', True, BLACK)
# Setup back button background
back_btn_bg_rect = back_btn_txt_surface.get_rect()
back_btn_bg_rect.width += 2 * BTN_MARGIN
back_btn_bg_rect.height += 2 * BTN_MARGIN
back_btn_bg_rect.x = (SCREEN_WIDTH) - (back_btn_bg_rect.width)
back_btn_bg_rect.y = 615 - 50
# Setup the back button text
back_btn_txt_rect = back_btn_txt_surface.get_rect()
back_btn_txt_rect.x = back_btn_bg_rect.x + BTN_MARGIN
back_btn_txt_rect.y = back_btn_bg_rect.y + BTN_MARGIN

#LEVEL ONE INFO
platform_height = 10
screen_rectangle = screen.get_rect()
bottom_platform = pygame.Rect(
            screen_rectangle.left,
            screen_rectangle.bottom - platform_height,
            screen_rectangle.right - screen_rectangle.left,
            platform_height)
level_one_walls = [
    bottom_platform,
    pygame.Rect([100, 520], [400, 10]),
    pygame.Rect([1, 425], [400, 10]),
    pygame.Rect([800, 425], [400, 10]),
    pygame.Rect([800, 425], [10, 190]),
    pygame.Rect([1, 1], [10, 615]),
    pygame.Rect([1190, 1], [10, 613]),
    pygame.Rect([700, 340], [200, 10]),
    pygame.Rect([800, 255], [400, 10]),
    pygame.Rect([1, 255], [500, 10]),
    pygame.Rect([250, 180], [10, 75])]
level_one_exit_rectangle = pygame.Rect([70, 280], [39, 75])
level_one_exit_img = pygame.image.load("exit_redone.png")
level_one_exit_rectangle = level_one_exit_img.get_rect()

target_img = pygame.image.load("portaltarget.png")
target_x = 0
target_y = 0

chell_location_x = 10
chell_location_y = 500
platform_height = 10
platform_color = WHITE
chell_velocity_x = 0 # Larger means moving faster rightwards
chell_velocity_y = 0 # Larger means moving faster downwards
GRAVITATIONAL_CONSTANT = 0.1
is_standing = False

chell_left = pygame.image.load("chell_blue_standingleft.png")
chell_right = pygame.image.load("chell_blue_standing.png")
chell_img = chell_right
chell_rectangle = chell_img.get_rect()

mouse_pos = [0,0]

proj_rect = pygame.rect.Rect(0, 0, 10, 10)
proj_x = 0
proj_y = 0

proj_speed = 8


direction = [0, 0]

blue_portal_rect = pygame.rect.Rect(0, 0, 5, 75)
orange_portal_rect = pygame.rect.Rect(0, 0, 5, 75)

pygame.mixer.music.load("background_music.ogg")
pygame.mixer.music.play(-1, 0.0)

blue_on = False
orange_on = False

portal_timeout = 0.5
last_tele = 0

pygame.mouse.set_visible(True)


##############################################################################
##############################################################################
                # Main Game Loop
##############################################################################
##############################################################################

# Game loop
while True:
    screen.blit(ASCREEN, [0,0])
    # We need to show different things depending on whether or not we're in 'title'
    # or 'menu' mode
    if screen_mode == 'title':
        # ==== TITLE SCREEN MODE ====
        # Draw the title screen
        # Render the title text in the middle of the screen
        screen.blit(title_surface, title_rect)
        # Draw the menu button, first: the text
        pygame.draw.rect(screen, menu_btn_color, menu_btn_bg_rect)
        screen.blit(menu_btn_txt_surface, menu_btn_txt_rect)

    elif screen_mode == 'Levels':
        # === MENU SCREEN MODE ===
        screen.blit(Levels_screen_bg, [0,0])
        # Draw button rectangles!
        # - If button is active, color background with hover color and an outline
        # - otherwise, draw with normal color and no outline
        if Levels_screen_buttons[cur_menu_btn_id] == 'back':
            pygame.draw.rect(screen, menu_btn_hover_color, back_btn_bg_rect)
            pygame.draw.rect(screen, BLACK, back_btn_bg_rect, 5)
        else:
            pygame.draw.rect(screen, menu_btn_color, back_btn_bg_rect)

        if Levels_screen_buttons[cur_menu_btn_id] == 'Level_One':
            pygame.draw.rect(screen, menu_btn_hover_color, Level_One_btn_bg_rect)
            pygame.draw.rect(screen, BLACK, Level_One_btn_bg_rect, 5)
        else:
            pygame.draw.rect(screen, menu_btn_color, Level_One_btn_bg_rect)


        if Levels_screen_buttons[cur_menu_btn_id] == 'Level_Two':
            pygame.draw.rect(screen, menu_btn_hover_color, Level_Two_btn_bg_rect)
            pygame.draw.rect(screen, BLACK, Level_Two_btn_bg_rect, 5)
        else:
            pygame.draw.rect(screen, menu_btn_color, Level_Two_btn_bg_rect)



        if Levels_screen_buttons[cur_menu_btn_id] == 'Level_Three':
            pygame.draw.rect(screen, menu_btn_hover_color, Level_Three_btn_bg_rect)
            pygame.draw.rect(screen, BLACK, Level_Three_btn_bg_rect, 5)
        else:
            pygame.draw.rect(screen, menu_btn_color, Level_Three_btn_bg_rect)
        # Layer button text over button backgrounds
        screen.blit(Level_One_btn_txt_surface, Level_One_btn_txt_rect)
        screen.blit(Level_Two_btn_txt_surface, Level_Two_btn_txt_rect)
        screen.blit(Level_Three_btn_txt_surface, Level_Three_btn_txt_rect)
        screen.blit(back_btn_txt_surface, back_btn_txt_rect)
        ########################################################################################################
        # PHYSICAL OUTLOOK OF EACH LEVEL. INSERT CODE BELOW.
        #########################################################################################################

    elif screen_mode == "Level_One":
        screen.fill(BLACK)
        screen.blit(target_img, [target_x, target_y])
        for wall in level_one_walls:
            pygame.draw.rect(screen, WHITE ,wall)

        if blue_on == True:
            pygame.draw.rect(screen, [100, 100, 255], blue_portal_rect)
        if orange_on == True:
            pygame.draw.rect(screen, [255, 165, 0], orange_portal_rect)
        if time.time() - last_tele > portal_timeout and blue_on == True and orange_on == True:
            if chell_rectangle.colliderect(blue_portal_rect):
                chell_rectangle.center = orange_portal_rect.center
                last_tele = time.time()


            elif chell_rectangle.colliderect(orange_portal_rect):
                chell_rectangle.center = blue_portal_rect.center
                last_tele = time.time()


        #Shooting
        if is_shooting == 'Blue'or is_shooting == 'Orange':

            direction = [mouse_pos[0] - chell_rectangle.left, mouse_pos[1] - chell_rectangle.top]
            normal = math.sqrt(direction[0] **2 + direction[1] **2)
            direction[0] /= normal
            direction[1] /= normal

            direction[0] *= proj_speed
            direction[1] *= proj_speed

            proj_x += direction[0]
            proj_y += direction[1]

            proj_rect.x = proj_x
            proj_rect.y = proj_y

            if is_shooting == 'Blue':
                pygame.draw.rect(screen, [100, 100, 255], proj_rect)
            elif is_shooting == 'Orange':
                pygame.draw.rect(screen, [255, 165, 0], proj_rect)

            if proj_rect.collidelist(level_one_walls) != -1:
                if is_shooting == 'Blue':
                    blue_on = True
                    blue_portal_rect.center = proj_rect.center
                else:
                    orange_on = True
                    orange_portal_rect.center = proj_rect.center
                is_shooting = ""


        ############################################################################################################
        #    Player Shooting and Movement
        ############################################################################################################

        if screen_mode == "Level_One" or screen_mode == "Level_Two" or screen_mode == "Level_Three":


            exit_img = pygame.image.load("exit_redone.png")
            exit_rectangle = exit_img.get_rect()
            screen_rectangle = screen.get_rect()
            bottom_platform = pygame.Rect(
            screen_rectangle.left,
            screen_rectangle.bottom - platform_height,
            screen_rectangle.right - screen_rectangle.left,
            platform_height)
            platforms = [bottom_platform]

            is_standing = False
            index = chell_rectangle.collidelist(level_one_walls)
            if index != -1:
                touching_platform = level_one_walls[index]
                is_just_touching_down = chell_rectangle.bottom - touching_platform.top < platform_height

                is_descending = chell_velocity_y > 0
                # is_descending = True

                if is_just_touching_down and is_descending:
                    chell_location_y = touching_platform.top - chell_rectangle.height
                    is_standing = True
                    chell_velocity_y = 0
            # Draw chell (this is the hardest because we need to use chell's
            # x and y location to determine where to place them).

            if chell_rectangle.colliderect(level_one_exit_rectangle):
                screen_mode = "Levels"
                pygame.mouse.set_visible(True)



            if chell_velocity_x >0:
                chell_img = chell_right
            if chell_velocity_x <0:
                chell_img = chell_left
            chell_rectangle.left += chell_velocity_x
            if chell_rectangle.left <= 0:
                chell_rectangle.left = 0
            elif chell_rectangle.right >= SCREEN_WIDTH:
                chell_rectangle.right = SCREEN_WIDTH
            chell_velocity_y += GRAVITATIONAL_CONSTANT
            chell_rectangle.top += chell_velocity_y

            print(chell_rectangle.top, GRAVITATIONAL_CONSTANT)
            if chell_rectangle.top <= 0:
                chell_rectangle.top = 0
            elif chell_rectangle.bottom >= SCREEN_HEIGHT:
                chell_rectangle.bottom = SCREEN_HEIGHT
            screen.blit(chell_img, chell_rectangle)
            screen.blit(level_one_exit_img, level_one_exit_rectangle)

    else:
        # ==== ???? MODE ====
        print("UNRECOGNIZED SCREEN MODE! Exiting.")
        pygame.quit()
        sys.exit()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        # ===== TITLE MODE EVENTS =====
        if screen_mode == 'title' and event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()
            if menu_btn_bg_rect.collidepoint(mouse_pos):
                screen_mode = 'Levels'
                cur_menu_btn_id = 0

        # ===== LEVELS MODE EVENTS =====
        if screen_mode == 'Levels' and event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()
            if back_btn_bg_rect.collidepoint(mouse_pos):
                screen_mode = 'title'
                cur_menu_btn_id = 0
                print("test")
        if screen_mode == 'Levels' and event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()
            if Level_One_btn_bg_rect.collidepoint(mouse_pos):
                screen_mode = 'Level_One'
                chell_rectangle.top = 500
                cur_menu_btn_id = 0
                print("test")

        if screen_mode == 'Level_One':
            if event.type == pygame.MOUSEBUTTONDOWN:
                pygame.mouse.set_visible(False)

                mouse_pos = pygame.mouse.get_pos()
                pressed = pygame.mouse.get_pressed()
                if pressed[0] == True:
                    is_shooting = 'Blue'
                elif pressed[2] == True:
                    is_shooting = 'Orange'
                proj_x, proj_y = chell_rectangle.center
            elif event.type == pygame.MOUSEMOTION:
                x, y = event.pos
                target_x = x
                target_y = y

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP and is_standing:
                # if event.key == pygame.K_UP
                # changing them to make chell jump or run faster.
                chell_velocity_y = -3.9
            if event.key == pygame.K_RIGHT:
                chell_velocity_x = 4
            if event.key == pygame.K_LEFT:
                chell_velocity_x = -4
        # This code ensures that when you release the left or right arrow keys
        # chell stops moving.
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_RIGHT:
                chell_velocity_x = 0
            if event.key == pygame.K_LEFT:
                chell_velocity_x = 0

    clock.tick(FPS)
    pygame.display.update()

|>> download student-games/aperture-science/game.py

Team - Arena Masters

Game: Rising Through the Rainbow

import sys
import random
import pygame
import itertools
import math

SCREEN_WIDTH = 1200
SCREEN_HEIGHT = 800
FPS = 60

BTN_PADDING = 10    # How much padding are we going to put around a button?
BTN_MARGIN = 10     # How much space do we want around button text?


RED = [255, 0, 0]
ORANGE = [ 255, 127, 0]
YELLOW = [255, 255,0]
GREEN = [0,255,0]
BLUE = [0,0,255]
INDIGO = [39, 0, 51]
VIOLET = [139, 0, 255]
LIGHT_GREY = [230, 230, 230]
BLACK = [0, 0, 0]
WHITE = [255, 255, 255]
DARKER_YELLOW = [255, 217, 102]
GREY = [175, 175, 175]


uw = 10
uh = 10
usx = 1100
usy = 700
us = 5

userHP = 50
tot_userHP = 50
user_color = RED
alreadyused = True

cuxv = 0
cuyv = 0
user = pygame.Rect([usx,usy],[uw,uh])

bullets = []
bvx = 10
bw = 7.5
bh = 5
absolute_speed = 10
bulletife = 10

tw = 20
th = 20
ts = 2
'''
bdamage =
bhealth =
bmaxhealth =

'''
print('Available fonts:', pygame.font.get_fonts())



pygame.init()
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
pygame.display.set_caption("RISING THROUGH THE RAINBOW")
clock = pygame.time.Clock()



menu_font = pygame.font.SysFont('impact', 32)   # Here's our button font
print("Loaded the font!")
screen_mode = 'title'   # Modes: title, menu

menu_btn_color = YELLOW
menu_btn_hover_color = DARKER_YELLOW

################################################################################
# Title screen components
################################################################################
title_screen_bg_color = BLACK
# === Title text ===
title_font = pygame.font.SysFont('impact', 70)
title_surface = title_font.render('RISING THROUGH THE RAINBOW', True, WHITE)
title_rect = title_surface.get_rect()
title_rect.x = (SCREEN_WIDTH/2) - (title_rect.width/2)# Put rect in middle of screen (perfectly in middle x)
title_rect.y = (SCREEN_HEIGHT/2) - (title_rect.height/2) # Put rect in middle of the screen (sitting on top of horizontal midline)

# === Open menu button ===
menu_btn_txt_surface = menu_font.render('open menu', True, BLACK)

menu_btn_bg_rect= menu_btn_txt_surface.get_rect()

menu_btn_bg_rect.width=menu_btn_bg_rect.width+ (2*BTN_MARGIN)
menu_btn_bg_rect.height=menu_btn_bg_rect.height+(2*BTN_MARGIN)

menu_btn_bg_rect.x = (SCREEN_WIDTH/2) - (menu_btn_bg_rect.width/2)
menu_btn_bg_rect.y = title_rect.bottom 

menu_btn_txt_rect = menu_btn_txt_surface.get_rect()
menu_btn_txt_rect.x = menu_btn_bg_rect.x + BTN_MARGIN
menu_btn_txt_rect.y = menu_btn_bg_rect.y + BTN_MARGIN

################################################################################
# Menu screen components
################################################################################
menu_screen_bg_color = GREY

menu_screen_buttons = ['Instructions', 'Arena', 'quit'] # Available buttons
cur_menu_btn_id = 0                                # What button are we currently on?
btn_color = YELLOW

# === Resume button ===
# Render resume btn text onto surface
resume_btn_txt_surface = menu_font.render('Instructions', True, BLACK)
# Setup resume button background
resume_btn_bg_rect = resume_btn_txt_surface.get_rect()
resume_btn_bg_rect.width += 2 * BTN_MARGIN
resume_btn_bg_rect.height += 2 * BTN_MARGIN
resume_btn_bg_rect.x = (SCREEN_WIDTH / 2) - (0.5 * resume_btn_bg_rect.width)
resume_btn_bg_rect.y = 50
# Setup the resume button text
resume_btn_txt_rect = resume_btn_txt_surface.get_rect()
resume_btn_txt_rect.x = resume_btn_bg_rect.x + BTN_MARGIN
resume_btn_txt_rect.y = resume_btn_bg_rect.y + BTN_MARGIN

# === Random button ===
# Render random btn text onto surface
random_btn_txt_surface = menu_font.render('Arena', True, BLACK)
# Setup random button background
random_btn_bg_rect = random_btn_txt_surface.get_rect()
random_btn_bg_rect.width += 2 * BTN_MARGIN
random_btn_bg_rect.height += 2 * BTN_MARGIN
random_btn_bg_rect.x = (SCREEN_WIDTH / 2) - (0.5 * random_btn_bg_rect.width)
random_btn_bg_rect.y = resume_btn_bg_rect.y + (resume_btn_bg_rect.height + BTN_PADDING)
# Setup the random button text
random_btn_txt_rect = random_btn_txt_surface.get_rect()
random_btn_txt_rect.x = random_btn_bg_rect.x + BTN_MARGIN
random_btn_txt_rect.y = random_btn_bg_rect.y + BTN_MARGIN

# === Quit button ===
# Render quit btn text onto surface
quit_btn_txt_surface = menu_font.render('Quit', True, BLACK)
# Setup quit button background
quit_btn_bg_rect = quit_btn_txt_surface.get_rect()
quit_btn_bg_rect.width += 2 * BTN_MARGIN
quit_btn_bg_rect.height += 2 * BTN_MARGIN
quit_btn_bg_rect.x = (SCREEN_WIDTH / 2) - (0.5 * quit_btn_bg_rect.width)
quit_btn_bg_rect.y = random_btn_bg_rect.y + (resume_btn_bg_rect.height + BTN_PADDING)
# Setup the quit button text
quit_btn_txt_rect = quit_btn_txt_surface.get_rect()
quit_btn_txt_rect.x = quit_btn_bg_rect.x + BTN_MARGIN
quit_btn_txt_rect.y = quit_btn_bg_rect.y + BTN_MARGIN
################################################################################
#Instruction Screen Components

#Instruction Text
Instruct_font = pygame.font.SysFont('impact', 70)
Instruct_surface = title_font.render('RISING THROUGH THE RAINBOW', True, WHITE)
Instruct_rect = title_surface.get_rect()
Instruct_rect.x = (SCREEN_WIDTH/2) - (title_rect.width/2)# Put rect in middle of screen (perfectly in middle x)
Instruct_rect.y = (SCREEN_HEIGHT/2) - (title_rect.height/2) # Put rect in middle of the screen (sitting on top of horizontal midline)

back_btn_txt_surface = menu_font.render('back', True, BLACK)

back_btn_bg_rect= menu_btn_txt_surface.get_rect()

back_btn_bg_rect.width=menu_btn_bg_rect.width+ (2*BTN_MARGIN)
back_btn_bg_rect.height=menu_btn_bg_rect.height+(2*BTN_MARGIN)

back_btn_bg_rect.x = (SCREEN_WIDTH/2) - (menu_btn_bg_rect.width/2)
back_btn_bg_rect.y = title_rect.bottom 

back_btn_txt_rect = menu_btn_txt_surface.get_rect()
back_btn_txt_rect.x = menu_btn_bg_rect.x + BTN_MARGIN
back_btn_txt_rect.y = menu_btn_bg_rect.y + BTN_MARGIN

#Arenabox

arena_box_rect = (20,20,1160,760)

#targets
targets = []
total_targets = []
dead_targets = []
directions = []
target_color = RED
for i in range(0,0):
    rand_x = random.randint(0,SCREEN_WIDTH-tw-30)
    rand_y = random.randint(0,SCREEN_HEIGHT-th-30)
    targets.append(pygame.Rect([rand_x,rand_y],[tw,th]))
    total_targets.append(pygame.Rect([rand_x,rand_y],[tw,th]))
print(len(targets),len(directions))
frame = 0
aim = 0

# Game loop
while True:
    # We need to show different things depending on whether or not we're in 'title'
    # or 'menu' mode
    if screen_mode == 'title':
        # ==== TITLE SCREEN MODE ====
        screen.fill(title_screen_bg_color)
        # Draw the title screen
        # Render the title text in the middle of the screen

        screen.blit(title_surface, title_rect)
        # Draw the menu button, first: the text
        pygame.draw.rect(screen, menu_btn_color, menu_btn_bg_rect)
        screen.blit(menu_btn_txt_surface, menu_btn_txt_rect)
    
    elif screen_mode == 'menu':
        # === MENU SCREEN MODE ===
        screen.fill(menu_screen_bg_color)
        # Draw button rectangles!
        # - If button is active, color background with hover color and an outline
        # - otherwise, draw with normal color and no outline
        if menu_screen_buttons[cur_menu_btn_id] == 'Instructions':
            pygame.draw.rect(screen, menu_btn_hover_color, resume_btn_bg_rect)
            pygame.draw.rect(screen, BLACK, resume_btn_bg_rect, 5)
        else:
            pygame.draw.rect(screen, menu_btn_color, resume_btn_bg_rect)

        if menu_screen_buttons[cur_menu_btn_id] == 'Arena':
            pygame.draw.rect(screen, menu_btn_hover_color, random_btn_bg_rect)
            pygame.draw.rect(screen, BLACK, random_btn_bg_rect, 5)
        else:
            pygame.draw.rect(screen, menu_btn_color, random_btn_bg_rect)

        if menu_screen_buttons[cur_menu_btn_id] == 'quit':
            pygame.draw.rect(screen, menu_btn_hover_color, quit_btn_bg_rect)
            pygame.draw.rect(screen, BLACK, quit_btn_bg_rect, 5)
        else:
            pygame.draw.rect(screen, menu_btn_color, quit_btn_bg_rect)

        # Layer button text over button backgrounds
        screen.blit(resume_btn_txt_surface, resume_btn_txt_rect)
        screen.blit(random_btn_txt_surface, random_btn_txt_rect)
        screen.blit(quit_btn_txt_surface, quit_btn_txt_rect)
    elif screen_mode == 'Instructions':
        screen.fill(menu_screen_bg_color)
        screen.blit(Instruct_surface, Instruct_rect)
        pygame.draw.rect(screen, menu_btn_color, back_btn_bg_rect)
        screen.blit(back_btn_txt_surface, back_btn_txt_rect)
    
    elif screen_mode == 'Arena1':
        screen.fill([247,197,143])
        pygame.draw.rect(screen, BLACK, arena_box_rect)
        HP_font = pygame.font.SysFont('impact', 42)
        HP = HP_font.render('Health: ' + str(userHP), True, user_color)
        HP_rect = HP.get_rect()
        HP_rect.x = 950
        HP_rect.y = 50
        DEATH_font = pygame.font.SysFont('impact', 42)
        DEATH = HP_font.render('Kills: ' + str(len(dead_targets)), True, user_color)
        DEATH_rect = HP.get_rect()
        DEATH_rect.x = 950
        DEATH_rect.y = 100
        screen.blit(HP,HP_rect)
        screen.blit(DEATH,DEATH_rect)
        pressed_keys = pygame.key.get_pressed()
        if pressed_keys[pygame.K_UP]:
            print("up arrow")
            cuyv = -1*us
        elif pressed_keys[pygame.K_DOWN]:
            print("down arrow")
            cuyv = us
        else:
            cuyv = 0
        if pressed_keys[pygame.K_RIGHT]:
            print("right arrow")
            cuxv = us
        elif pressed_keys[pygame.K_LEFT]:
            print("LEFT!!!!")
            cuxv = -1*us
        else:
            cuxv = 0

        user.left += cuxv
        user.top += cuyv
        pygame.draw.rect(screen, user_color, user)
        usx,usy = user.topleft
        aim_y = absolute_speed * math.sin(aim * (math.pi / 180))
        aim_x = -1 * (absolute_speed * math.cos(aim * (math.pi / 180)))
        pygame.draw.line(screen, user_color,[usx,usy],[usx+aim_x,usy+aim_y])
        
        for target in targets:
            if user.colliderect(target):
                userHP = userHP - 1
                print("HP:",userHP)
                if userHP <= 0:
                    screen_mode = 'title'
                    userHP = 50
                    targets = []
                    dead_targets = []
                    
        
        on_screen_bullets=[]
        for bullet_rect, bullet_x_vel, bullet_y_vel, bullet_life in bullets:
            bullet_rect.left += bullet_x_vel
            bullet_rect.top += bullet_y_vel
            pygame.draw.rect(screen,RED,bullet_rect)
                   #insert enemy death count here
            alive_targets = []
            for target in targets:
                if bullet_rect.colliderect(target):
                    dead_targets.append(target)
                    print("Deaths:",len(dead_targets))
                    print(random.choice(["AAAAHHHH","GRUNT", "UUUGGG", "SPLAT", "POP"]))
                    continue
                alive_targets.append(target)
               
            targets = alive_targets
        
            
 
            if bullet_rect.left <= SCREEN_WIDTH and bullet_life > 0:
                on_screen_bullets.append((bullet_rect, bullet_x_vel, bullet_y_vel, bullet_life - 1))
        bullets = on_screen_bullets
        
        for i in range(0, len(targets)):
            
            if directions[i][0] == 0 or targets[i].y < 100:
                targets[i].y =  targets[i].y + ts
            else:
                targets[i].y = targets[i].y - ts
            
            
            if directions[i][1] == 0 or targets[i].x < 100:
                targets[i].x =  targets[i].x + ts
            else:
                targets[i].x = targets[i].x - ts
            pygame.draw.rect(screen, target_color, targets[i])
                
        if frame % 50 == 0:
            direction = random.randint(0,1)
            direction1 = random.randint(0,1)
            target = pygame.Rect([0,25],[tw,th])
            targets.append(target)
            total_targets.append(target)
            directions.append([direction,direction1])
            for direction in directions:
                direction [0] = random.randint(0,1)
                direction [1] = random.randint(0,1)
            if len(dead_targets) >= 500:
                target_color = WHITE
                ts = 50
            elif len(dead_targets) > 480:
                target_color = PURPLE
                ts = 8.5
                user_color = PURPLE
                print("VICTORY!")
                us = 9
                bullet_life = 50
                if alreadyused == False:
                    userHP = 1000
                    alreadyused = True
            elif len(dead_targets) > 410:
                target_color = PURPLE
                ts = 8.5
                #userHP = user_HP + 50 
            elif len(dead_targets) > 360:
                target_color = INDIGO
                ts = 7.5
                user_color = INDIGO
                us = 8
                bullet_life = 30
                if alreadyused == True:
                    user_HP = 800
                    alreadyused == False
            elif len(dead_targets) > 300:
                target_color = INDIGO
                ts = 7.5
                #userHP = userHP + 45 
            elif len(dead_targets) > 250:
                target_color = BLUE
                ts = 6
                user_color = BLUE
                us = 7.5
                bullet_life = 12
                if alreadyused == False:
                    userHP = 600
                    alreadyused = True
            elif len(dead_targets) > 250:
                target_color = BLUE
                ts = 6
                #userHP = userHP + 40
            elif len(dead_targets) > 220:
                target_color = GREEN
                ts = 4.5
                user_color = GREEN
                us = 7
                if alreadyused == True:
                    userHP = 400
                    alreadyused = False
            elif len(dead_targets) > 180:
                target_color = GREEN
                ts = 4.5
                #userHP = userHP + 30
            elif len(dead_targets) > 130:
                target_color = YELLOW
                ts = 3.5
                user_color = YELLOW
                us = 6.5
                if alreadyused == False:
                    userHP = 200
                    alreadyused = True
            elif len(dead_targets) > 100:
                target_color = YELLOW
                ts = 3.5
                #userHP = userHP + 25
            elif len(dead_targets) > 50:
                target_color = ORANGE
                ts = 2.5
                user_color = ORANGE
                us = 5.5
                if alreadyused == True:
                    userHP = 100
                    alreadyused = False
            elif len(dead_targets) > 30:
                target_color = ORANGE
                ts = 2.5
                #userHP  = userHP + 20
            else:
                target_color = RED
                
                
        print(len(targets))
    else:
        
        print("AAAH UNRECOGNIZED SCREEN MODE! Exiting")
        pygame.quit()
        sys.exit()
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        # ===== TITLE MODE EVENTS =====
        if screen_mode == 'title' and event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()
            if menu_btn_bg_rect.collidepoint(mouse_pos):
                screen_mode = 'menu'
                cur_menu_btn_id = 0
        if screen_mode == 'Instructions' and event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()
            if back_btn_bg_rect.collidepoint(mouse_pos):
                screen_mode = 'title'
                cur_menu_btn_id = 0
            

        # ===== MENU MODE EVENTS =====
        if screen_mode == 'menu' and event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                # player presses down arrow
                cur_menu_btn_id = (cur_menu_btn_id + 1) % len(menu_screen_buttons)
            if event.key == pygame.K_UP:
                # player presses up arrow
                cur_menu_btn_id = (cur_menu_btn_id - 1) % len(menu_screen_buttons)
            if event.key == pygame.K_RETURN:
                # Player presses return (selects current option)
                if menu_screen_buttons[cur_menu_btn_id] == 'Instructions':
                    # if on resume button, go back to title screen
                    screen_mode = 'Instructions'
                elif menu_screen_buttons[cur_menu_btn_id] == 'Arena':
                    # if on random ('???') button, randomize background color
                    menu_screen_bg_color = [random.randint(0, 255),
                                            random.randint(0, 255),
                                            random.randint(0, 255)]
                    screen_mode ='Arena1'
        
                elif menu_screen_buttons[cur_menu_btn_id] == 'quit':
                    # if on quit button, quit the game
                    pygame.quit()
                    sys.exit()

        if screen_mode == 'Arena1' and event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
               print("pressed space")
               print(len(dead_targets))
               print(user.midright)
               pos = user.midright
               bullet_rect = pygame.Rect(pos[0], pos[1], bw, bh)
               variance_angle = 20
               
               angle = aim + 20
               
               bullet_y_vel = absolute_speed * math.sin(aim * (math.pi / 180))
               bullet_x_vel = -1 * (absolute_speed * math.cos(aim * (math.pi / 180)))
               bullet_life = bulletife
               bullets.append((bullet_rect, bullet_x_vel, bullet_y_vel, bullet_life))
               print(bullet_x_vel,bullet_y_vel)
            if event.key == pygame.K_w:
                aim -= 10
                if aim <= -20:
                    aim = -20
            if event.key == pygame.K_s:
                aim += 10
                if aim >= 20:
                    aim = 20
        
    

    frame = frame + 1
    clock.tick(FPS)
    pygame.display.update()


|>> download student-games/arena-masters/game.py

Team - get_rekt()

Game: .get_rekt()

import sys
import random
import pygame
import time

pygame.init()

#OBJECTIVES
#ENEMIES (Spawn more enemies + spawn powerups on dead enemies)

#AMMO (AMMO IF POSSIBLE)
#MAYBE DIFFERENT WEAPONS

# ---Standard Variables---
fps = 60
scrn_w = 1200 #Width
scrn_h = 800 #Height
btn_padding = 10
btn_margin = 10
got_time = 0
got_speed = False
got_freeze = False
# ---Screen & Clock---
screen = pygame.display.set_mode([scrn_w, scrn_h])
clock = pygame.time.Clock()

# ---Music---
pygame.mixer.music.load('lofi.ogg')
pygame.mixer.music.play(-1)


# ---Colors---
BLACK = [0, 0, 5]
GREY = [175, 175, 175]
WHITE = [255, 255, 255]
RED = [220,60,50]
DARK_RED = [125, 0, 0]
GREEN = [80,200,25]
DARK_GREEN = [5, 150, 10]
BLUE = [25,90,170]
LIGHT_BLUE = [120,195,225]
ORANGE = [255,120,0]

# ---Different Screens---

screen_mode = "title"

###########
# ---Title Screen---
title_scrn_color = GREY
title_font = pygame.font.SysFont('impact', 100)
title_button_font = pygame.font.SysFont('impact',30)
#    ---- Title Text & Buttons ----
#Title Text
title_surface = title_font.render("GET_REKT()", True,BLUE)#Color needed
title_rect = title_surface.get_rect()
title_rect.x = (scrn_w / 2) - (title_rect.width / 2)
title_rect.y = (scrn_h / 2) - (title_rect.height)

# Title Button
title_btn_txt_surface = title_button_font.render("Start Game", True,BLACK)#Color needed
# Title Button Background
title_btn_bg_rect = title_btn_txt_surface.get_rect()
title_btn_bg_rect.width += 2 * btn_margin
title_btn_bg_rect.height += 2 * btn_margin
title_btn_bg_rect.x = title_rect.midbottom[0] - (title_btn_bg_rect.width / 2)
title_btn_bg_rect.y = title_rect.midbottom[1]
# Title Button Text
title_btn_txt_rect = title_btn_txt_surface.get_rect()
title_btn_txt_rect.x = title_btn_bg_rect.x + btn_margin
title_btn_txt_rect.y = title_btn_bg_rect.y + btn_margin


###########
# ---Power Ups---

def generate_powerup(name=''):
    rx = random.randint(50,400)
    rxt = random.randint(800,1150)

    ry = random.randint(50,300)
    ryt = random.randint(500,750)
    PU_start_x = random.choice([rx,rxt])
    PU_start_y = random.choice([ry,ryt])

    health = pygame.Rect([PU_start_x,PU_start_y],[15,15])
    speed = pygame.Rect([PU_start_x,PU_start_y],[15,15])
    freeze = pygame.Rect([PU_start_x,PU_start_y],[15,15])

    powerups = [
        {'name': 'health', 'rect': health},
        {'name': 'speed', 'rect': speed},
        {'name': 'freeze', 'rect': freeze}]

    return next(i for i in powerups if i['name'] == name) if name else random.choice(powerups)


current_powerups = [generate_powerup()]


###########
# ---Weapons---
weapon_start_x = random.randint(0,1200)
weapon_start_y = random.randint(0,800)

revolver = pygame.Rect([weapon_start_x,weapon_start_y],[15,15])
tommy = pygame.Rect([weapon_start_x,weapon_start_y],[15,15])
shotgun = pygame.Rect([weapon_start_x,weapon_start_y],[15,15])


weapons = [revolver, tommy, shotgun]
weapon_mode = 0
ammunition = 0



###########
# ---Enemies---
enemies_color = RED
enemies = []
amount_enemies = 3
enemy_width = 22
enemy_height = 22
enemy_speed = 2

safe_space = pygame.Rect(200,200,800,400)

def get_enemy_rect():
    while True:
        enemy_width = 22
        enemy_height = 22
        enemy_x = random.randint(0,900)
        enemy_y = random.randint(0,900)

        # print(enemy_x,", ", enemy_y)

        enemy_rect = pygame.Rect([enemy_x,enemy_y],[enemy_width,enemy_height])
        if not enemy_rect.colliderect(safe_space):
            return enemy_rect

for i in range(amount_enemies):
    enemies.append(get_enemy_rect())


###########
# ---Lives/Player---
char_start_x = title_rect.x - 23
char_start_y = title_rect.y + 80
char_width = 22
char_height = 22
char_speed = 3
cur_char_x_vel = 0
cur_char_y_vel = 0
character = pygame.Rect([char_start_x, char_start_y], [char_width, char_height])

direction = "right"

lives = 3
lives_font = pygame.font.SysFont('impact', 30)

###########
# ---Projectiles---
projectiles = []
projectile_width = 10
projectile_height = 5

projectile_color = BLACK
projectile_speed = 5
projectile_direction = []
#Projectile Rectangle is by the pygame.K_Space event


###########
# ---Death Screen---
death_scrn_color = BLACK
death_font = pygame.font.SysFont('impact', 100)
death_button_font = pygame.font.SysFont('impact',30)

death_surface = death_font.render("U.GOT_REKT()", True,DARK_RED)#Color needed
death_rect = title_surface.get_rect()
death_rect.x = (scrn_w / 2) - (death_rect.width / 2)
death_rect.y = (scrn_h / 2) - (death_rect.height)

death_btn_txt_surface = death_button_font.render("Play Again?", True,BLACK)#Color needed
# Title Button Background
death_btn_bg_rect = death_btn_txt_surface.get_rect()
death_btn_bg_rect.width += 2 * btn_margin
death_btn_bg_rect.height += 2 * btn_margin
death_btn_bg_rect.x = death_rect.midbottom[0] - (death_btn_bg_rect.width / 2)
death_btn_bg_rect.y = death_rect.midbottom[1]
# death Button Text
death_btn_txt_rect = death_btn_txt_surface.get_rect()
death_btn_txt_rect.x = death_btn_bg_rect.x + btn_margin
death_btn_txt_rect.y = death_btn_bg_rect.y + btn_margin

while True:

    if screen_mode == "title":
        screen.fill(title_scrn_color)
        screen.blit(title_surface, title_rect)
        pygame.draw.rect(screen,RED,title_btn_bg_rect)
        screen.blit(title_btn_txt_surface, title_btn_txt_rect)


        pressed_keys = pygame.key.get_pressed()
        if pressed_keys[pygame.K_UP]:
            cur_char_y_vel = -1*char_speed
            direction = "up"
        elif pressed_keys[pygame.K_DOWN]:
            cur_char_y_vel = char_speed
            direction = "down"
        else:
            cur_char_y_vel = 0
        if pressed_keys[pygame.K_RIGHT]:
            cur_char_x_vel = char_speed
            direction = "right"
        elif pressed_keys[pygame.K_LEFT]:
            cur_char_x_vel = -1*char_speed
            direction = "left"
        else:
            cur_char_x_vel = 0

        character.left += cur_char_x_vel
        if character.left <= 0:
            character.left = 0
        elif character.right >= scrn_w:
            character.right = scrn_w
        character.top += cur_char_y_vel
        if character.top <= 0:
            character.top = 0
        elif character.bottom >= scrn_h:
            character.bottom = scrn_h
        pygame.draw.rect(screen, DARK_GREEN, character)


        for powerup in current_powerups:
            rect = powerup['rect']
            name = powerup['name']
            pygame.draw.rect(screen, GREEN, rect)



        for i in range (0, len(projectiles)):

            pygame.draw.rect(screen, BLACK, projectiles[i])

        for i, projectile in enumerate(projectiles):
            if projectile_direction[i] == "up":
                projectile.top -= projectile_speed
            elif projectile_direction[i] == "right":
                projectile.right += projectile_speed
            elif projectile_direction[i] == "down":
                projectile.top += projectile_speed
            elif projectile_direction[i] == "left":
                projectile.left -= projectile_speed


    elif screen_mode == "play":
        screen.fill(WHITE)


        if got_freeze == True:
            cur_time = time.time()
            elapsed_time = int(cur_time - got_time)
            text = lives_font.render("Freeze: "+ str(2 - elapsed_time), True, BLACK)
            screen.blit(text, [50, 150])
            if elapsed_time > 2:
                got_freeze = False
                enemy_speed = 2


        if got_speed == True:
            cur_time = time.time()
            elapsed_time = int(cur_time - got_time)
            text = lives_font.render("Speed Boost: "+ str(5 - elapsed_time), True, BLACK)
            screen.blit(text, [50, 100])
            if elapsed_time > 5:
                got_speed = False
                char_speed -= 2



        current_time = time.time()
        elapsed = int(current_time - start_time)
        text = lives_font.render(str(elapsed), True, BLACK)

        pressed_keys = pygame.key.get_pressed()
        if pressed_keys[pygame.K_UP]:
            cur_char_y_vel = -1*char_speed
            direction = "up"
        elif pressed_keys[pygame.K_DOWN]:
            cur_char_y_vel = char_speed
            direction = "down"
        else:
            cur_char_y_vel = 0
        if pressed_keys[pygame.K_RIGHT]:
            cur_char_x_vel = char_speed
            direction = "right"
        elif pressed_keys[pygame.K_LEFT]:
            cur_char_x_vel = -1*char_speed
            direction = "left"
        else:
            cur_char_x_vel = 0

        character.left += cur_char_x_vel
        if character.left <= 0:
            character.left = 0
        elif character.right >= scrn_w:
            character.right = scrn_w
        character.top += cur_char_y_vel
        if character.top <= 0:
            character.top = 0
        elif character.bottom >= scrn_h:
            character.bottom = scrn_h
        pygame.draw.rect(screen, DARK_GREEN, character)

        for powerup in current_powerups:
            rect = powerup['rect']
            name = powerup['name']
            pygame.draw.rect(screen, GREEN, rect)
            if character.colliderect(rect):
                if name == 'health':

                    print('got health')
                    lives = lives + 1

                elif name == 'speed':

                    print('got speed')
                    char_speed += 2
                    got_time = time.time()
                    got_speed = True

                elif name == 'freeze':
                    print('frozen')
                    enemy_speed -= 2
                    got_time = time.time()
                    got_freeze = True
                else:
                    print('name is', name)
                current_powerups.remove(powerup)
                #current_powerups.append(generate_powerup())
            else:
                pass

        for i in range (0, len(projectiles)):

            pygame.draw.rect(screen, [197,212,208], projectiles[i])

        for i, projectile in enumerate(projectiles):
            if projectile_direction[i] == "up":
                projectile.top -= projectile_speed
            elif projectile_direction[i] == "right":
                projectile.right += projectile_speed
            elif projectile_direction[i] == "down":
                projectile.top += projectile_speed
            elif projectile_direction[i] == "left":
                projectile.left -= projectile_speed

        for enemy in enemies:
            pygame.draw.rect(screen, ORANGE , enemy)
        for enemy in enemies:
            if character.x > enemy.left:
                enemy.left += enemy_speed
            if character.x < enemy.left:
                enemy.left -= enemy_speed
            if character.y > enemy.top:
                enemy.top += enemy_speed
            if character.y < enemy.top:
                enemy.top -= enemy_speed

        if len(enemies) == 0 and screen_mode == "play":
            amount_enemies += 2
            for i in range(amount_enemies):
                enemies.append(get_enemy_rect())

        enemies_kill = []
        for i in reversed(range(len(enemies))):
            for project in range(len(projectiles)):
                if projectiles[project].colliderect(enemies[i]):
                    enemies_kill.append(i)
                    print("Enemy Died")
                    if random.random() <= 0.15:
                        current_powerups.append(generate_powerup())
                else:
                    pass


        for i in reversed(range(len(enemies))):
            if character.colliderect(enemies[i]):
                enemies_kill.append(i)
                lives -= 1
            else:
                pass

        a = []
        for i in range(0, len(enemies)):
            if i not in enemies_kill:
                a.append(enemies[i])
        enemies = a

        #for i in reversed(range(len(enemies_kill))):

         #   del enemies[i]



        lives_surface = lives_font.render('LIVES: ' + str(lives), True, BLACK)
        lives_rect = lives_surface.get_rect()
        lives_rect.x = scrn_w - lives_rect.width - 50
        lives_rect.y = 50


        screen.blit(lives_surface, lives_rect)
        screen.blit(text, (50, 50))
        if lives <= 0:
            screen_mode = "death"
    elif screen_mode == "death":
        score_txt_font = pygame.font.SysFont('impact',30)
        score_txt_surface = score_txt_font.render("Wave Enemies: "+str(amount_enemies), True,WHITE)
        score_txt_rect = score_txt_surface.get_rect()
        score_txt_rect.x = 50
        score_txt_rect.y = 50

        screen.fill(BLACK)
        screen.blit(death_surface, death_rect)
        pygame.draw.rect(screen,DARK_RED,death_btn_bg_rect)
        screen.blit(death_btn_txt_surface, death_btn_txt_rect)
        screen.blit(score_txt_surface,score_txt_rect)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                # Fire a bullet
                print("pressed space")
                print(direction)
                pos = [0,0]
                if direction == "up":
                    projectile_direction.append("up")
                    pos = character.midtop
                    h = projectile_width
                    w = projectile_height
                elif direction == "down":
                    projectile_direction.append("down")
                    pos = character.midbottom
                    h = projectile_width
                    w = projectile_height
                elif direction == "right":
                    projectile_direction.append("right")
                    pos = character.midright
                    h = projectile_height
                    w = projectile_width
                elif direction == "left":
                    projectile_direction.append("left")
                    pos = character.midleft
                    h = projectile_height
                    w = projectile_width
                projectile = pygame.Rect([pos[0], pos[1]], [w, h])
                projectiles.append(projectile)
        if screen_mode == 'title' and event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()
            if title_btn_bg_rect.collidepoint(mouse_pos):
                screen_mode = 'play'
                start_time = time.time()
        if screen_mode == 'death' and event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()
            if death_btn_bg_rect.collidepoint(mouse_pos):
                screen_mode = 'play'
                lives = 3
                start_time = time.time()
                amount_enemies = 3
                enemies = []
                for i in range(amount_enemies):
                    enemies.append(get_enemy_rect())

    clock.tick(fps)
    pygame.display.flip()

|>> download student-games/get_rekt/game.py

Team - Metal Rams

Game: Soul Catcher

#Game Code

import sys
import pygame


FPS = 60
SCREEN_WIDTH = 512
SCREEN_HEIGHT = 512

BTN_PADDING = 10    # How much padding are we going to put around a button?
BTN_MARGIN = 10     # How much space do we want around button text?


#Colors
WHITE = [255, 255, 255]
ANTI_WHITE = [236, 239, 241]
LIGHT_GREY = [207, 216, 219]

#Mid-Shades
LIGHT_S_GREY = [120, 144, 156]

#Dark Colors
CHARCOAL = [55, 71, 79]

pygame.init()

pygame.mixer.music.load('dead_silence_theme.mp3')
pygame.mixer.music.play(-1) 

GHOST_png = pygame.image.load('GHOST.png')
GHOST_png = pygame.transform.scale(GHOST_png, (100,100))

GRIMM_png = pygame.image.load('GRIMM.png')
GRIMM_png = pygame.transform.scale(GRIMM_png, (100,100))

MSG_png = pygame.image.load('MSG (2).png')
GHOST_x = 10
GHOST_y = 10
SPEED = 5

BACKGROUND_png = pygame.image.load('BACKGROUND.png')


screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
clock = pygame.time.Clock()
settings_font = pygame.font.SysFont('impact', 64)   # Here's our button font
print("Loaded the font!")
screen_mode = 'INTRO'   # Modes: intro, menu


NEW_ICON_png = pygame.image.load('NEW_ICON.png')
NEW_ICON_png = pygame.transform.scale(NEW_ICON_png, (256, 256))
NEW_ICON_rect = NEW_ICON_png.get_rect()
NEW_ICON_rect.x = (SCREEN_WIDTH / 2) - (NEW_ICON_rect.width / 2)
NEW_ICON_rect.y = (SCREEN_HEIGHT / 2) - NEW_ICON_rect.height

SCROLLER_png = pygame.image.load('ICONS/SCROLLER.png')
SCROLLER_png = pygame.transform.scale(SCROLLER_png, (64, 64))

TOMATO_png = pygame.image.load('TOMATO.png')
TOMATO_png = pygame.transform.scale(TOMATO_png, (32, 32))

LETTUCE_png = pygame.image.load('LETTUCE.png')
LETTUCE_png = pygame.transform.scale(LETTUCE_png, (32, 32))


play_text = settings_font.render("Start" , True, LIGHT_S_GREY)
play_rect = play_text.get_rect()
play_rect.x = (SCREEN_WIDTH / 2) - (play_rect.width / 2)
play_rect.y = (SCREEN_HEIGHT / 2) - play_rect.height + 100

scrolls = [
    {"img":SCROLLER_png, "goto": "GAME", "collected": False, "x": 300, "y": 400,"screen_mode": "GAME","msg": " Welcome player, Here's a little welcome gift to get you started; 3 Hearts, 2 Fireballs, Starter Scroll. Be wise about your choices from here on out. Good Luck on your journey! - F"},
    {"img":SCROLLER_png,"goto": "CRYPT", "collected": False, "x": 230, "y": 200, "screen_mode": "GAME","msg": " Congratulations! you have found your first scroll, there will be many more through out the game. Hopefully you will find them all. Good luck player on your journey!"},  
    {"img":GRIMM_png, "goto":"INTRO", "collected": False,"x": 0, "y": 0, "screen_mode": "CRYPT","msg": "..."},
    {"img":SCROLLER_png, "goto": "CRYPT", "collected" : False, "x": 25, "y": 400,"screen_mode": "CRYPT", "msg": "Beware of Grimm...-F"},
    {"img":TOMATO_png, "goto": "INTRO", "collected": False, "x": 362, "y":362, "screen_mode": "CRYPT", "msg": "Ouch!"}
    ]

setting_btn_color = ANTI_WHITE
setting_btn_hover_color = LIGHT_GREY

#TITLE SCREEN
title_screen_bg_color = LIGHT_GREY


setting_btn_txt_surface = settings_font.render('Settings', True, LIGHT_S_GREY)

setting_btn_bg_rect = setting_btn_txt_surface.get_rect()
setting_btn_bg_rect.width += 2 * BTN_MARGIN  # Add some margins to the button
setting_btn_bg_rect.height += 2 * BTN_MARGIN # Add margin to the button

setting_btn_bg_rect.x = NEW_ICON_rect.midbottom[0] - (setting_btn_bg_rect.width / 2)
setting_btn_bg_rect.y = NEW_ICON_rect.midbottom[1] + BTN_PADDING + BTN_MARGIN


#SETTING COMP
setting_screen_bg_color = CHARCOAL

setting_screen_buttons = ['Mute', 'Quit', 'Back to Home'] # Available buttons
cur_setting_btn_id = 0                    
btn_color = LIGHT_GREY

#SETTING BTN
setting_btn_txt_surface = settings_font.render('Settings', True, LIGHT_S_GREY)

# Setup Setting menu button background
setting_btn_bg_rect = setting_btn_txt_surface.get_rect()
setting_btn_bg_rect.width = setting_btn_bg_rect.width + (2*BTN_MARGIN)
setting_btn_bg_rect.height = setting_btn_bg_rect.height + (2*BTN_MARGIN)
setting_btn_bg_rect.x = (SCREEN_WIDTH /2) - (setting_btn_bg_rect.width / 2)
setting_btn_bg_rect.y = 0 #title_rect.bottom

# Setup txt rect
setting_btn_txt_rect = setting_btn_txt_surface.get_rect()
setting_btn_txt_rect.x = setting_btn_bg_rect.x + BTN_MARGIN
setting_btn_txt_rect.y = setting_btn_bg_rect.y + BTN_MARGIN



while True:

    
    if screen_mode == 'INTRO':
        for scroll in scrolls:
            scroll["collected"] = False
            if scroll["img"] == GRIMM_png:
                scroll["x"] = 0
                scroll["y"] = 0
        GHOST_x = (SCREEN_WIDTH / 2) - 100
        GHOST_y = SCREEN_HEIGHT - 100
        # ==== TITLE SCREEN MODE ====
        screen.fill(title_screen_bg_color)
        screen.blit(NEW_ICON_png, NEW_ICON_rect)
        pygame.draw.rect(screen, ANTI_WHITE, play_rect) 
        screen.blit(play_text, play_rect)
          
    
    elif screen_mode == 'Settings':
        # === MENU SCREEN MODE ===
        screen.fill(setting_screen_bg_color)
        if setting_screen_buttons[cur_setting_btn_id] == 'Mute':
            pygame.draw.rect(screen, setting_btn_hover_color, setting_btn_bg_rect)
            pygame.draw.rect(screen, CHARCOAL, setting_btn_bg_rect, 5)
 

        screen.blit(setting_btn_txt_surface)

    elif screen_mode == "GAME":
        screen.fill(WHITE)
        BLACK = [0, 0, 0] 
        screen.fill(BLACK)
        screen.blit(BACKGROUND_png, (0, 0))
        
    elif screen_mode == "CRYPT":
        screen.fill(LIGHT_S_GREY)
        for scroll in scrolls :
            if scroll["img"] == GRIMM_png:
                scroll["x"] = (GHOST_x + scroll["x"] * 99) / 100
                scroll["y"] = (GHOST_y + scroll["y"] * 99) / 100
    
    
    else:
        print("unknown.")



    if screen_mode == "CRYPT" or screen_mode == "GAME":
        pressed_keys = pygame.key.get_pressed()
        if pressed_keys[pygame.K_RIGHT] and not pressed_keys[pygame.K_LEFT]:
            GHOST_x = (GHOST_x + SPEED) % SCREEN_WIDTH
        elif pressed_keys[pygame.K_LEFT] and not pressed_keys[pygame.K_RIGHT]:
            GHOST_x = (GHOST_x - SPEED) % SCREEN_WIDTH
      
        if pressed_keys[pygame.K_UP] and not pressed_keys[pygame.K_DOWN]:
            GHOST_y = (GHOST_y - SPEED) % SCREEN_HEIGHT
        elif pressed_keys[pygame.K_DOWN] and not pressed_keys[pygame.K_UP]:
            GHOST_y = (GHOST_y + SPEED) % SCREEN_HEIGHT
        
        screen.blit(GHOST_png, [GHOST_x, GHOST_y])
        
    ghost_rect = GHOST_png.get_rect()
    ghost_rect.x = GHOST_x
    ghost_rect.y = GHOST_y
    for scroll in scrolls:
        scroll_rect = scroll["img"].get_rect()
        scroll_rect.x = scroll["x"]
        scroll_rect.y = scroll["y"]
        if scroll["screen_mode"] == screen_mode and not scroll["collected"]:
            screen.blit(scroll["img"], [scroll["x"], scroll["y"]])
            if ghost_rect.colliderect(scroll_rect):
                scroll["collected"]= True
                print("=" * 20)
                print(scroll["msg"]) 
                print("=" * 20)
                screen_mode = scroll["goto"]
                
            for other in scrolls:
                other_rect = other["img"].get_rect()
                other_rect.x = other["x"]
                other_rect.y = other["y"]
                if other["img"] == scroll["img"]:
                    continue
                elif other["img"] == TOMATO_png and other_rect.colliderect(scroll_rect):
                    scroll["collected"] = True
                    print("OUCH! It burns!")
                    print("You coming too?")
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN and screen_mode == "INTRO":
            print("test") 
            mouse_pos = pygame.mouse.get_pos() 
            if play_rect.collidepoint(mouse_pos):
                screen_mode = 'GAME'
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN:
               pass
            elif event.key == pygame.K_UP:
               GHOST_y -= + SPEED
            elif event.key == pygame.K_LEFT:
               GHOST_x -= + SPEED
            elif event.key == pygame.K_DOWN:
               GHOST_y -= - SPEED
            elif event.key == pygame.K_RIGHT:
               GHOST_x -= - SPEED
              
        # ===== TITLE MODE EVENTS =====
        
          

    clock.tick(FPS)
    pygame.display.update()









|>> download student-games/metal-rams/game.py

Team - P(ython) Team

Game: Take Aim

'''
Bullet shooter game
'''

import sys
import random
import pygame
import math

pygame.init()

# let's try to avoid magic numbers for this
screen_width = 900
screen_height = 900
wall_size = 25
FPS = 60

RED = [255, 0, 0]
LIGHT_GREY = [230, 230, 230]
BLACK = [0, 0, 0]
BLUE = [0,0,230]
GREEN = [0, 255, 0]
ARMY_GREEN = [72, 107, 7]
BLACK = [0,0,0]
BULLET_SPEED = 20

font = pygame.font.SysFont('swmono', 20)


health_color = [255,255,255]
health_bg = [0,0,0]

health_img = pygame.image.load("health_bar.png")
health_img = pygame.transform.scale(health_img, (150,30))

score_board_img = pygame.image.load("health_bar.png")
score_board_img = pygame.transform.scale(score_board_img, (150,30))

health_x = 25
health_y = 25

health_cords = [health_x, health_y]
'''
score_x1 = 700
score_y1 = 25
score_cords1 = [score_x1, score_y1]
'''
score_x = 700
score_y = 30
score_cords = [score_x, score_y]

score_color = [0,0,0]
score_bg = [255,255,255]
score_surface = font.render('Score:', True, score_color, score_bg)


leftwall = pygame.Rect(0, 0, wall_size, screen_height)
rightwall = pygame.Rect(screen_width - wall_size, 0, wall_size, screen_height)
topwall = pygame.Rect(0, 0, screen_width, wall_size)
bottomwall = pygame.Rect(0, screen_height - wall_size, screen_width, wall_size)

#Data that stores types and locations of every wall, 0 = full wall, 1 = wall w/ door, 2 = no wall.

vertical_walltype = {0: [wall_size, screen_height / 3], 1: [wall_size, (screen_height / 3) - (screen_height/12)], 2: [0, 0]} 
horizontal_walltype = {0: [screen_width / 3, wall_size], 1: [(screen_width / 3) - (screen_width/12), wall_size], 2: [0, 0]}
verticalwall_locations = [[(screen_width/3) - wall_size/2, 0], [(2*screen_width/3) - wall_size/2, 0], [(screen_width/3) - wall_size/2, (screen_height/3) - wall_size/2], [(2*screen_width/3) - wall_size/2, (screen_height/3) - wall_size/2], [(screen_width/3) - wall_size/2, (2*screen_height/3) - wall_size/2], [(2*screen_width/3) - wall_size/2, (2*screen_height/3) - wall_size/2]]
horizontalwall_locations = [[0,(screen_height/3) - wall_size/2],[0,(2*screen_height/3) - wall_size/2],[(screen_width/3) - wall_size/2, (screen_height/3) - wall_size/2], [(screen_width/3) - wall_size/2,(2*screen_height/3) - wall_size/2],[(2*screen_width/3) - wall_size/2, (screen_height/3) - wall_size/2],[(2*screen_width/3) - wall_size/2,(2*screen_height/3) - wall_size/2]]

screen = pygame.display.set_mode([screen_width, screen_height])
pygame.display.set_caption("Take Aim")

clock = pygame.time.Clock()

char_start_x = 450
char_start_y = 450
char_x_val = 450    #this is the x cordinate value
char_y_val = 450    #this is the y cordinate value
char_width = 30
char_height = 30
char_speed = 5    # How fast does character move?
cur_char_x_vel = 0  # What's the character's current x speed?
cur_char_y_vel = 0  # What's the character's current y speed?

bullets = [] # Here's where we'll track all of the bullets on the screen
gun_length = 25

'''
bullet_velocity_x = 10 # How fast should bullets move?
bullet_width = 7.5
bullet_height = 5
'''

character = pygame.Rect([char_x_val, char_y_val], [char_width, char_height])

target_img = pygame.image.load("target_transparent.png")
floor_img = pygame.image.load("Floor.png")
target_img_box = target_img.get_rect()
floor_img_box = floor_img.get_rect()

health = 500
max_health = 500
print(health)
score = 0

next_room=0

safe_space = pygame.Rect(250,250,450,450)

def generate_level():
    verticalwall_typelist = [0, 0, 0, 0, 0, 0]
    horizontalwall_typelist = [0, 0, 0, 0, 0, 0]
    for wall in range(6):
        verticalwall_typelist[wall] = random.randrange(3)
    for wall in range(6):
        horizontalwall_typelist[wall] = random.randrange(3)
    return verticalwall_typelist, horizontalwall_typelist

def draw_level():
    vwall = []
    hwall = []
    for w_type, location in zip(verticalwall_typelist, verticalwall_locations):
        temporary_wall = (location + vertical_walltype[w_type])
        wallrect = pygame.draw.rect(screen, [0, 0, 0], temporary_wall)
        vwall.append(wallrect)
    for w_type, location in zip(horizontalwall_typelist, horizontalwall_locations):
        temporary_wall = (location + horizontal_walltype[w_type])
        wallrect = pygame.draw.rect(screen, [0, 0, 0], temporary_wall)
        hwall.append(wallrect)
    return vwall, hwall

#Retry loop / floor loop

verticalwall_typelist, horizontalwall_typelist = generate_level()

most_recent_dir = ''

def get_enemy_rect():
    while True:
        enemy_width = 25
        enemy_height = 25
        enemy_x_val = random.randint(0,900)
        enemy_y_val = random.randint(0,900)
        
        # print(enemy_x_val,", ", enemy_y_val)

        enemy_rect = pygame.Rect([enemy_x_val,enemy_y_val],[enemy_width,enemy_height])
        if not enemy_rect.colliderect(safe_space):
            return enemy_rect

enemies = []
amount_enemies = 3
place_holder_enemies = 3

for i in range(amount_enemies):
    enemies.append(get_enemy_rect())


dead = False

while True:
    screen.fill(LIGHT_GREY)
    screen.blit(floor_img, floor_img_box)
    if not dead:
        screen.blit(health_img, health_cords)
        health_rect=health_img.get_rect()
        health_rect.x = health_cords[0] + 5
        health_rect.y = health_cords[1] + 5
        health_rect.width -= 10
        health_rect.height -= 10
        health_rect.width *= health/max_health
          
        pygame.draw.rect(screen, RED, health_rect)
        
        score_txt_font = pygame.font.SysFont('impact',30)
        score_txt_surface = score_txt_font.render("Score: "+str(score), True,BLACK)
        score_txt_rect = score_txt_surface.get_rect()
        score_txt_rect.x = 750
        score_txt_rect.y = 25
            

        screen.blit(score_txt_surface,score_txt_rect)
        
        #screen.blit(score_board_img, score_cords1)
        #screen_rect=score_img.get_rect()

        collide = False
        pygame.draw.rect(screen, [0, 0, 0], topwall)
        pygame.draw.rect(screen, [0, 0, 0], bottomwall)
        pygame.draw.rect(screen, [0, 0, 0], leftwall)
        pygame.draw.rect(screen, [0, 0, 0], rightwall)
        
        v_walls, h_walls = draw_level()
        all_walls = v_walls + h_walls + [topwall , bottomwall , leftwall , rightwall]
        vwalls = v_walls + [leftwall, rightwall]
        hwalls = h_walls + [topwall, bottomwall]
        
        pygame.mouse.set_visible(False)
        mouse_pos = pygame.mouse.get_pos()
        line_vec = [mouse_pos[0] - character.centerx, mouse_pos[1] - character.centery]
        vec_len = math.hypot(line_vec[0], line_vec[1])
        vec = [(line_vec[0] / vec_len) * gun_length, (line_vec[1] / vec_len) * gun_length]
        char_center = [character.centerx, character.centery]
        pygame.draw.line(screen, BLACK, char_center, [char_center[0] + vec[0], char_center[1] + vec[1]], 5)
    #    character.left += cur_char_x_vel
    #    character.top += cur_char_y_vel
        
        
        target_img_box.centerx = mouse_pos[0]
        target_img_box.centery = mouse_pos[1]
        screen.blit(target_img, target_img_box)
        #screen.blit(floor_img, floor_img_box)
        
    #    pygame.draw.rect(screen, GREEN, safe_space)
        # Determine character movement
        # Is the player pressing a key?
        # - Is player moving vertically?
        
        pressed_keys = pygame.key.get_pressed()
        
        bounce_back_distance = 10
        
        if pressed_keys[pygame.K_w]:
            #print("up arrow")
            cur_char_y_vel = -1*char_speed
            char_y_val -= 5
            char_clock = pygame.time.Clock()
            char_start_y -= 5
        elif pressed_keys[pygame.K_s]:
            #print("down arrow")
            cur_char_y_vel = char_speed
            char_y_val += 5
            char_start_y += 5
        else:
            cur_char_y_vel = 0
        # - Is player moving horizontally?
        if pressed_keys[pygame.K_d]:
            #print("down arrow")
            cur_char_x_vel = char_speed
            char_x_val += 5
            char_start_x += 5
        elif pressed_keys[pygame.K_a]:
            #print("down arrow")
            cur_char_x_vel = -1*char_speed
            char_x_val -= 5
            char_start_x -= 5
        else:
            cur_char_x_vel = 0
            
        for wall in vwalls:
            collide = character.colliderect(wall)
            if collide:
                #collide_x = abs(character.centerx - wall.centerx) <= (character.width/2 + wall.width/2)
                if (character.centerx - wall.centerx) < 0:
                    character.right = wall.left - 1
                else:
                    character.left = wall.right - 1
        for wall in hwalls:
            collide = character.colliderect(wall)
            if collide:
                #collide_y = abs(character.centery - wall.centery) <= (character.height/2 + wall.height/2)
                if (character.centery - wall.centery) > 0:
                    character.top = wall.bottom - 1
                else:
                    character.bottom = wall.top - 1
            
            
        
        for bullet in bullets:
            # Draw the bullet
            bullet["current_loc"][0] += (BULLET_SPEED * bullet["direction"][0])
            bullet["current_loc"][1] += (BULLET_SPEED * bullet["direction"][1])
            cur_loc = bullet["current_loc"]
            pygame.draw.circle(screen, BLACK, [int(cur_loc[0]), int(cur_loc[1])], 3)

        # Draw the character!
        character.left += cur_char_x_vel
        character.top += cur_char_y_vel
        pygame.draw.rect(screen, ARMY_GREEN, character)

        # Draw the enemies!
        for enemy in enemies:
            pygame.draw.rect(screen, RED, enemy)

        # Draw the bullets!
        # Challenge: Every time you click, fire bullets from your mouse
        # Challenge: Have bullets that collide with enemies remove that enemy from the screen
        # Challenge: clean up off-screen bullets
        # Challange: spawn new enemies
        
        on_screen_bullets = []
        for bullet in bullets:
            alive_enemies = []
            for enemy in enemies:
                x_y = bullet["current_loc"]
                bullet_rect = pygame.Rect(x_y, [3, 3])
                if bullet_rect.colliderect(enemy):
                    clock = pygame.time.Clock()
                    amount_enemies -= 1
                    score = score + 1
                    if amount_enemies == 0:
                        place_holder_enemies += 1
                        amount_enemies = place_holder_enemies
                        for i in range(amount_enemies):
                            enemies.append(get_enemy_rect())
                        
                        verticalwall_typelist, horizontalwall_typelist = generate_level()
                    continue
                alive_enemies.append(enemy)

            enemies = alive_enemies

            if bullet_rect.left <= screen_width:
                on_screen_bullets.append(bullet)
        bullets = on_screen_bullets
        
        for enemy in enemies:
            if character.colliderect(enemy):
                health = health - 1
                print("Health: ", health)
        
        if(health <= 0):
            print("YOU DIED SUCKER!!!")
            print("Score: ",score)
            dead = True

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                # Keydown event!
                '''
                if event.key == pygame.K_SPACE:
                    # Fire a bullet
                    print("pressed space")
                    print(character.midright)
                    pos = character.midright
                    bullet = pygame.Rect(pos[0], pos[1], bullet_width, bullet_height)
                    bullets.append(bullet)
                '''
            if event.type == pygame.MOUSEBUTTONDOWN:
                #pygame.mixer.music.load("gunshot.ogg")
                #pygame.mixer.music.play(1, 0.0)
                line_vec = [mouse_pos[0] - character.centerx, mouse_pos[1] - character.centery]
                vec_len = math.hypot(line_vec[0], line_vec[1])
                unit_vec = [line_vec[0] / vec_len, line_vec[1] / vec_len]
                #print("====")
                #print("Line vec: " + str(line_vec) + "; Unit vec: " + str(unit_vec))
                bullets.append({"current_loc": [character.centerx, character.centery], "direction": unit_vec})
            
        for enemy in enemies:
                
            if character.centerx > enemy.centerx:
                enemy.left += 2
            
            if character.centerx < enemy.centerx:
                enemy.left -= 2 
            
            if character.centery > enemy.centery:
                enemy.top += 2
            
            if character.centery < enemy.centery:
                enemy.top -= 2

    else:
        pygame.mouse.set_visible(True)
        font = pygame.font.SysFont('impact', 100)
        game_over = font.render('You were slain!', True, [100, 0, 0])
        screen.blit(game_over, [100, 300])
        small_font = pygame.font.SysFont('impact', 60)
        #score_text = 'Your score:', score
        score_display = small_font.render('Your score: ' + str(score), True, [100, 0, 0])
        screen.blit(score_display, [100, 500])
        
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
                
                
    pygame.display.update()
    clock.tick(FPS)

|>> download student-games/p-team/game.py

Team - Team Boo

Game: Finding Light

import sys
import random
import pygame
import itertools


pygame.init()

################################################################
# Colors
crimson = [204, 0, 0]
bla = [0, 0, 0]
darkgrey = [90, 90, 100]
background = [56, 0, 20]
red = [220, 0, 0]
WHITE = [255, 255, 255]
BLACK = [88, 88, 88]
YELLOW = [255, 204, 229] #highlight
menu_btn_color = YELLOW
menu_btn_hover_color = bla
################################################################

screenwidth = 1500
screenheight = 1000
FPS = 60
BTN_PADDING = 10    # How much padding are we going to put around a button?
BTN_MARGIN = 10

gravity = 0.045

screen = pygame.display.set_mode([screenwidth, screenheight])
pygame.display.set_caption("Finding Light")
clock = pygame.time.Clock()
menu_font = pygame.font.SysFont('impact', 32)
screen_mode = 'title'   # Modes: title, menu

filenames = itertools.cycle(['sus.ogg', 'jumpy.ogg', 'happy.ogg'])
pygame.mixer.music.load('sus.ogg')
pygame.mixer.music.play(-1)


#################################################################
# title
title_font = pygame.font.SysFont('impact', 128)
title_surface = title_font.render('Finding Light', True, WHITE)
title_rect = title_surface.get_rect()
title_rect.x = (screenwidth / 2) - (title_rect.width / 2) # Put rect in middle of screen (perfectly in middle x)
title_rect.y = (screenheight /2) - (title_rect.height / 2) # Put rect in middle of the screen (sitting on top of horizontal midline)
#Background
loadingscreen_image = pygame.image.load('loadingscreen.png')
loadingscreen_rect = loadingscreen_image.get_rect()
loadingscreen_rect.center = [100, 400]
# === Open menu button ===
menu_btn_txt_surface = menu_font.render('Main Menu', True, BLACK)

menu_btn_bg_rect = menu_btn_txt_surface.get_rect()
#size correctly
menu_btn_bg_rect.width = menu_btn_bg_rect.width + (2*BTN_MARGIN)
menu_btn_bg_rect.height = menu_btn_bg_rect.height + (2*BTN_MARGIN)

#position it
menu_btn_bg_rect.x = (screenwidth / 2) - (menu_btn_bg_rect.width / 2)
menu_btn_bg_rect.y = title_rect.bottom + BTN_PADDING

menu_btn_txt_rect = menu_btn_txt_surface.get_rect()
menu_btn_txt_rect.x = menu_btn_bg_rect.x + BTN_MARGIN
menu_btn_txt_rect.y = menu_btn_bg_rect.y + BTN_MARGIN
#################################################################END SCREEN
catimage = pygame.image.load('cat.png')
catx = 10
caty = 10
endfont = pygame.font.SysFont('impact', 128)
endcolor = [255,255,255]
endsurface = endfont.render("You Lost...",True, endcolor, crimson)
endrect = endsurface.get_rect()
endx = (screenwidth / 2 ) - (endrect.width / 2)
endy = (screenheight / 2 ) - (endrect.height / 2)
backrect = pygame.Rect(400, 375, 700, 250)
###############################################################WIN SCREEN
winimage = pygame.image.load('win.png')
winfont = pygame.font.SysFont('impact', 128)
wincolor = [255,255,255]
winsurface = winfont.render("You Won!",True, wincolor,)
winrect = winsurface.get_rect()
winx = (screenwidth / 2 ) - (winrect.width / 2)
winy = (screenheight / 2 ) - (winrect.height / 2)
winimage = pygame.image.load('win.png')
winimage_rect = winimage.get_rect()
#################################################################
# menu
menu_screen_buttons = ['quit', 'resume'] # Available buttons
cur_menu_btn_id = 0                                # What button are we currently on?
btn_color = YELLOW

# === Resume button ===
# Render resume btn text onto surface
resume_btn_txt_surface = menu_font.render('Start Game', True, BLACK)
# Setup resume button background
resume_btn_bg_rect = resume_btn_txt_surface.get_rect()
resume_btn_bg_rect.width += 2 * BTN_MARGIN
resume_btn_bg_rect.height += 2 * BTN_MARGIN
resume_btn_bg_rect.x = (screenwidth / 2) - (resume_btn_bg_rect.width / 2)
resume_btn_bg_rect.y = 400
# Setup the resume button text
resume_btn_txt_rect = resume_btn_txt_surface.get_rect()
resume_btn_txt_rect.x = resume_btn_bg_rect.x + BTN_MARGIN
resume_btn_txt_rect.y = resume_btn_bg_rect.y + BTN_MARGIN

# === Quit button ===
# Render quit btn text onto surface
quit_btn_txt_surface = menu_font.render('Quit', True, BLACK)
# Setup quit button background
quit_btn_bg_rect = quit_btn_txt_surface.get_rect()
quit_btn_bg_rect.width += 2 * BTN_MARGIN
quit_btn_bg_rect.height += 2 * BTN_MARGIN
quit_btn_bg_rect.x = resume_btn_bg_rect.x + (resume_btn_bg_rect.width / 4)
quit_btn_bg_rect.y = resume_btn_bg_rect.y + (resume_btn_bg_rect.y / 4)
# Setup the quit button text
quit_btn_txt_rect = quit_btn_txt_surface.get_rect()
quit_btn_txt_rect.x = quit_btn_bg_rect.x + BTN_MARGIN
quit_btn_txt_rect.y = quit_btn_bg_rect.y + BTN_MARGIN
################################################################################

#################################################################
# game

loadingscreengame_image = pygame.image.load('back.png')
loadingscreengame_rect = loadingscreengame_image.get_rect()
loadingscreengame_rect.center = [screenwidth/2, screenheight / 2]


standing = False
win = False
health = 1

back_image = pygame.image.load('back.png')

charimage = pygame.image.load('sprite.png')
char_rect = charimage.get_rect()

char_velocity_x = 0
char_velocity_y = 0
catx = 10
caty = 10
charheight = 75
charwidth = 25
char_rect.left = 0
char_rect.top = 0

death_blocks = [
    pygame.Rect(200, 0, 60, 220),
    pygame.Rect(800, 0, 60, 175),
    pygame.Rect(970, 300, 360, 15),
    pygame.Rect(0, 420, 190, 60),
    pygame.Rect(450, 0, 15, 600),
    pygame.Rect(300, 850, 15, 100),
    pygame.Rect(800, 800, 30, 300),
    pygame.Rect(1313, 170, 30, 400),
    pygame.Rect(1300, 600, 30, 300),
    pygame.Rect(1250, 400, 30, 300),
    pygame.Rect(700, 500, 300, 30),
    pygame.Rect(450, 620, 200, 30),
    pygame.Rect(0, 800, 30, 15)]

end_block = pygame.image.load('bloss.png')
end_block_rect = end_block.get_rect()
end_block_rect.x = screenwidth - end_block_rect.width
end_block_rect.y = 500
platforms = [
    pygame.Rect(200, 620, 250, 15),
    pygame.Rect(800, 800, 300, 15),
    pygame.Rect(600, 300, 300, 15),
    pygame.Rect(1, 940, 2000, 65)]

while True:
    # We need to show different things depending on whether or not we're in 'title'
    # or 'menu' mode
    if screen_mode == 'title':
        # ==== TITLE SCREEN MODE ====
        screen.fill(bla)
        loadingscreen_image = pygame.image.load('loadingscreen.png')
        loadingscreen_rect = loadingscreen_image.get_rect()
        loadingscreen_rect.center = [screenwidth  / 2, screenheight / 2]
        screen.blit(loadingscreen_image, loadingscreen_rect)
        # Draw the title screen
        # Render the title text in the middle of the screen
        screen.blit(title_surface, title_rect)
        # Draw the menu button, first: the text
        pygame.draw.rect(screen, menu_btn_color, menu_btn_bg_rect)
        screen.blit(menu_btn_txt_surface, menu_btn_txt_rect)

    elif screen_mode == 'menu':
        # === MENU SCREEN MODE ===
        screen.fill(bla)
        loadingscreen_image = pygame.image.load('loadingscreen.png')
        loadingscreen_rect = loadingscreen_image.get_rect()
        loadingscreen_rect.center = [screenwidth / 2, screenheight / 2]
        screen.blit(loadingscreen_image, loadingscreen_rect)

        # Draw button rectangles!
        # - If button is active, color background with hover color and an outline
        # - otherwise, draw with normal color and no outline
        #print(cur_menu_btn_id)
        if menu_screen_buttons[cur_menu_btn_id] == 'resume':
            pygame.draw.rect(screen, menu_btn_hover_color, resume_btn_bg_rect)#draw menu box
            pygame.draw.rect(screen, bla, resume_btn_bg_rect, 5)#draw outline
        else:
            pygame.draw.rect(screen, menu_btn_color, resume_btn_bg_rect)
        if menu_screen_buttons[cur_menu_btn_id] == 'quit':
            pygame.draw.rect(screen, menu_btn_hover_color, quit_btn_bg_rect)
            pygame.draw.rect(screen, bla, quit_btn_bg_rect, 5)
        else:
            pygame.draw.rect(screen, menu_btn_color, quit_btn_bg_rect)

        # Layer button text over button backgrounds
        screen.blit(resume_btn_txt_surface, resume_btn_txt_rect)

        screen.blit(quit_btn_txt_surface, quit_btn_txt_rect)
    elif screen_mode == 'game':
        standing = False
        platform_index = char_rect.collidelist(platforms)
        if platform_index != -1:
            platform = platforms[platform_index]
            is_just_touching_down = char_rect.bottom - platform.top < platform.height
            is_descending = char_velocity_y > 0

            if is_just_touching_down and is_descending:
                char_rect.top = platform.top - char_rect.height
                standing = True
                char_velocity_y = 1

        if char_rect.collidelist(death_blocks) != -1:
            health = 0

        if char_rect.colliderect(end_block_rect):
            win = True
            print("you won")
            ###############################################NEED TO DO
            screen_mode = 'winscreen'
            continue

        screen.blit(loadingscreengame_image, loadingscreengame_rect)
        for death_block in death_blocks:
            pygame.draw.rect(screen,red,death_block)
        for platform in platforms:
            pygame.draw.rect(screen, darkgrey, platform)
        screen.blit(end_block, end_block_rect)
        screen.blit(charimage, char_rect)

        if health == 0:

            print("U DED")
           # pygame.quit()
            #sys.exit()
            screen_mode = 'gameover'


        char_rect.left += char_velocity_x
        char_rect.top += char_velocity_y

        char_velocity_x *= 0.99
        char_velocity_y *= 0.99
        char_velocity_y += gravity

    elif screen_mode == 'gameover':
        screen.fill(bla)
        for i in range(300):
            screen.blit(catimage, [random.randint(0, screenwidth), random.randint(0, screenheight)])
            catx = catx + 1
            pygame.draw.rect(screen, crimson, backrect)
            screen.blit(endsurface, [endx, endy])

        # ===== WIN SCREEN =============
    elif screen_mode == 'winscreen':
            screen.fill(bla)
            winimage_rect.center = [screenwidth / 2, screenheight / 2]
            screen.blit(winimage, [0,0])

            screen.blit(winsurface, [winx, winy])


    else:
        # ==== ???? MODE ====
        print("AAAH UNRECOGNIZED SCREEN MODE! Exiting")
        pygame.quit()
        sys.exit()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        # ===== TITLE MODE EVENTS =====
        if screen_mode == 'title' and event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()
            if menu_btn_bg_rect.collidepoint(mouse_pos):
                screen_mode = 'menu'
                cur_menu_btn_id = 0

        # ===== MENU MODE EVENTS =====
        if screen_mode == 'menu' and event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                # player presses down arrow
                cur_menu_btn_id = (cur_menu_btn_id + 1) % len(menu_screen_buttons)
            if event.key == pygame.K_UP:
                # player presses up arrow
                cur_menu_btn_id = (cur_menu_btn_id - 1) % len(menu_screen_buttons)
            if event.key == pygame.K_RETURN:
                # Player presses return (selects current option)
                if menu_screen_buttons[cur_menu_btn_id] == 'quit':
                    # if on resume button, go back to title screen
                     screen_mode = 'game'

                    #Need to direct to game

                elif menu_screen_buttons[cur_menu_btn_id] == 'resume':
                    # if on quit button, quit the game

                    pygame.quit()
                    sys.exit()
        if screen_mode == 'game':
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                      print("Space key press.")

                      #Shooter
                elif event.key == pygame.K_w:
                    print("w key was pressed")
                    char_velocity_y -= 1
                elif event.key == pygame.K_s:
                    print("s key was pressed")
                    char_velocity_y += 1
                elif event.key == pygame.K_a:
                    print("a key was pressed")
                    char_velocity_x -= 1
                elif event.key == pygame.K_d:
                    print("d key was pressed")
                    char_velocity_x += 1
    clock.tick(FPS)
    pygame.display.update()

|>> download student-games/team-boo/game.py