Controller - Code

From RoboWiki
Jump to: navigation, search

Return back to project page: Game Controller - Jakub Vojtek

Python code for the Controller project:

 
import pygame
import random
from player import Player
from buildhat import Motor, ForceSensor

pygame.init()
running = True
endscreen = False


WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.SRCALPHA)
pygame.display.set_caption("Fighter Jet Game")


background_image = pygame.image.load("pictures/universe.jpg").convert()
background_image = pygame.transform.scale(background_image, (WIDTH, HEIGHT))


WHITE = (255, 255, 255)


player = Player((WIDTH - 60) // 2, HEIGHT - 70, 60, 50, 15)


rock_image = pygame.image.load("pictures/rock1.png").convert_alpha()
rock_image = pygame.transform.scale(rock_image, (50, 50))

comet_image = pygame.image.load("pictures/comet.png").convert_alpha()
comet_image = pygame.transform.scale(comet_image, (80, 40))

explosion_image = pygame.image.load("pictures/explosion.png").convert_alpha()
explosion_image = pygame.transform.scale(explosion_image, (80, 80))

heart_image = pygame.image.load("pictures/heart.png").convert_alpha()
heart_image = pygame.transform.scale(heart_image, (30, 30))

# Game variables
rock_speed = 3
rocks = []
comet_speed = 5
comet_spawn_timer = random.randint(1000, 2000)  # Adjust spawn interval
comet_direction = random.choice(["left", "right"])
comet_x = -80 if comet_direction == "left" else WIDTH
comet_y = random.randint(50, HEIGHT - 200)
comet_active = False
player_lives = 10
boom_text_visible = False
boom_text_timer = 0
boom_text_duration = 1000
score = 0
shot_speed = 7
shots = []

clock = pygame.time.Clock()


font = pygame.font.SysFont(None, 48)


steering_wheel = Motor('C')
laser_gun = ForceSensor('D')
steering_wheel.run_to_position(0)

def handle_pressed(force):
    global player_lives, rocks, shots, comet_spawn_timer, comet_direction, comet_x, comet_y, comet_active, endscreen, score
    if endscreen:
        score = 0
        player_lives = 10
        rocks.clear()
        shots.clear()
        comet_spawn_timer = random.randint(1000, 2000)  # Adjusted spawn interval
        comet_direction = random.choice(["left", "right"])
        comet_x = -80 if comet_direction == "left" else WIDTH
        comet_y = random.randint(50, HEIGHT - 200)
        comet_active = True
        endscreen = False
    else:
        shot_x = player.x + (player.width - 5) // 2
        shot_y = player.y
        shots.append([shot_x, shot_y, 5, 15])

laser_gun.when_pressed = handle_pressed

boom_text_surface = font.render("!!!BOOOOM!!!", True, (255, 0, 0))

def collision(obj1, obj2):
    obj1_rect = pygame.Rect(obj1[0], obj1[1], obj1[2], obj1[3])
    obj2_rect = pygame.Rect(obj2[0], obj2[1], obj2[2], obj2[3])
    return obj1_rect.colliderect(obj2_rect)

def show_stats():
    for i in range(player_lives):
        screen.blit(heart_image, (WIDTH - (i + 1) * 35, 10))
    score_text = font.render(f"Score: {score}", True, WHITE)
    screen.blit(score_text, (10, 10))

def check_shot_comet_collision(comet_width, comet_height):
    global comet_active, score, boom_text_visible, boom_text_timer
    for shot in shots[:]:
        if comet_active and collision(shot, [comet_x, comet_y, comet_width, comet_height]):
            comet_active = False
            shots.remove(shot)
            score += len(rocks)
            rocks.clear()
            boom_text_visible = True
            boom_text_timer = pygame.time.get_ticks()

def check_shot_rock_collision():
    global shots, rocks, score
    for shot in shots[:]:
        for rock in rocks[:]:
            if collision(shot, rock):
                shots.remove(shot)
                explosion(rock[0], rock[1])
                rocks.remove(rock)
                score += 1

def display_boom_text():
    screen.blit(boom_text_surface, ((WIDTH - boom_text_surface.get_width()) // 2, HEIGHT // 4))


def explosion(x, y):
    screen.blit(explosion_image, (x - 20, y - 20))


def spawn_rock():
    global rocks
    if random.randint(0, 100) < 2:
        rock_x = random.randint(0, WIDTH - 50)
        rock_y = -50
        rocks.append([rock_x, rock_y, 50, 50])


def spawn_comet():
    global comet_spawn_timer, comet_active, comet_direction, comet_x, comet_y
    comet_spawn_timer -= 1
    if comet_spawn_timer <= 0:
        comet_spawn_timer = random.randint(1000, 2000)  # Adjusted spawn interval
        comet_direction = random.choice(["left", "right"])
        comet_x = -80 if comet_direction == "left" else WIDTH
        comet_y = random.randint(50, HEIGHT - 200)
        comet_active = True
    if comet_active:
        if comet_direction == "left":
            comet_x += comet_speed
        else:
            comet_x -= comet_speed

def draw_rocks():
    global rocks
    for rock in rocks[:]:
        rock[1] += rock_speed
        screen.blit(rock_image, (rock[0], rock[1]))

def draw_shots():
    global shots
    for shot in shots[:]:
        shot[1] -= shot_speed
        pygame.draw.rect(screen, (255, 0, 0), (shot[0], shot[1], shot[2], shot[3]))

def draw_comet():
    global comet_active
    if comet_active:
        screen.blit(comet_image, (comet_x, comet_y))

def check_end_game():
    global player_lives, endscreen
    for rock in rocks:
        if rock[1] > HEIGHT:
            rocks.remove(rock)
            player_lives -= 1

    # Check if the game should end
    if player_lives <= 0:
        endscreen = True
        screen.fill((0, 0, 0))
        end_text = font.render("Press SENSOR to play again", True, WHITE)  # Changed to "SENSOR"
        score_text = font.render(f"Final Score: {score}", True, WHITE)
        screen.blit(end_text, ((WIDTH - end_text.get_width()) // 2, (HEIGHT - end_text.get_height()) // 2))
        screen.blit(score_text, ((WIDTH - score_text.get_width()) // 2, (HEIGHT - score_text.get_height()) // 2 - 50))

previous_angle = 0
# Main game loop
while running:
    screen.blit(background_image, (0, 0))

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

    current_angle = steering_wheel.get_position()

    angle_difference = abs(current_angle - previous_angle)

    if angle_difference > 5:  # Adjust sensitivity
        if current_angle < previous_angle:
            player.move_left()
        else:
            player.move_right()

        # Ensure player stays within the screen boundaries
        player.x = max(0, min(player.x, WIDTH - player.width))
        previous_angle = current_angle

    spawn_rock()
    spawn_comet()
    draw_shots()
    draw_rocks()
    draw_comet()

    check_shot_comet_collision(80, 40)
    check_shot_rock_collision()

    # Draw player
    screen.blit(player.image, (player.x, player.y))

    check_end_game()
    show_stats()

    if boom_text_visible:
        display_boom_text()
        if pygame.time.get_ticks() - boom_text_timer >= boom_text_duration:
            boom_text_visible = False

    pygame.display.flip()
    clock.tick(30)  # Reduced frame rate

pygame.quit()