aboutsummaryrefslogtreecommitdiff
path: root/src/splitscreen_duo/menu.py
blob: 8962c5dc1e40b57be38fd469f6094aaf799e4044 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import sys
import pygame
import os
from .input import Input
import logging
import json

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
IS_DEVELOPMENT_MODE = os.getenv("DEVELOPMENT", "").lower() != ""
OPTIONS = ["Breakout", "Pong v.s. Computer", "Snake", "Quit"]
logger = logging.getLogger(__name__)


def init_display():
    global WIDTH, HEIGHT, FONT, screen, selected_index

    WIDTH, HEIGHT = (
        pygame.display.Info().current_w // 2,
        pygame.display.Info().current_h // 2,
    )
    FONT = pygame.font.Font(None, 36)
    screen = pygame.display.set_mode(
        (WIDTH, HEIGHT) if IS_DEVELOPMENT_MODE else (0, 0),
        0 if IS_DEVELOPMENT_MODE else pygame.FULLSCREEN,
    )
    selected_index = 0


def draw_menu():
    screen.fill(WHITE)

    for i, option in enumerate(OPTIONS):
        text = FONT.render(option, True, BLACK if i != selected_index else (200, 0, 0))

        screen.blit(text, (WIDTH // 2 - text.get_width() // 2, 150 + i * 50))

    pygame.display.flip()


def main_loop(serial, instance):
    init_display()

    global selected_index

    is_running = True
    input_handler = Input(debug=IS_DEVELOPMENT_MODE)

    while is_running:
        draw_menu()

        if instance == "secondary":
            if serial.in_waiting() > 0:
                logger.debug(serial.readline().decode("utf-8").strip())

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

            action = input_handler.get_input(event)

            if action == "UP":
                selected_index = (selected_index - 1) % len(OPTIONS)
            elif action == "DOWN":
                selected_index = (selected_index + 1) % len(OPTIONS)
            elif action == "SELECT":
                if OPTIONS[selected_index] == "Quit":
                    pygame.quit()
                    sys.exit()
                else:
                    serial.write(
                        json.dumps({"command": 0, "action": action}).encode("utf-8")
                    )
            elif action == "QUIT":
                pygame.quit()
                sys.exit()