def __init__(self):
        pygame.init()

        pygame.display.set_caption("Pathfinding Algorithms")
        self.window_surface = pygame.display.set_mode((800, 600))

        self.ui_manager = pygame_gui.UIManager(
            (800, 600), "pathfinding/data/ui_theme.json")
        self.ui_manager.preload_fonts([{
            'name': 'fira_code',
            'point_size': 14,
            'style': 'bold'
        }])

        self.background_surface = pygame.Surface((800, 600))
        self.background_surface.fill(
            self.ui_manager.get_theme().get_colour('dark_bg'))

        self.playing_pathfinder = False
        self.play_speed = 0.5
        self.play_speed_acc = 0.0

        pathfinding_algorithms = [
            'A*', "Breadth First", "Depth First", "Dijkstra's", "Uniform Cost"
        ]
        self.pathfinder_drop_down = UIDropDownMenu(
            pathfinding_algorithms, 'A*', pygame.Rect((620, 50), (150, 25)),
            self.ui_manager)

        self.pathfinder_label = pygame_gui.elements.UILabel(
            pygame.Rect((520, 50), (100, 25)), "Algorithm: ", self.ui_manager)

        map_sizes = ['20x20', "40x40", "80x80"]
        self.map_size_drop_down = UIDropDownMenu(
            map_sizes, '20x20', pygame.Rect((620, 225), (150, 25)),
            self.ui_manager)

        self.map_size_label = pygame_gui.elements.UILabel(
            pygame.Rect((520, 225), (100, 25)), "Map size: ", self.ui_manager)

        self.random_start_button = UIButton(pygame.Rect((620, 350), (150, 25)),
                                            "Random start", self.ui_manager)

        self.increment_pathfinder_button = UIButton(
            pygame.Rect((620, 385), (150, 25)), "Increment", self.ui_manager)

        self.play_button = UIButton(pygame.Rect((620, 420), (150, 25)), "Play",
                                    self.ui_manager)

        self.speed_slider = UIHorizontalSlider(
            pygame.Rect((620, 455), (150, 25)), self.play_speed, (1.0, 0.017),
            self.ui_manager)

        self.speed_slider_label = pygame_gui.elements.UILabel(
            pygame.Rect((520, 455), (100, 25)), "Play speed: ",
            self.ui_manager)

        self.tool_tip = None

        self.wall_colour = pygame.Color("#FFFFFF")

        self.available_maze_space = 450
        self.wall_size = 4
        self.maze_dimension = 20

        self.maze_square_size = int(
            self.available_maze_space / self.maze_dimension) + 1
        self.walls, self.junctions, self.entrance, self.exit = create_maze(
            top_left=(20, 20),
            square_size=self.maze_square_size,
            width=self.maze_dimension,
            height=self.maze_dimension)

        self.nav_node_graph = [
            junction.nav_node for junction in self.junctions
        ]
        self.font = pygame.font.Font(None, 12)
        self.current_finder = AStarFinder(self.entrance.nav_node,
                                          self.exit.nav_node,
                                          incremental=True)

        self.clock = pygame.time.Clock()
        self.running = True
示例#2
0
import pygame, sys
import random
import math
import pygame_gui
import game_db

pygame.init()
pygame.display.set_caption('Robo Tube')
window_surface = pygame.display.set_mode((800, 600))
background = pygame.Surface((800, 600))
background.fill(pygame.Color('#ffffff'))
logged_user = ""

manager = pygame_gui.UIManager((800, 600))

panel_select = pygame_gui.elements.ui_panel.UIPanel(pygame.Rect((150, 200),
                                                                (550, 150)),
                                                    manager=manager,
                                                    starting_layer_height=3)

btn_show_login = pygame_gui.elements.UIButton(relative_rect=pygame.Rect(
    (100, 50), (100, 25)),
                                              text='Login',
                                              manager=manager,
                                              container=panel_select)

btn_show_register = pygame_gui.elements.UIButton(relative_rect=pygame.Rect(
    (300, 50), (100, 25)),
                                                 text='Register',
                                                 manager=manager,
                                                 container=panel_select)
示例#3
0
    def audio(self):
        if self.config_data["Color_Mode"] == "NORMAL_MODE":
            background_image = pygame.image.load("pictures/normal_pause.png")
        else:
            background_image = pygame.image.load("pictures/dark_pause.png")

        done = False
        manager = pygame_gui.UIManager((380, 650))
        heading_font = pygame.font.SysFont("Calibri", 40, True, False)
        heading_text = heading_font.render("Audio", True,
                                           self.color_manager.HEADLINE)

        menu_background_audio_value = Slider(
            self.screen, "Menu-Music: ", 80, 150 + self.displacement,
            Color_Manager.DARKEST_GRAY, manager,
            self.config_data["Audio_Settings"]["menu_background"], (1, 100))
        game_backgorund_audio_value = Slider(
            self.screen, "Background-Music: ", 80, 210 + self.displacement,
            Color_Manager.DARKEST_GRAY, manager,
            self.config_data["Audio_Settings"]["game_background"], (1, 100))
        effects_audio_value = Slider(
            self.screen, "Game-Effects: ", 80, 270 + self.displacement,
            Color_Manager.DARKEST_GRAY, manager,
            self.config_data["Audio_Settings"]["effects"], (1, 100))
        if self.type == "menu":
            main_ref = menu_background_audio_value
        elif self.type == "game":
            main_ref = game_backgorund_audio_value
        else:
            main_ref = menu_background_audio_value

        if self.config_data["Audio_Settings"]["muted"]:
            text = "Unmute"
            position = (122, 330 + self.displacement)
        else:
            text = "Mute"
            position = (145, 330 + self.displacement)

        options = [
            Option(self.screen, text, position, self.color_manager),
            Option(self.screen, "Back", (145, 370 + self.displacement),
                   self.color_manager)
        ]

        while not done:
            self.screen.blit(background_image,
                             ((380 - background_image.get_width()) / 2,
                              75 + self.displacement))
            self.screen.blit(heading_text, (141, 110 + self.displacement))
            time_delta = self.clock.tick(30)

            menu_background_audio_value.draw()
            game_backgorund_audio_value.draw()
            effects_audio_value.draw()

            if not self.config_data["Audio_Settings"]["muted"]:
                self.background_music.set_volume(main_ref.get_current_value())
                self.effect_music.set_volume(
                    effects_audio_value.get_current_value())
            self.config_data["Audio_Settings"][
                "menu_background"] = menu_background_audio_value.get_current_value(
                )
            self.config_data["Audio_Settings"][
                "game_background"] = game_backgorund_audio_value.get_current_value(
                )
            self.config_data["Audio_Settings"][
                "effects"] = effects_audio_value.get_current_value()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    Close_Game(self.config_data)

                if event.type == pygame.MOUSEBUTTONDOWN:
                    for option in options:
                        if option.rect.collidepoint(pygame.mouse.get_pos()):
                            if option.text == "Mute":
                                self.effect_music.play(
                                    "music/button_click.mp3")
                                self.background_music.set_volume(0)
                                self.effect_music.set_volume(0)
                                self.config_data["Audio_Settings"][
                                    "muted"] = True
                                option.text = "Unmute"
                                option.pos = (122, 330 + self.displacement)
                                option.set_rect()
                            elif option.text == "Unmute":
                                self.effect_music.play(
                                    "music/button_click.mp3")
                                self.background_music.set_volume(
                                    self.config_data["Audio_Settings"]
                                    ["menu_background"])
                                self.effect_music.set_volume(
                                    self.config_data["Audio_Settings"]
                                    ["effects"])
                                self.config_data["Audio_Settings"][
                                    "muted"] = False
                                option.text = "Mute"
                                option.pos = (145, 330 + self.displacement)
                                option.set_rect()
                            elif option.text == "Back":
                                done = True
                                self.main()
                manager.process_events(event)

            for option in options:
                if option.rect.collidepoint(pygame.mouse.get_pos()):
                    option.hovered = True
                else:
                    option.hovered = False
                option.draw()

            if menu_background_audio_value.is_pressed():
                self.effect_music.play("music/button_click_down.mp3")
            if menu_background_audio_value.is_released():
                self.effect_music.play("music/button_click_up.mp3")
            if game_backgorund_audio_value.is_pressed():
                self.effect_music.play("music/button_click_down.mp3")
            if game_backgorund_audio_value.is_released():
                self.effect_music.play("music/button_click_up.mp3")
            if effects_audio_value.is_pressed():
                self.effect_music.play("music/button_click_down.mp3")
            if effects_audio_value.is_released():
                self.effect_music.play("music/button_click_up.mp3")

            manager.draw_ui(self.screen)
            manager.update(time_delta=time_delta)
            pygame.display.flip()
            self.clock.tick(30)
示例#4
0
    def win_menu(self):
        manager = pgui.UIManager(self.screen_rect.size)
        bg = pg.Surface(self.screen_rect.size)
        bg.fill(pg.Color('#000000'))

        nar = r'<b><font color="#115622">Narrator:</font></b>'
        frank = r'<b><font color="#d78f00">Frank:</font></b>'
        robyn = r'<b><font color="#af0500">Robyn:</font></b>'

        text1_time = 9
        text1 = f"""{nar} After several hours of hard fighting, Frank had finally cleared the ransomware from the cluster.
{robyn} Great work, Frank! You really saved our ass on this one. Why don't you take the rest of the day off and go relax a bit.
{frank} Thanks boss. That was one of the more challenging and buggy infections I've seen. Taking the afternoon off would be a welcome change.
{nar} With that, Frank pulled off his headset and headed outside to take a walk. Just another day in the life of a cyber warrior....
 
<b>[ Space to Continue ]</b>"""

        thank_time = 4
        thank_text = f"""Thank you <i>so much</i> for taking the time to play my entry for the <font color="#e167cf"><b>Pygame Community Easter Jam 2021</b></font>. I know it has some rough edges, but I'm generally happy with how it turned out.
 
Thanks for playing.
Andy
 
<b>[ Space to Main Menu ]</b>"""

        text_list = [text1, thank_text]
        time_list = [text1_time, thank_time]
        text_itr = 0

        current_text = text_list[text_itr]
        current_timer = time_list[text_itr] * 1000

        box_width = 800
        box_height = 600
        box_x = (self.wind_width / 2) - (box_width / 2)
        box_y = (self.wind_height / 2) - (box_height / 2)
        textbox = pgui.elements.UITextBox(
            relative_rect=pg.Rect((box_x, box_y), (box_width, box_height)),
            html_text=current_text.replace('\n', '<br>'),
            manager=manager
        )
        textbox.set_active_effect('typing_appear')

        ui_clock = pg.time.Clock()
        text_finished = False
        text_timer = pg.time.get_ticks()
        while True:
            time_delta = ui_clock.tick(60)/1000.0
            textbox.update(0.5)

            if not text_finished and pg.time.get_ticks() >= text_timer + current_timer:
                text_finished = True

            for event in pg.event.get():
                if event.type == pg.QUIT:
                    self.state = GameState.EXIT
                    return

                if event.type == pg.KEYDOWN:
                    if event.key == pg.K_SPACE:
                        if not text_finished:
                            textbox.set_active_effect(None)
                            textbox.rebuild()
                            text_finished = True
                        else:
                            if text_itr == len(text_list) - 1:
                                self.state = GameState.TITLE
                                return
                            else:
                                text_finished = False
                                text_itr += 1
                                textbox.html_text = text_list[text_itr].replace('\n', '<br>')
                                current_timer = time_list[text_itr] * 1000
                                textbox.set_active_effect('typing_appear')
                                textbox.rebuild()
                                text_timer = pg.time.get_ticks()

                manager.process_events(event)

            manager.update(time_delta)

            self.window.blit(bg, (0, 0))
            manager.draw_ui(self.window)

            pg.display.update()
示例#5
0
from typing import Text
import pygame
from pygame.draw import ellipse
import pygame_gui
import random
import time

from pygame_gui.elements import ui_drop_down_menu

pygame.init()
pygame.display.set_caption('GM Lore Keeper v.0')
screen_size = (1000, 500)
window_surface = pygame.display.set_mode(screen_size)
background = pygame.Surface(screen_size)
background.fill(pygame.Color('#505000'))
manager = pygame_gui.UIManager(
    screen_size)  #manager needs to know the size of the window
clock = pygame.time.Clock()
'''start buttons'''
button_active_battle = pygame_gui.elements.ui_button.UIButton(
    relative_rect=pygame.Rect((30, 20), (150, 50)),
    text='Active Battle',
    manager=manager,
    tool_tip_text='open the active battle')
button_gm_note = pygame_gui.elements.ui_button.UIButton(
    relative_rect=pygame.Rect((30, 90), (150, 50)),
    text='GM Notes',
    manager=manager,
)
button_pc_detail = pygame_gui.elements.ui_button.UIButton(
    relative_rect=pygame.Rect((30, 160), (150, 50)),
    text='PC Details',
示例#6
0
num_cols = 10

square_w, square_h = (
    (home_grid_right - home_grid_left) // num_cols,
    (home_grid_bottom - home_grid_top) // num_rows,
)

pygame.init()

pygame.display.set_caption("Battleship")
window_surface = pygame.display.set_mode((display_w, display_h))

background = pygame.Surface((display_w, display_h))
background.fill(pygame.Color("#FFFFFF"))

manager = pygame_gui.UIManager((display_w, display_h),
                               "data/themes/game_theme.json")

home_grid = Grid(
    manager,
    board_left=home_grid_left,
    board_top=home_grid_top,
    square_w=square_w,
    square_h=square_h,
    num_rows=num_rows,
    num_cols=num_cols,
    initial_text="",
)
tracking_grid = Grid(
    manager,
    board_left=tracking_grid_left,
    board_top=tracking_grid_top,
示例#7
0
    def intro_story(self):
        manager = pgui.UIManager(self.screen_rect.size)
        bg = pg.Surface(self.screen_rect.size)
        bg.fill(pg.Color('#000000'))

        nar = r'<b><font color="#115622">Narrator:</font></b>'
        frank = r'<b><font color="#d78f00">Frank:</font></b>'
        robyn = r'<b><font color="#af0500">Robyn:</font></b>'

        text1_time = 17
        text1 = f"""{nar} Monday. The worst day of the week. As Frank rolled out of bed and brewed a cup of coffee he had no idea what would be in store for him when he logged in to work.
{nar} Steaming cup of Joe in hand, Frank walked into his home office, sat down at his desk, and pulled on his headset. In 2341 most people only commuted to their VR headset. And while Frank was not like most people, in this regard he was the same.
{frank} <i>Yawning.</i> Morning folks. How we lookin'?
{robyn} Morning sunshine. If you had shown up 10 minutes ago I would've said "lookin' good", but we just started getting some weird telemetry from the data cluster in Seattle. I need you to check it out ASAP.
{nar} "Just great" thought Frank. "I should've stayed in bed and let someone else be the first one in...."
{frank} Yea, no problem boss. I'll take a look. Probably just a misconfiguration. Not many people have access to that cluster, so there can't be too much wrong.
{nar} Boy did Frank regret that last statement.
 
<b>[ Space to Continue ]</b>"""

        text2_time = 13
        text2 = f"""{nar} As a seasoned cyber warrior, it only took Frank a few minutes of digging to realize that he had been horribly wrong. This was no misconfiguration. Somehow ransomware had been installed in the cluster and was now trying to encrypt all of the data!
{frank} ...Robyn we have a problem. That cluster is completely infested with a particularly nasty flavor of Ransomware. The automated defenses aren't going to cut it this time...I have to go in.
{robyn} Ahh shit. Well, I'm glad it was you who arrived first today then. You're the best we've got, so go kick some ass out there!
{nar} Frank did not respond, but simply proceeded to load himself into the cluster. This is why he got paid the big bucks. It was time to do battle with the malware - man to byte.
 
<b>[ Space to Continue ]</b>"""

        text3_time = 3
        instruction_text = f"""<b>Move:</b> Arrow keys
 
<b>Aim:</b> Move the mouse

<b>Shoot:</b> Left click
 
<b>Collect dropped computer chips</b> to power up your character.
 
<b>Defeat all the viruses</b> to win the game!
 
<b>[ Space to Start ]</b>"""

        text_list = [text1, text2, instruction_text]
        time_list = [text1_time, text2_time, text3_time]
        text_itr = 0

        current_text = text_list[text_itr]
        current_timer = time_list[text_itr] * 1000

        box_width = 800
        box_height = 600
        box_x = (self.wind_width / 2) - (box_width / 2)
        box_y = (self.wind_height / 2) - (box_height / 2)
        textbox = pgui.elements.UITextBox(
            relative_rect=pg.Rect((box_x, box_y), (box_width, box_height)),
            html_text=current_text.replace('\n', '<br>'),
            manager=manager
        )
        textbox.set_active_effect('typing_appear')

        ui_clock = pg.time.Clock()
        text_finished = False
        text_timer = pg.time.get_ticks()
        while True:
            time_delta = ui_clock.tick(60)/1000.0
            textbox.update(0.5)

            if not text_finished and pg.time.get_ticks() >= text_timer + current_timer:
                text_finished = True

            for event in pg.event.get():
                if event.type == pg.QUIT:
                    self.state = GameState.EXIT
                    return

                if event.type == pg.KEYDOWN:
                    if event.key == pg.K_SPACE:
                        if not text_finished:
                            textbox.set_active_effect(None)
                            textbox.rebuild()
                            text_finished = True
                        else:
                            if text_itr == len(text_list) - 1:
                                self.state = GameState.NEWGAME
                                return
                            else:
                                text_finished = False
                                text_itr += 1
                                textbox.html_text = text_list[text_itr].replace('\n', '<br>')
                                current_timer = time_list[text_itr] * 1000
                                textbox.set_active_effect('typing_appear')
                                textbox.rebuild()
                                text_timer = pg.time.get_ticks()

                manager.process_events(event)

            manager.update(time_delta)

            self.window.blit(bg, (0, 0))
            manager.draw_ui(self.window)

            pg.display.update()
示例#8
0
import numpy as np
import pygame_gui
import time

width, height = 501, 550

numOfCellX, numOfCellY = 50, 50

cellWidth = (width - 1) / numOfCellX
cellHeight = (height - 50) / numOfCellY

pygame.init()
BG_Color = (28, 28, 28)

screen = pygame.display.set_mode([width, height])
manager = pygame_gui.UIManager((width, height))
gameState = np.zeros([width, height])

speed = 0.1
solitude = 2
poblation = 3

speedButton = pygame_gui.elements.UIButton(relative_rect=pygame.Rect(
    (10, 510), (100, 30)),
                                           text='Speed Up',
                                           manager=manager)

slowButton = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((110, 510),
                                                                    (100, 30)),
                                          text='Slow down',
                                          manager=manager)
示例#9
0
    def __init__(self):
        self.level_number = data.number_of_levels()
        self.make_level_pictures()
        self.manager = pygame_gui.UIManager(
            WINDOW_SIZE, "themes/buttons/menu_buttons.json")
        self.running = True
        self.game_on = False
        self.info_on = False
        self.construction = False
        self.chaos_on = False
        self.game = None
        self.constructor = None
        self.chaos_study = None
        self.chaos_mode = False

        self.slb_rect = [
            pygame.Rect((135, WINDOW_HEIGHT - 50 * 3 // 2), (100, 50)),
            pygame.Rect((WINDOW_WIDTH // 2 - 50, WINDOW_HEIGHT // 2 - 50),
                        (100, 50))
        ]
        self.select_level_button = pygame_gui.elements.UIButton(
            relative_rect=self.slb_rect[1],
            text='Levels',
            manager=self.manager,
            object_id="menu_button")
        self.mmb_rect = [
            pygame.Rect((25, WINDOW_HEIGHT - 50 * 3 // 2), (100, 50)),
            pygame.Rect((WINDOW_WIDTH // 2 - 50, WINDOW_HEIGHT // 2 + 35),
                        (100, 50))
        ]
        self.main_menu_button = pygame_gui.elements.UIButton(
            relative_rect=self.mmb_rect[0],
            text='Main menu',
            manager=self.manager,
            visible=0,
            object_id="menu_button")
        self.cb_rect = self.slb_rect[1].copy()
        self.cb_rect.top = self.cb_rect.bottom + 5
        self.credits_button = pygame_gui.elements.UIButton(
            relative_rect=self.cb_rect,
            text='Credits',
            manager=self.manager,
            object_id="menu_button")
        self.text_box = None
        self.gbb_rect = pygame.Rect((685, WINDOW_HEIGHT - 50 * 3 // 2),
                                    (100, 50))
        self.go_back_button = pygame_gui.elements.UIButton(
            relative_rect=self.gbb_rect,
            text="Go back",
            manager=self.manager,
            visible=0,
            object_id="menu_button")
        self.help_button = pygame_gui.elements.UIButton(
            relative_rect=self.gbb_rect,
            text='Help',
            manager=self.manager,
            object_id="menu_button",
            visible=0)
        self.exit_rect = self.cb_rect.copy()
        self.exit_rect.top = self.cb_rect.bottom + 5
        self.exit_button = pygame_gui.elements.UIButton(
            relative_rect=self.exit_rect,
            text='Exit',
            manager=self.manager,
            object_id="menu_button")
        self.lb_managers = []
        self.level_buttons = self.make_level_buttons()
        self.new_level_button = pygame_gui.elements.UIButton(
            relative_rect=self.slb_rect[0],
            text='New level',
            manager=self.manager,
            visible=0,
            object_id="menu_button")
        self.chb_rect = pygame.Rect((245, WINDOW_HEIGHT - 50 * 3 // 2),
                                    (100, 50))
        self.chaos_button = pygame_gui.elements.UIButton(
            relative_rect=self.chb_rect,
            text="Chaos",
            manager=self.manager,
            visible=0,
            object_id="menu_button")
        self.sliders_rect = [
            pygame.Rect((245, WINDOW_HEIGHT - 50 * 3 // 2), (100, 50)),
            pygame.Rect((355, WINDOW_HEIGHT - 50 * 3 // 2), (100, 50)),
            pygame.Rect((465, WINDOW_HEIGHT - 50 * 3 // 2), (100, 50)),
        ]
        self.sliders = []
        self.slider_values = [pygame.Surface((100, 20)) for i in range(3)]

        self.rb_rect = pygame.Rect((575, WINDOW_HEIGHT - 50 * 3 // 2),
                                   (100, 50))
        self.restart_button = pygame_gui.elements.UIButton(
            relative_rect=self.rb_rect,
            text="Restart",
            manager=self.manager,
            visible=0,
            object_id="menu_button")
示例#10
0
def start_screen():
    global pmg_factor
    global pidentification
    main_menu_screen = pygame.display.set_mode(size)
    enter_sound.stop()
    mainmenu_sound.set_volume(0.15)
    mainmenu_sound.play(-1)
    running = True
    fon = pygame.transform.scale(load_image('заставка.jpg'), (width, height))
    main_menu_screen.blit(fon, (0, 0))
    ptp = cur.execute(
        f"SELECT topnum FROM pacman_top WHERE playerid = {pidentification}"
    ).fetchone()[0]
    ttp = cur.execute(
        f"SELECT topnum FROM tetris_top WHERE playerid = {pidentification}"
    ).fetchone()[0]
    font = pygame.font.SysFont("Times New Roman", 35, bold=True)
    label1 = font.render(f"МЕСТО В ПАКМАН ТОПЕ: {ptp}", 1, (0, 255, 0))
    label2 = font.render(f"МЕСТО В ТЕТРИС ТОПЕ: {ttp}", 1, (0, 255, 0))
    screen.blit(label1, (5, 5))
    screen.blit(label2, (5, 45))
    manager = pygame_gui.UIManager((800, 700))
    pacmanbutton = pygame_gui.elements.UIButton(relative_rect=pygame.Rect(
        (575, 10), (200, 100)),
                                                text='ПАКМАН',
                                                manager=manager)
    tetrisbutton = pygame_gui.elements.UIButton(relative_rect=pygame.Rect(
        (575, 125), (200, 100)),
                                                text='ТЕТРИС',
                                                manager=manager)
    toppacman = pygame_gui.elements.UIButton(relative_rect=pygame.Rect(
        (575, 240), (200, 100)),
                                             text='ТОП ПАКМАН',
                                             manager=manager)
    toptetris = pygame_gui.elements.UIButton(relative_rect=pygame.Rect(
        (575, 355), (200, 100)),
                                             text='ТОП ТЕТРИС',
                                             manager=manager)
    gamespacman = pygame_gui.elements.UIButton(relative_rect=pygame.Rect(
        (575, 470), (200, 100)),
                                               text='ИГРЫ ПАКМАН',
                                               manager=manager)
    gamestetris = pygame_gui.elements.UIButton(relative_rect=pygame.Rect(
        (575, 585), (200, 100)),
                                               text='ИГРЫ ТЕТРИС',
                                               manager=manager)
    while running:
        manager.update(clock.tick(50))
        manager.draw_ui(main_menu_screen)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                terminate()
            if event.type == pygame.USEREVENT:
                if event.user_type == pygame_gui.UI_BUTTON_PRESSED:
                    if event.ui_element == pacmanbutton:
                        tetrisbutton.kill()
                        pacmanbutton.kill()
                        mainmenu_sound.stop()
                        pacman_screen()
                    if event.ui_element == tetrisbutton:
                        tetrisbutton.kill()
                        pacmanbutton.kill()
                        tetris_game_sound.set_volume(0.10)
                        tetris_game_sound.play(-1)
                        mainmenu_sound.stop()
                        main(win)
                    if event.ui_element == toppacman:
                        os.startfile('pacman_pics_n_fields\топ пакмана.xlsx')
                    if event.ui_element == toptetris:
                        os.startfile('pacman_pics_n_fields\топ тетриса.xlsx')
                    if event.ui_element == gamespacman:
                        os.startfile(
                            f"pacman_pics_n_fields\{pidentification}_pac.xlsx")
                    if event.ui_element == gamestetris:
                        os.startfile(
                            f"pacman_pics_n_fields\{pidentification}_tet.xlsx")
            manager.process_events(event)
        pygame.display.flip()
import pygame
import pygame_gui

# Rough current performance measure - Button creation time taken: 4.392 seconds. (54 x rounded rectangles)

pygame.init()

pygame.display.set_caption('Button Theming Test')
window_surface = pygame.display.set_mode((800, 600))
manager = pygame_gui.UIManager((800, 600),
                               'data/themes/button_theming_test_theme.json')
clock = pygame.time.Clock()

background = pygame.Surface((800, 600))
background.fill(manager.get_theme().get_colour(None, None, 'dark_bg'))

load_time_1 = clock.tick()

button_row_width = 100
button_row_height = 40
spacing = 20
for j in range(1, 10):
    for i in range(1, 7):
        position = (i * spacing + ((i - 1) * button_row_width),
                    (j * spacing + ((j - 1) * button_row_height)))
        pygame_gui.elements.UIButton(relative_rect=pygame.Rect(
            position, (button_row_width, button_row_height)),
                                     text=str(i) + ',' + str(j),
                                     manager=manager,
                                     object_id='#' + str(i) + ',' + str(j))
示例#12
0
def conect_to_bd(reg_or_enter):
    enter = pygame.display.set_mode(size)
    running = True
    nn_txt = None
    pw_txt = None
    fon = pygame.transform.scale(load_image('связь с бд.jpg'), (width, height))
    enter.blit(fon, (0, 0))
    manager = pygame_gui.UIManager((800, 700))
    nickname = pygame_gui.elements.UITextEntryLine(relative_rect=pygame.Rect(
        (475, 175), (300, 500)),
                                                   manager=manager)
    password = pygame_gui.elements.UITextEntryLine(relative_rect=pygame.Rect(
        (475, 350), (300, 500)),
                                                   manager=manager)
    while running:
        font1 = pygame.font.SysFont("Times New Roman", 25, bold=True)
        label1 = font1.render("ПОСЛЕ КАЖДОГО ВВОДА НАЖИМАЙТЕ КЛАВИШУ ENTER!!!",
                              1, (0, 255, 255))
        screen.blit(label1, (15, 20))
        font2 = pygame.font.SysFont("Times New Roman", 70, bold=True)
        label2 = font2.render("ВВЕДИТЕ НИКНЕЙМ:", 1, (0, 255, 255))
        screen.blit(label2, (25, 100))
        font3 = pygame.font.SysFont("Times New Roman", 70, bold=True)
        label3 = font3.render("ВВЕДИТЕ ПАРОЛЬ:", 1, (0, 255, 255))
        screen.blit(label3, (105, 275))
        pygame.display.update()
        manager.update(clock.tick(50))
        manager.draw_ui(enter)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                enter_screen()
            if event.type == pygame.USEREVENT:
                if event.user_type == pygame_gui.UI_TEXT_ENTRY_FINISHED:
                    if event.text == '':
                        font4 = pygame.font.SysFont("Times New Roman",
                                                    60,
                                                    bold=True)
                        label4 = font4.render("ПРИДУМАЙТЕ НИКНЕЙМ", 1,
                                              (255, 0, 0))
                        label5 = font4.render("И ПАРОЛЬ!!!", 1, (255, 0, 0))
                        screen.blit(label4, (10, 375))
                        screen.blit(label5, (250, 475))
                        pygame.display.update()
                    elif event.ui_element == nickname:
                        nn_txt = event.text
                    elif event.ui_element == password:
                        pw_txt = event.text
                    if nn_txt is not None and pw_txt is not None:
                        global pidentification
                        global pmg_factor
                        global btp
                        cur.execute(
                            "SELECT nickname, password FROM information WHERE nickname = ? AND password = ?",
                            (nn_txt, pw_txt))
                        # регистрация
                        if reg_or_enter:
                            if cur.fetchone() is None:
                                cur.execute(
                                    f"INSERT INTO information (nickname, password) VALUES (?, ?)",
                                    (nn_txt, pw_txt))
                                con.commit()
                                pidentification = (cur.execute(
                                    f"SELECT playerid FROM information WHERE nickname = ? AND password = ?",
                                    (nn_txt, pw_txt)).fetchone())[0]
                                cur.execute(
                                    f"INSERT INTO pacman_top (playerid, best_game_pacman_time,"
                                    f" best_game_pacman_points, factor) VALUES (?, ?, ?, ?)",
                                    (pidentification, 0, 0, pmg_factor))
                                con.commit()
                                cur.execute(
                                    f"INSERT INTO tetris_top (playerid, best_tetris_points) VALUES (?, ?)",
                                    (pidentification, 0))
                                con.commit()
                                # обновление ексель файла с пакман топом
                                update_pacman_top_xl()
                                # обновление ексель файла с тетрис топом
                                update_tetris_top_xl()

                                wb_p = openpyxl.Workbook()
                                wb_p.save(
                                    f'pacman_pics_n_fields\{pidentification}_pac.xlsx'
                                )

                                wb_t = openpyxl.Workbook()
                                wb_t.save(
                                    f"pacman_pics_n_fields\{pidentification}_tet.xlsx"
                                )

                                start_screen()
                            else:
                                font4 = pygame.font.SysFont("Times New Roman",
                                                            40,
                                                            bold=True)
                                label4 = font4.render(
                                    "ПРИДУМАЙТЕ ПАЖАЛУЙСТА ДРУГОЙ", 1,
                                    (255, 0, 0))
                                label5 = font4.render(
                                    "ПАРОЛЬ И / ИЛИ НИКНЕЙМ!!!", 1,
                                    (255, 0, 0))
                                screen.blit(label4, (10, 550))
                                screen.blit(label5, (125, 600))
                        # вход
                        else:
                            if cur.fetchone() is None:
                                font4 = pygame.font.SysFont("Times New Roman",
                                                            47,
                                                            bold=True)
                                label4 = font4.render(
                                    "НЕПРАВИЛЬНО ВВЕДЁН ПАРОЛЬ", 1,
                                    (255, 0, 0))
                                label5 = font4.render("И / ИЛИ НИКНЕЙМ!!!", 1,
                                                      (255, 0, 0))
                                screen.blit(label4, (10, 550))
                                screen.blit(label5, (150, 600))
                            else:
                                pidentification = (cur.execute(
                                    f"SELECT playerid FROM information WHERE nickname = ?"
                                    f" AND password = ?",
                                    (nn_txt, pw_txt)).fetchone())[0]
                                pmg_factor = cur.execute(
                                    f"SELECT factor FROM pacman_top"
                                    f" WHERE playerid = {pidentification}"
                                ).fetchone()[0]
                                btp = cur.execute(
                                    f"SELECT best_tetris_points FROM tetris_top"
                                    f" WHERE playerid = {pidentification}"
                                ).fetchone()[0]
                                start_screen()
            manager.process_events(event)
        pygame.display.flip()
    def update(self, time_delta: float):
        super().update(time_delta)

        if self.camera is not None:

            self.cam_image.set_image(pygame.transform.smoothscale(self.camera.get_image(),
                                                                  self.get_container().rect.size))


pygame.init()
pygame.camera.init()

pygame.display.set_caption('Quick Start')
window_surface = pygame.display.set_mode((800, 600))
manager = pygame_gui.UIManager((800, 600), 'data/themes/quick_theme.json')

background = pygame.Surface((800, 600))
background.fill(manager.ui_theme.get_colour(None, None, 'dark_bg'))


cam_window_pos = [10, 10]
num_connected_cameras = 2
cam_names = ["My Camera", "My Boss"]
for cam_id in range(0, 2):
    cam_window_rect = pygame.Rect(0, 0, 400, 300)
    cam_window_rect.topleft = cam_window_pos
    CameraWindow(cam_window_rect, cam_id, cam_names[cam_id], manager)
    cam_window_pos = (cam_window_pos[0] + 420,
                      cam_window_pos[1])
示例#14
0
def main():
    pygame.mixer.pre_init()
    pygame.init()
    pygame.font.init()
    vec = pygame.math.Vector2

    manager_menu = pygame_gui.UIManager((320, 240))
    manager_death = pygame_gui.UIManager((320, 240))
    manager_win = pygame_gui.UIManager((320, 240))

    class Hero:  # main character
        def __init__(self, level):
            self.jump = False
            self.jump_sound = pygame.mixer.Sound(
                link_file('jump.wav', DATA_FILE))
            self.moving_left = False
            self.moving_right = False
            self.animations_right = [
                load_image('walk1.png', DATA_FILE, -1),  # add animations
                load_image('walk2.png', DATA_FILE, -1),
                load_image('walk3.png', DATA_FILE, -1),
                load_image('walk2.png', DATA_FILE, -1),
                load_image('walk1.png', DATA_FILE, -1),
                load_image('walk2.png', DATA_FILE, -1),
                load_image('walk3.png', DATA_FILE, -1),
                load_image('walk2.png', DATA_FILE, -1),
                load_image('walk1.png', DATA_FILE, -1),
                load_image('walk2.png', DATA_FILE, -1),
                load_image('walk3.png', DATA_FILE, -1),
                load_image('walk2.png', DATA_FILE, -1)
            ]
            self.animations_left = [
                load_image('walk-1.png', DATA_FILE, -1),
                load_image('walk-2.png', DATA_FILE, -1),
                load_image('walk-3.png', DATA_FILE, -1),
                load_image('walk-2.png', DATA_FILE, -1),
                load_image('walk-1.png', DATA_FILE, -1),
                load_image('walk-2.png', DATA_FILE, -1),
                load_image('walk-3.png', DATA_FILE, -1),
                load_image('walk-2.png', DATA_FILE, -1),
                load_image('walk-1.png', DATA_FILE, -1),
                load_image('walk-2.png', DATA_FILE, -1),
                load_image('walk-3.png', DATA_FILE, -1),
                load_image('walk-2.png', DATA_FILE, -1)
            ]
            self.sprite = load_image('stand1.png', DATA_FILE, -1)
            self.start_pos = (10, HEIGHT - self.sprite.get_height() - 48)
            self.player_location = [self.start_pos[0], self.start_pos[1]]
            self.body = level.CreateDynamicBody(  # box2d collision create
                angle=0,
                position=(self.get_box2d_coordinates()),
                shapes=b.b2PolygonShape(
                    box=(self.get_box2d_size())))  # 1 = 20 pixel
            self.start_box2d = self.get_box2d_coordinates()
            self.x, self.y = 0, 0
            self.check_jump = 0
            self.anim_count = 0
            self.stand = True
            self.dir = 1  # 1 right. -1 left
            self.run = False
            self.j_check = False
            self.start = True

        def get_box2d_coordinates(self):
            formula_x = 0.1 * (self.player_location[0] +
                               (self.sprite.get_width() / 2))
            if formula_x > 0:
                formula_x -= 0.05
            elif formula_x < 0:
                formula_x += 0.05
            formula_y = 0.1 * ((HEIGHT - self.player_location[1]) -
                               (self.sprite.get_height() / 2))
            if formula_y > 0:
                formula_y -= 0.05
            elif formula_y < 0:
                formula_y += 0.05
            return formula_x, formula_y

        def merge(self):  # merge sprite and dynamic box2d body
            x, y = person.body.position
            self.player_location = [
                x / 0.1 - (self.sprite.get_width() / 2) + 0.05,
                -(y / 0.1 - HEIGHT + (self.sprite.get_height() / 2))
            ]

        def get_box2d_size(self):
            size_x = 0.05 * (self.sprite.get_width() - 1)
            size_y = 0.05 * (self.sprite.get_height() - 1)
            return size_x, size_y

        def get_x_y(self):
            self.x = self.body.linearVelocity.x
            self.y = self.body.linearVelocity.y

        def set_x_y(self):
            self.body.linearVelocity.x = self.x
            self.body.linearVelocity.y = self.y

        def awake(self):  # if not awake - object freeze
            self.body.awake = True

        def movement(self, events):
            if events.type == KEYDOWN:
                if events.key == K_RIGHT or events.key == K_d:
                    self.moving_right = True
                if events.key == K_LEFT or event.key == K_a:
                    self.moving_left = True

                if events.key == K_UP or events.key == K_w or events.key == K_SPACE:
                    if self.jump and len(self.body.contacts) != 0:
                        self.y += 40
                        self.jump_sound.play()
                        self.jump = False
                        self.stand = False
                        self.check_jump = 0
            if events.type == KEYUP:
                if events.key == K_RIGHT or events.key == K_d:
                    self.moving_right = False
                if events.key == K_LEFT or events.key == K_a:
                    self.moving_left = False

        def change_dir(self):
            if self.body.linearVelocity[0] > 0:
                self.dir = 1
                self.run = True
            elif self.body.linearVelocity[0] < 0:
                self.dir = -1
                self.run = True
            if self.body.linearVelocity[0] == 0:
                self.anim_count = 0
                self.run = False

        def check(self):  # control velocity
            if self.moving_left:
                if self.x > -13:
                    self.x -= 1
            if self.moving_right:
                if self.x < 13:
                    self.x += 1
            if len(self.body.contacts) != 0:
                if self.check_jump != 8:
                    self.check_jump += 1
                if self.check_jump == 8 and self.body.linearVelocity[1] == 0:
                    self.jump = True
                    self.j_check = False
                    self.start = False
                    if not self.run:
                        if self.dir == 1:
                            self.sprite = load_image('stand1.png', DATA_FILE,
                                                     -1)
                        elif self.dir == -1:
                            self.sprite = load_image('stand-1.png', DATA_FILE,
                                                     -1)
                    elif self.run:
                        pass

        def draw_polygons(self, py_screen):
            for fixture in self.body.fixtures:
                shape = fixture.shape
                vertices = [
                    self.body.transform * v * 10 for v in shape.vertices
                ]
                vertices = [(v[0], 240 - v[1]) for v in vertices]
                pygame.draw.polygon(py_screen, (255, 255, 255), vertices)

        def death(self):
            if self.player_location[1] + self.sprite.get_height() >= HEIGHT:
                return False
            else:
                return True

        def win(self):
            if self.player_location[0] >= (py_world.get_width() - (16 * 10.5)):
                return True
            else:
                return False

    class Menu:
        def __init__(self, man):
            self.manager = man
            self.layer = pygame.Surface((320, 240))
            self.label = pygame_gui.elements.UILabel(relative_rect=pygame.Rect(
                (70, 30), (180, 60)),
                                                     text='Super Yandex Proj.',
                                                     manager=self.manager)
            self.switch = pygame_gui.elements.UIButton(
                relative_rect=pygame.Rect((130, 90), (60, 60)),
                text="Start",
                manager=self.manager)
            self.author = pygame_gui.elements.UILabel(
                relative_rect=pygame.Rect((70, 190), (180, 60)),
                text='Made by Alexey Alexey.',
                manager=self.manager)

    class Death:
        def __init__(self, man):
            self.manager = man
            self.layer = pygame.Surface((320, 240))
            self.label = pygame_gui.elements.UILabel(relative_rect=pygame.Rect(
                (70, 30), (180, 60)),
                                                     text='YOU DIED',
                                                     manager=self.manager)
            self.label1 = pygame_gui.elements.UILabel(
                relative_rect=pygame.Rect((70, 190), (180, 60)),
                text='Press ESC to exit.',
                manager=self.manager)

    class Win:
        def __init__(self, man):
            self.manager = man
            self.layer = pygame.Surface((320, 240))
            self.label = pygame_gui.elements.UILabel(relative_rect=pygame.Rect(
                (70, 30), (180, 60)),
                                                     text='YOU WIN!!!',
                                                     manager=self.manager)
            self.label = pygame_gui.elements.UILabel(relative_rect=pygame.Rect(
                (70, 190), (180, 60)),
                                                     text='Press ESC to exit.',
                                                     manager=self.manager)

    class Camera:
        def __init__(self, player):
            self.player = player
            self.offset = vec(0, 0)
            self.offset_float = vec(0, 0)
            self.w, self.h = 320, 240
            self.CONST = vec(-self.w / 2 + self.player.sprite.get_width() / 2,
                             -self.player.sprite.get_height() + 20)

        def scroll(self):
            self.method.scroll()

        def set_method(self, method):
            self.method = method

    class CamScroll(ABC):
        def __init__(self, cam, player):
            self.player = player
            self.camera = cam

        @abstractmethod
        def scroll(self):
            pass

    class Follow(CamScroll):
        def __init__(self, cam, player):
            CamScroll.__init__(self, cam, player)

        def scroll(self):
            self.camera.offset_float.x += (self.player.player_location[0] -
                                           self.camera.offset_float.x +
                                           self.camera.CONST.x)
            self.camera.offset.x, self.camera.offset.y = int(
                self.camera.offset_float.x), 0

    class Border(CamScroll):
        def __init__(self, cam, player):
            CamScroll.__init__(self, cam, player)

        def scroll(self):
            self.camera.offset_float.x += (self.player.player_location[0] -
                                           self.camera.offset_float.x +
                                           self.camera.CONST.x)
            self.camera.offset.x, self.camera.offset.y = int(
                self.camera.offset_float.x), 0
            self.camera.offset.x = max(self.player.player_location,
                                       self.camera.offset.x)
            self.camera.offset.x = min(
                self.camera.offset.x, self.player.player_location +
                self.player.sprite - self.camera.w)

    class Auto(CamScroll):
        def __init__(self, cam, player):
            CamScroll.__init__(self, cam, player)

        def scroll(self):
            self.camera.offset.x += 1

    WIDTH = 320
    HEIGHT = 240
    DATA_FILE = 'data'
    SIZE = (WIDTH, HEIGHT)
    SKY = (119, 128, 225)

    flag = pygame.SCALED | pygame.FULLSCREEN
    screen = pygame.display.set_mode(SIZE, flag)
    pygame.display.set_caption('Super Yandex proj.')
    clock = pygame.time.Clock()

    pygame.mixer.music.load(link_file('ambient.wav', DATA_FILE))
    pygame.mixer.music.play(-1)
    button_click = pygame.mixer.Sound(link_file('button.wav', DATA_FILE))
    death_sound = pygame.mixer.Sound(link_file('death.wav', DATA_FILE))
    win_sound = pygame.mixer.Sound(link_file('win.wav', DATA_FILE))

    world = b.b2World()
    world.gravity = (0, -100)
    world.CreateStaticBody(position=(0, -5),
                           shapes=b.b2PolygonShape(box=(70, 5)))
    world.CreateStaticBody(position=(-5, 0),
                           shapes=b.b2PolygonShape(box=(5.05, 100)))

    menu = Menu(manager_menu)
    death = Death(manager_death)
    win = Win(manager_win)

    person = Hero(world)
    my_map = Map('main1.tmx', world, DATA_FILE, HEIGHT)
    py_world = pygame.Surface(my_map.get_size())
    camera = Camera(person)
    follow = Follow(camera, person)
    Auto(camera, person)
    Border(camera, person)

    camera.set_method(follow)
    music = False
    start_menu = True
    switch = True
    win_check = False
    death_check = False
    running = True
    delta_time = 17 / 1000.0  # time for refresh gui
    while running:  # game loop
        person.merge()
        person.awake()
        person.get_x_y()

        for event in pygame.event.get():
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    return
            if event.type == QUIT:
                return
            if not start_menu and not switch:
                person.movement(event)
            if start_menu:
                if event.type == pygame.USEREVENT:
                    if event.user_type == pygame_gui.UI_BUTTON_PRESSED:
                        if event.ui_element == menu.switch:
                            button_click.play(0)
                            start_menu = False
                            music = True
                            switch = False
            manager_menu.process_events(event)

        menu.manager.update(delta_time)  # update gui
        death.manager.update(delta_time)
        win.manager.update(delta_time)

        person.check()
        person.set_x_y()
        person.change_dir()

        if music:  # main loop music
            pygame.mixer.music.load(link_file('disco.wav', DATA_FILE))
            pygame.mixer.music.play(-1, 0, 3000)
            pygame.mixer.music.set_volume(0.2)
            music = False

        if person.anim_count + 1 >= 60:
            person.anim_count = 0
        elif not person.jump and not person.start:
            if person.dir == 1:
                person.sprite = load_image('jump1.png', DATA_FILE, -1)
            elif person.dir == -1:
                person.sprite = load_image('jump-1.png', DATA_FILE, -1)
            person.j_check = True
        elif person.moving_right:
            person.sprite = person.animations_right[person.anim_count // 5]
            person.anim_count += 1
        elif person.moving_left:
            person.sprite = person.animations_left[person.anim_count // 5]
            person.anim_count += 1

        camera.scroll()  # camera update

        screen.fill(SKY)
        py_world.fill(SKY)

        my_map.render(py_world)
        screen.blit(py_world, [0 - camera.offset.x, 0])
        screen.blit(person.sprite, [
            person.player_location[0] - camera.offset.x,
            person.player_location[1]
        ])

        if start_menu:
            switch = True
            menu.layer.fill(SKY)
            menu.manager.draw_ui(menu.layer)
            screen.blit(menu.layer, [0, 0])

        if not person.death():
            switch = True
            if not death_check:
                pygame.mixer.music.stop()
                death_sound.play()
                death_check = True
            death.layer.fill(SKY)
            death.manager.draw_ui(death.layer)
            screen.blit(death.layer, [0, 0])

        if person.win():
            switch = True
            if not win_check:
                pygame.mixer.music.stop()
                win_sound.play()
                win_check = True
            win.layer.fill(SKY)
            win.manager.draw_ui(win.layer)
            screen.blit(win.layer, [0, 0])

        pygame.display.flip()
        world.Step(1 / 60, 10, 10)
        clock.tick(60)
    terminate()
示例#15
0
    def __init__(self, screenSize):

        # Initialise Pygame Library
        pygame.init()

        # Create Program Window
        pygame.display.set_caption('Duck Hunt: AI Edition')
        icon = pygame.transform.scale(pygame.image.load("images/icon.png"),
                                      (32, 32))
        pygame.display.set_icon(icon)

        # Adjust DPI Awareness for Windows OS
        awareness = ctypes.c_int()
        errorCode = ctypes.windll.shcore.GetProcessDpiAwareness(
            0, ctypes.byref(awareness))

        # Set DPI Awareness  (Windows 10 and 8)
        errorCode = ctypes.windll.shcore.SetProcessDpiAwareness(2)

        # Initialise program clock
        self.clock = pygame.time.Clock()

        # Pre-load all background images and sizes
        self.bgSize = (1925, 1085)
        self.background = pygame.Surface(self.bgSize)
        self.mainBG = pygame.transform.scale(
            pygame.image.load("images/editedStage.png"), self.bgSize)
        self.trainBG = pygame.transform.scale(
            pygame.image.load("images/trainBackground.png"), self.bgSize)
        self.configBG = pygame.transform.scale(
            pygame.image.load("images/settingsScreen.png"), self.bgSize)

        # Create and display window
        self.windowSurface = pygame.display.set_mode(screenSize)

        # Initialise App Constants
        self.running = True
        self.screenSize = screenSize

        # Preload + Create screen managers to handle graphical elements
        # Note: The screen codes for each screen are the following:
        # 0 = Play Screen, 1 = Train Screen, 2 = Settings Screen, 5 = Main Menu
        self.managers = {
            '0': gui.UIManager(self.screenSize, "./themes/playScreen.json"),
            '1': gui.UIManager(self.screenSize, "./themes/trainScreen.json"),
            '2': gui.UIManager(self.screenSize,
                               "./themes/settingsScreen.json"),
            '5': gui.UIManager(self.screenSize, "./themes/mainScreen.json")
        }

        # Set Current Screen Manager to Main Menu
        self.manager = self.managers['5']

        # Create an object instance for the main screen
        self.currentScreen = MainScreenInstance(self.screenSize, self.manager)

        # Initialise Play Screen Variables / Constants
        self.game = False
        self.validate = True
        self.gameInstance = None

        # Create custom event for play screen
        self.gameEvent = pygame.USEREVENT + 1

        # Preload cursor images and display surfaces
        self.cursorSurface = pygame.Surface((100, 100), pygame.SRCALPHA)
        self.cursorImageClassic = pygame.transform.scale(
            pygame.image.load("images/crosshair.png"), (100, 100))
        self.cursorImageComplex = pygame.transform.scale(
            pygame.image.load("images/crosshair1.png"), (100, 100))
        self.cursorImageSimple = pygame.transform.scale(
            pygame.image.load("images/crosshair2.png"), (100, 100))
        self.cursorRect = (self.screenSize[0] // 2 - 50,
                           self.screenSize[1] // 2 - 50)

        # Initialise Train Screen Variables / Constants
        self.training = False
        self.initialTraining = False
        self.trainInstance = None
        self.trainSpeedDict = {}
        self.trainDiffDict = {}
        self.model = ()
        self.testOption = False
        self.trainSpeedDict = None
        self.trainDiffDict = None

        # Create custom event for train screen
        self.initialTrainEvent = pygame.USEREVENT + 2
        self.trainEvent = pygame.USEREVENT + 3

        # Initialise Function Dictionary
        # This links all the buttons from other object instances to functions in this object.
        # Ensures all interactable elements are linked to processes
        self.masterDirectory = {
            '0': self.play,
            '1': self.train,
            '1.1': self.initialTrainSelection,
            '1.2': self.returnInitialTraining,
            '1.3': self.processTraining,
            '1.4': self.swapModes,
            '1.5': self.adjustTrainingSpeed,
            '1.6': self.adjustTrainingDifficulty,
            '1.7': self.saveQuit,
            '2': self.settings,
            '2.1': self.swapPage,
            '2.2': self.bgSwap,
            '2.3': self.handlePSOptions,
            '2.4': self.handleTSOptions,
            '2.5': self.handleTrainSetOptions,
            '2.6': self.handleBufferOptions,
            '2.7': self.writeSave,
            '2.8': self.clearScores,
            '2.9.1': self.promptWarning,
            '2.9.2': self.returnSettingScreen,
            '2.9.3': self.deleteModel,
            '3': self.quit,
            '4': self.pause,
            '4.1': self.resume,
            '4.2': self.gameOver,
            '4.3': self.testOver,
            '5': self.returnMenu,
        }

        # Initialise all setting variables

        self.settingsPanelDict = None
        self.config = False

        self.bgConfig = [0, 0, 1]
        self.backgroundOptions = [("Default", self.mainBG),
                                  ("Serenity", self.trainBG),
                                  ("Sunset", self.configBG)]

        self.bgLeftButtons = None
        self.bgRightButtons = None
        self.crosshair = 0
        self.tCrosshair = 0
        self.crosshairOptions = [("Classic", self.cursorImageClassic),
                                 ("Complex", self.cursorImageComplex),
                                 ("Simple", self.cursorImageSimple)]

        self.optionsPS = None
        self.gameFX = True
        self.optionsTS = None
        self.trainFX = True

        self.trainSetOptions = ["500", "1000", "5000", "10000"]
        self.bufferOptions = [("Slow", 8), ("Normal", 4), ("Fast", 2),
                              ("Instant", 0)]

        self.optionsTrainingSet = None
        self.optionsBuffer = None
        self.trainingSetNum = 2
        self.bufferNum = 1
        self.masterSettings = []

        # Create custom event for settings screen
        self.configEvent = pygame.USEREVENT + 4

        # Sound Variables
        # Stores previous values for sound/music
        self.prevMusic = 0
        self.prevSound = 0

        # Current values for sound/music
        self.musicVol = 0.5
        self.soundVol = 0.5

        # Unload settings from config.txt and apply them to the app
        self._unloadSettings()

        # Play Initial Menu Music
        pygame.mixer.music.load("./sounds/start1.mp3")
        pygame.mixer.music.set_volume(self.musicVol)
        pygame.mixer.music.play()

        # Draw background onto screen
        self.background.blit(self.backgroundOptions[self.bgConfig[0]][1],
                             (-2, -2))
示例#16
0
    def run(self):

        # SPRITE GROUPS
        self.bullets = py.sprite.LayeredDirty()
        self.enemies = py.sprite.LayeredDirty()
        self.clouds = py.sprite.LayeredDirty()
        self.buffs = py.sprite.LayeredDirty()
        self.all_sprites = py.sprite.LayeredDirty()

        # Instantiate player.
        self.all_sprites.add(self.player)

        # Initialize pygame
        py.init()

        # create UI manager
        self.manager = gui.UIManager((self.SW, self.SH))

        # time variables
        clock = py.time.Clock()  # time handler for game
        manual_start = 0  # shooting with space time handler if turned on
        auto_start = 0  # auto shooting time handler
        sBooster = 0  # for auto shooting time control
        time_delta = 0  # time handler for manager

        # game variables
        running = True  # game loop
        score = 0  # player score
        won = False  # if user won
        checker = True  # for spawning buffs
        customMouse = ()  # custom mouse position if movement with mouse is on

        # ========================================== SETTERS ====================================================
        maxWaves = 1
        levelTitle = 'Level 1'

        # ================================== MUTABLE GAME VARIABLES ===============================================
        buffSpawn = 5
        maxScore = 50
        currentWave = 1

        # initialize HUD WITH SCREEN SIZE, BACKGROUND, LEVEL NAME AND # OF WAVES
        hud = HUD(self.screen,self.manager, self.background,levelTitle,currentWave)

        # Setup for sounds. Defaults are good.
        #py.mixer.init()

        # Load and play background music
        #py.mixer.music.load("Media/game2.mp3")
        #py.mixer.music.set_volume(0.3)
        #py.mixer.music.play(loops=-1)

        # TIMER EVENTS FOR SPAWNING CLOUDS AND ENEMIES
        self.ADDENEMY = py.USEREVENT + 1
        py.time.set_timer(self.ADDENEMY, 2000)
        self.ADDCLOUD = py.USEREVENT + 2
        py.time.set_timer(self.ADDCLOUD, 5000)


        # ============================ MAIN GAME LOOP =============================================

        while running:

            # UPDATE MANAGER
            self.manager.update(time_delta)

            # WIN ARGUMENT
            if score >= maxScore:
                won = True
                running = False
                print("you won!")

            # LOSE ARGUMENT
            if self.player.lives <= 0:
                won = False
                running = False
                print("you died!")

            # MOUSE SET IF MOVEMENT IS WITH MOUSE
            if self.mouse:
                py.mouse.set_pos(960, 540)

            # ============================== CHECK ALL EVENTS START ====================================
            for event in py.event.get():
                # QUIT EVENT
                if event.type == py.QUIT or event.type == QUIT:
                    running = False
                    won = False

                # --------------------------------- PRESSED KEY EVENTS --------------------------------
                elif event.type == py.KEYDOWN:

                    # P PAUSE
                    if event.key == K_p:
                        py.mixer.music.pause()
                        hud.pause()
                        py.mixer.music.unpause()

                    # ESC
                    if event.key == K_ESCAPE:
                        running = False
                        won = False

                    # SPACE IF TURNED ON
                    if event.key == K_SPACE and self.space:
                        manual_timer = py.time.get_ticks() - manual_start
                        if manual_timer >= 600 - sBooster:
                            new_bullet = Bullet1(self.player.rect.center, self.player.damage, self.player.bspeed)
                            self.bullets.add(new_bullet)
                            self.all_sprites.add(new_bullet)
                            manual_start = py.time.get_ticks()

                # -------------------------------- FINISHED CHECKING KEYS ---------------------------------------

                # MOUSE MOTION EVENT IF TURNED ON
                elif event.type == MOUSEMOTION and self.mouse:
                    currentP = py.mouse.get_pos()
                    customMouse = ((currentP[0] - 960) * 0.3, (currentP[1] - 540)*0.3)
                    self.player.rect.move_ip(customMouse)

                # MOUSE BUTTON EVENT IF TURNED ON
                elif event.type == py.MOUSEBUTTONDOWN and event.button == 1 and self.space is not True and self.auto is not True:
                    manual_timer = py.time.get_ticks() - manual_start
                    if manual_timer >= 600 - sBooster:
                        new_bullet = Bullet1(self.player.rect.center, self.player.damage, self.player.bspeed)
                        self.bullets.add(new_bullet)
                        self.all_sprites.add(new_bullet)
                        manual_start = py.time.get_ticks()

                # ENEMY SPAWN EVENT
                elif event.type == self.ADDENEMY:
                    new_enemy = EnenemyJet(0)
                    self.enemies.add(new_enemy)
                    self.all_sprites.add(new_enemy)

                # CLOUD SPAWN EVENT
                elif event.type == self.ADDCLOUD:
                    # Create the new cloud and add it to sprite groups
                    new_cloud = Cloud()
                    self.clouds.add(new_cloud)
                    self.all_sprites.add(new_cloud)

                # PAUSE BUTTON USER EVENT FROM HUD
                elif event.type == py.USEREVENT:
                    if event.user_type == gui.UI_BUTTON_PRESSED:
                        if event.ui_element == hud.pause_button:
                            py.mixer.music.pause()
                            hud.pause()
                            py.mixer.music.unpause()

                # MANAGER PROCESS HUD GUI EVENTS
                self.manager.process_events(event)

            # =================================== EVENT CHECK LOOP FINISHED ============================================

            # SPAWN PLAYER BULLETS IF AUTO SHOOT IS ON
            auto_timer = py.time.get_ticks() - auto_start
            if auto_timer >= 600 - sBooster and self.auto:
                new_bullet = Bullet1(self.player.rect.center, self.player.damage, self.player.bspeed)
                self.bullets.add(new_bullet)
                self.all_sprites.add(new_bullet)
                auto_start = py.time.get_ticks()

            # SPAWNING BUFFS
            if score % buffSpawn == 0 and checker and score != 0:  # spawn a new buff
                num = random.randint(1, 100)
                if num in range(0, 51):
                    type = 0
                elif num in range(50, 76):
                    type = 1
                else:
                    type = 2
                new_buff = Buff(type)
                self.buffs.add(new_buff)
                self.all_sprites.add(new_buff)
                checker = False

            # CLEAR BUFF SPAWN CHECK
            elif score % buffSpawn != 0 and score != 0:
                checker = True

            # ================================== SPRITE COLLISION DETECTION ====================================

            # PLAYER BULLETS AND ENEMY COLLISION
            hits = py.sprite.groupcollide(self.enemies, self.bullets, False, True)
            for enemy, bullet_list in hits.items():
                for bullet in bullet_list:
                    enemy.health -= bullet.damage
                    # self.collision_sound.play()
                    if enemy.health <= 0:
                        score += enemy.points

            # PLAYER AND BUFF COLLISION
            hit = py.sprite.spritecollideany(self.player, self.buffs)
            if hit != None:
                if hit.type == 0:
                    if not self.player.health >= self.player.maxHealth:
                        self.player.health += hit.power
                elif hit.type == 1:
                    self.player.damage += hit.power
                else:
                    if sBooster <= 300:
                        sBooster += hit.power
                print("power up!")
                hit.kill()

            # ENEMY AND PLAYER COLLISION
            hit = py.sprite.spritecollideany(self.player, self.enemies)
            if hit != None:
                self.player.health -= hit.damage
                print("you got hit!")
                hit.kill()

            # ======================================== END COLLISION DETECTION ========================================

            # GET KEYS AND UPDATE PLAYER POSITION
            pressed_keys = py.key.get_pressed()
            self.player.update(pressed_keys)

            # UPDATE REST OF SPRITES POSITIONS
            self.enemies.update()
            self.clouds.update()
            self.bullets.update()
            self.buffs.update()

            # REDRAW BACKGROUND
            self.screen.blit(self.background, (0, 0))

            # DRAW ALL SPRITES
            for entity in self.all_sprites:
                self.screen.blit(entity.surf, entity.rect)

            # UPDATE HUD AND DRAW IT
            hud.update(currentWave, score, maxScore, self.player.health, self.player.maxHealth, self.player.lives, self.player.damage,
                       600 - sBooster, self.player.bspeed)
            self.manager.draw_ui(self.screen)

            # UPDATE SCREEN AND TICK CLOCK
            py.display.update()
            clock.tick(60)

        # ========================================= GAME LOOP DONE ==============================================

        #STOP MUSIC
        #py.mixer.music.stop()
        #py.mixer.quit()

        # RETURN IF USER WON AND SCORE
        return won, score
示例#17
0
pygame.init()
geocoder_key = "40d1649f-0493-4b70-98ba-98533de7710b"
schirota, dolgota = 51.558403, 46.038191
schirota_metki, dolgota_metki = 51.558403, 46.038191
x_maschtab = 0.01
map_file = "map.png"
running = True
screen = pygame.display.set_mode((800, 450))
screen.fill((255, 255, 255))
fon = pygame.font.Font(None, 24)
GREEN = (0, 200, 64)
type_cart = 'map'
city_add = ''
login = ''
manager = pygame_gui.UIManager((800, 450), 'theme.json')
manager_hybrid = pygame_gui.UIManager((800, 450), 'theme_1.json')
manager_map = pygame_gui.UIManager((800, 450), 'theme2.json')
manager_sat = pygame_gui.UIManager((800, 450), 'theme3.json')
manager_del = pygame_gui.UIManager((800, 450), 'del_metka.json')
# -------------------------
#------------
map_button = pygame_gui.elements.UIButton(
    relative_rect=pygame.Rect((50, 20), (100, 40)),
    text='',
    manager=manager_map)
#pygame.draw.rect(screen, GREEN, (50, 20, 100, 40))
#--------------
#pygame.draw.rect(screen, GREEN, (50, 80, 100, 40))
sat_button = pygame_gui.elements.UIButton(
    relative_rect=pygame.Rect((50, 80), (100, 40)),
示例#18
0
def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller's 'onefile' mode """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except AttributeError:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)


pygame.init()

pygame.display.set_caption('Quick Start')
window_surface = pygame.display.set_mode((800, 600))
manager = pygame_gui.UIManager((800, 600),
                               resource_path('data/themes/quick_theme.json'))

background = pygame.Surface((800, 600))
background.fill(manager.ui_theme.get_colour(None, None, 'dark_bg'))

hello_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect(
    (350, 280), (150, 40)),
                                            text='Hello',
                                            manager=manager)

clock = pygame.time.Clock()
is_running = True

while is_running:
    time_delta = clock.tick(60) / 1000.0
    for event in pygame.event.get():
示例#19
0
    def title_menu(self):
        manager = pgui.UIManager(self.screen_rect.size)
        bg = pg.Surface(self.screen_rect.size)
        bg.fill(pg.Color('#000000'))

        font = pg.font.Font(None, 150)
        title_text = font.render('Crypto Crime Fighter', True, pg.Color('#FF0000'))
        tt_rect = title_text.get_rect()
        title_x = (self.wind_width / 2) - (tt_rect.width / 2)
        title_y = 400

        # Buttons
        btn_width = 200
        btn_height = 50
        btn_x = (self.wind_width / 2) - (btn_width / 2)
        # Starting y-coordinate for the buttons so that there is room for the header
        btn_y_buffer = title_y + tt_rect.height + 200
        btn_new_game = pgui.elements.UIButton(
            relative_rect=pg.Rect(
                (btn_x, btn_y_buffer), 
                (btn_width, btn_height)
            ),
            text='New Game',
            manager=manager
        )
        btn_y_buffer += btn_height + 10

        btn_exit = pgui.elements.UIButton(
            relative_rect=pg.Rect(
                (btn_x, btn_y_buffer),
                (btn_width, btn_height)
            ),
            text='Exit Game',
            manager=manager
        )

        ui_clock = pg.time.Clock()
        while True:
            time_delta = ui_clock.tick(self.fps)/1000.0
            # Event loop
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    self.state = GameState.EXIT
                    return
                if event.type == pg.USEREVENT:
                    if event.user_type == pgui.UI_BUTTON_PRESSED:
                        if event.ui_element == btn_new_game:
                            self.state = GameState.INTROSTORY
                            return
                        elif event.ui_element == btn_exit:
                            self.state = GameState.EXIT
                            return

                manager.process_events(event)
            manager.update(time_delta)

            # Screen updates
            self.window.blit(bg, (0, 0))
            self.window.blit(title_text, (title_x, title_y))

            manager.draw_ui(self.window)

            pg.display.update()
示例#20
0
    def execute_pygame(self):
        manager = pygame_gui.UIManager((800, 600))

        hello_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect(
            (350, 275), (100, 50)),
                                                    text='Say Hello',
                                                    manager=manager)
        position_mouse = (0, 0)  # Inicializar posicion presionad
        grid = True  # Rejilla habilitada
        close = False
        timer = 0  # Necesario para el doble click
        dt = 0  # Incrementos del timer
        while not close:
            time_delta = self.clock.tick(60) / 1000.0
            keys = pygame.key.get_pressed()  # Obtencion de tecla presionada
            for event in pygame.event.get():
                if self.property_class.draw:  # Eventos para texto de name
                    self.property_class.check_text(event)
                if event.type == pygame.QUIT:
                    close = True
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    position_mouse = pygame.mouse.get_pos()
                    #print('pos', position_mouse)
                    if pygame.mouse.get_pressed()[0]:  # Boton izquierdo
                        if timer == 0 and self.property_class.modulos:
                            timer = 0.001
                        elif timer < 0.3 and not self.property_class.elem_type and self.property_class.modulos:  # Doble click apertura modulo/Debo bloquear esto mientras aun se este ejecutando el panel de propiedades
                            timer = 0
                            self.property_class.name_element.active = True  # Activar casilla de nombre propiedades
                            self.property_class.element_property(
                                position_mouse,
                                1)  # Activar propiedad elemento
                            if self.property_class.elem_selected:
                                self.property_class.name_element.buffer = \
                                    [char for char in self.property_class.elem_selected]
                            # Aca se le pone al buffer el texto del elemento seleccionado
                            for container in self.property_class.elementos[
                                    'containers']:  #Acciones de ingreso de texto
                                if container.selected:
                                    for caja in container.cajas:
                                        if caja.tag == self.property_class.elem_selected:
                                            self.property_class.box_field1.buffer = [
                                                char
                                                for char in str(caja.alpha)
                                            ]  # se le pone a los buffers los valores de los elementos seleccionados
                                            self.property_class.box_field2.buffer = [
                                                char
                                                for char in str(caja.betha)
                                            ]
                                    for knn_ind in container.knn:
                                        for col in knn_ind.cols:
                                            for caja in col:
                                                if caja.tag == self.property_class.elem_selected:
                                                    self.property_class.box_field1.buffer = \
                                                        [char for char in str(caja.alpha)]
                                                    self.property_class.box_field2.buffer = \
                                                        [char for char in str(caja.betha)]
                                    for stand_ind in container.stand:
                                        if stand_ind.tag == self.property_class.elem_selected:
                                            self.property_class.box_field1.buffer = [
                                                char for char in str(
                                                    stand_ind.alpha)
                                            ]
                                            self.property_class.box_field2.buffer = [
                                                char for char in str(
                                                    stand_ind.betha)
                                            ]
                                    for kdn in container.kdn:
                                        if kdn.tag == self.property_class.elem_selected:
                                            self.property_class.box_field1.buffer = [
                                                char for char in str(kdn.alpha)
                                            ]
                                            self.property_class.box_field2.buffer = [
                                                char for char in str(kdn.betha)
                                            ]
                        self.property_class.list_box_systems.consult_position(
                            position_mouse)
                        if self.property_class.add_rect.collidepoint(position_mouse) \
                                and self.property_class.cont < 14:  # Agregar pestañas si son menos de 14
                            self.property_class.add_container()
                        if self.property_class.min_rect.collidepoint(
                                position_mouse):
                            self.property_class.delete_container(
                                position_mouse
                            )  # Verificar si alguna pestaña se cierra
                        self.property_class.select_container(
                            position_mouse,
                            self.screen_form)  # Seleccionar pestaña
                        if not self.property_class.show_msg:
                            self.property_class.check_actions(
                                position_mouse)  # verifica acciones
                        if not self.property_class.show_msg2:
                            self.property_class.check_actions(
                                position_mouse)  # verifica acciones

                        self.property_class.close_elements(
                            position_mouse)  # Cerrar elementos
                        self.property_class.add_red_elements(position_mouse)
                        for container in self.property_class.elementos[
                                'containers']:
                            container.list_box.scroll.action_bar(
                                position_mouse)
                        self.property_class.list_box_systems.scroll.action_bar(
                            position_mouse)
                        if self.property_class.show_msg:  # Si La ventana de mensajes esta disponible
                            if self.property_class.mensaje.accept.recta.collidepoint(
                                    position_mouse):
                                self.property_class.show_msg = False
                        if self.property_class.show_msg2:  # Si La ventana de mensajes esta disponible
                            if self.property_class.mensaje2.accept.recta.collidepoint(
                                    position_mouse):
                                self.property_class.actions = [0] * 9
                                self.property_class.show_msg2 = False
                        if self.property_class.line_delete:
                            for container in self.property_class.elementos[
                                    'containers']:
                                if container.selected:
                                    for conexion in container.conections:
                                        if conexion.elem1 == self.property_class.line_element.elem1 and conexion.elem2\
                                                == self.property_class.line_element.elem2:
                                            container.conections.remove(
                                                conexion)
                                            for nodo in container.nodos:
                                                nodo.connected = False
                                            for key in container.keys:  # Recorre nodos conectados
                                                # Busca los terminales de la conexion eliminada y los retira de algun nodo
                                                if conexion.elem1 in container.nodos_sistema[key] and \
                                                        conexion.elem2 in container.nodos_sistema[key]:
                                                    container.nodos_sistema[
                                                        key].remove(
                                                            conexion.elem1)
                                                    container.nodos_sistema[
                                                        key].remove(
                                                            conexion.elem2)

                                            self.property_class.line_element = None
                                            self.property_class.line_delete = False
                                            break

                        if self.property_class.connecting:  # Si se encuentra la linea de dibujo activa se pueden adicionar elementos a la conexion
                            self.property_class.duple_conection.append([
                                self.property_class.init_pos,
                                self.property_class.end_line
                            ])  # Todos los puntos de una conexion
                            self.property_class.points_conection.extend(
                                self.property_class.build_rect_points(
                                    self.property_class.duple_conection[-1]))
                            if self.property_class.end_line != self.property_class.duple_conection[
                                    0][0]:
                                self.property_class.init_pos = self.property_class.end_line
                                for container in self.property_class.elementos[
                                        'containers']:
                                    if container.selected:
                                        for nodo in container.nodos:
                                            if nodo.rect.collidepoint(
                                                    self.property_class.
                                                    end_line):
                                                self.property_class.hold_line = False  # Deja de dibujar la linea
                                                self.property_class.line_able = False  # Deja de habilitar linea
                                                self.property_class.connecting = False  # Deja de conectar
                                                self.property_class.elem2 = nodo  # Elemento final de la conexion
                                                conexion = Conexion(
                                                    self.property_class.
                                                    duple_conection,
                                                    self.property_class.elem1,
                                                    self.property_class.elem2,
                                                    self.property_class.
                                                    points_conection)
                                                container.conections.add(
                                                    conexion)
                                                self.property_class.duple_conection = []
                                                self.property_class.points_conection = []
                                                # Verificar a que nodo del sistema van los nodos fisicos del objeto
                                                container.check_node(
                                                    self.property_class.elem1,
                                                    self.property_class.elem2)

                            else:
                                self.property_class.duple_conection.pop()
                        if self.property_class.actions[3]:  # Eliminar elemento
                            self.property_class.delete_element(position_mouse)
                        if self.property_class.actions[5]:  # importa modulo
                            if self.property_class.list_box_modules.accept2.recta.collidepoint(
                                    position_mouse):
                                self.property_class.draw_module = True
                                self.property_class.elem_modulo = self.property_class.list_box_modules.list_items[
                                    self.property_class.list_box_modules.
                                    conten_actual - 1]
                        """if self.property_class.rect_up.collidepoint(position_mouse):
                            self.property_class.scroll()"""
                        if self.property_class.line_able:  # Permitir dibujar linea
                            self.property_class.hold_line = True
                        if self.property_class.drawing:  # Poner elemento
                            self.property_class.put_element()
                        if self.property_class.moving and self.property_class.move_inside:  # Redesplazar elemento
                            self.property_class.repos_element()
                        if self.property_class.check.recta.collidepoint(
                                position_mouse):  # Para rotar cajitas
                            for container in self.property_class.elementos[
                                    'containers']:
                                if container.selected:
                                    for caja in container.cajas:
                                        if caja.tag == self.property_class.elem_selected:
                                            conectado = True
                                            for nodo in caja.nodos:
                                                if nodo.connected:
                                                    conectado = False
                                            if conectado:
                                                caja.orientation = not caja.orientation
                                                self.property_class.check.push = caja.orientation
                                                for nodo in caja.nodos:
                                                    container.nodos.remove(
                                                        nodo)
                                                caja.calc_nodes()
                                                for nodo in caja.nodos:
                                                    container.nodos.add(nodo)
                                            else:
                                                self.property_class.show_msg = True
                                                self.property_class.mensaje.text = 'El elemento debe estar desconectado'
                    elif pygame.mouse.get_pressed(
                    )[2] and self.property_class.modulos:  # Boton derecho
                        self.property_class.element_property(position_mouse)
                elif keys[K_ESCAPE]:  # Acciones al presionar tecla escape
                    position_mouse = self.property_class.cancel()
                    self.property_class.close_elements((0, 0), force=True)
                    self.property_class.box_field1.active = False
                    self.property_class.box_field2.active = False
                manager.process_events(event)
                if event.type == pygame.USEREVENT:
                    if event.user_type == pygame_gui.UI_BUTTON_PRESSED:
                        if event.ui_element == hello_button:
                            print('Hello World!')

            manager.update(time_delta)

            if timer != 0:  # Incremento del timer
                timer += dt
                if timer >= 0.5:  # Reinicio del timer
                    timer = 0
            abs_position = pygame.mouse.get_pos()
            self.screen_form.fill(SEMIWHITE2)
            self.property_class.draw_containers(self.screen_form)
            self.property_class.draw_on_screen(self.screen_form, abs_position,
                                               position_mouse)
            self.property_class.exec_actions(
                self.screen_form, abs_position,
                position_mouse)  # Ejecutar acciones: Mover, borrar...
            if self.property_class.actions[6] or self.property_class.elem_proper or self.property_class.config_bit \
                    or self.property_class.time_play or self.property_class.time_plot:  # Escribir nombre de pestañas
                self.property_class.draw_text(self.screen_form)
                self.property_class.draw = True
            if self.property_class.hold_line:  # Dibujando linea en caliente
                self.property_class.draw_line(self.screen_form)
            if self.property_class.element_moved != None:  # Mover elementos
                self.property_class.move_element(self.screen_form,
                                                 abs_position)
                self.property_class.moving = True
            if self.property_class.show_msg:
                self.property_class.mensaje.draw(self.screen_form)
                if self.property_class.mensaje.accept.recta.collidepoint(
                        abs_position):
                    self.property_class.mensaje.accept.over = True
                else:
                    self.property_class.mensaje.accept.over = False
            if self.property_class.show_msg2:
                self.property_class.mensaje2.draw(self.screen_form)
                if self.property_class.mensaje2.accept.recta.collidepoint(
                        abs_position):
                    self.property_class.mensaje2.accept.over = True
                else:
                    self.property_class.mensaje2.accept.over = False
            self.screen_form.blit(self.logo, (20, 10))
            self.screen_form.blit(self.font.render('REL-Imp', True, (0, 0, 0)),
                                  (550, 20))
            self.screen_form.blit(
                self.font_2.render(
                    'Plataforma para la identificación de componentes críticos',
                    True, (0, 0, 0)), (550, 65))
            #self.screen_form.blit(self.font_2.render('medida de la importancia', True, (0, 0, 0)), (30, 95))
            self.screen_form.blit(
                self.font_3.render('Editando sistema:', True, (0, 0, 0)),
                (760, 570))
            self.screen_form.blit(
                self.font_3.render(self.property_class.cont_selected.name,
                                   True, (0, 0, 0)), (870, 570))
            self.screen_form.blit(
                self.font_2.render('Sistemas', True, (0, 0, 0)), (50, 345))
            self.clock.tick(60)
            dt = self.clock.tick(30) / 1000  # Delta del timer
            #manager.draw_ui(self.screen_form)
            pygame.display.update()
示例#21
0
    def pause_menu(self):
        manager = pgui.UIManager(self.screen_rect.size)
        bg = pg.Surface(self.screen_rect.size)
        bg.fill(pg.Color('#000000'))

        font = pg.font.Font(None, 150)
        pause_text = font.render("Game Paused", True, pg.Color('#FF0000'))
        pt_rect = pause_text.get_rect()
        text_x = (self.wind_width / 2) - (pt_rect.width / 2)
        text_y = 400

        # Buttons
        btn_width = 200
        btn_height = 50
        btn_x = (self.wind_width / 2) - (btn_width / 2)
        # Starting y-coordinate for the buttons so that there is room for the header
        btn_y_buffer = text_y + pt_rect.height + 200

        btn_continue = pgui.elements.UIButton(
            relative_rect=pg.Rect(
                (btn_x, btn_y_buffer),
                (btn_width, btn_height)
            ),
            text='Continue',
            manager=manager
        )
        btn_y_buffer += btn_height + 10

        btn_main_menu = pgui.elements.UIButton(
            relative_rect=pg.Rect(
                (btn_x, btn_y_buffer),
                (btn_width, btn_height)
            ),
            text='Main Menu',
            manager=manager
        )
        btn_y_buffer += btn_height + 10

        btn_quit = pgui.elements.UIButton(
            relative_rect=pg.Rect(
                (btn_x, btn_y_buffer),
                (btn_width, btn_height)
            ),
            text='Quit Game',
            manager=manager
        )

        ui_clock = pg.time.Clock()
        while True:
            time_delta = ui_clock.tick(self.fps)/1000.0
            # Event loop
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    self.state = GameState.EXIT
                    return
                if event.type == pg.USEREVENT:
                    if event.user_type == pgui.UI_BUTTON_PRESSED:
                        if event.ui_element == btn_continue:
                            self.state = GameState.PLAYING
                            return
                        elif event.ui_element == btn_main_menu:
                            self.state = GameState.TITLE
                            return
                        elif event.ui_element == btn_quit:
                            self.state = GameState.EXIT
                            return
                manager.process_events(event)
            manager.update(time_delta)

            # Screen updates
            self.window.blit(bg, (0, 0))
            self.window.blit(pause_text, (text_x, text_y))

            manager.draw_ui(self.window)

            pg.display.update()
示例#22
0
from algorithms_view.sutherland_hodgman_view import SutherlandHodgmanView
from algorithms_view.transformation_view import TransformationView
from algorithms_view.sweep_line_view import SweepLineView
from algorithms_view.linear_transformation_view import LinearTransformationView

# colors
BLACK = (0, 0, 0)

# screen dimension
WIDTH = 800
HEIGHT = 600

pg.init()
SURFACE = pg.display.set_mode((WIDTH, HEIGHT))
Renderer(SURFACE)
gui_manager = pg_gui.UIManager((WIDTH, HEIGHT))

# windows list
windows_drop_down_menu_list = [
    'Convex Hull', 'Line Intersection', 'Minkowski Sum', 'Orientation',
    'Polygon Clipping', 'Sweep Line', 'Transformation', 'Linear Transformation'
]

windows_list = [
    ConvexHullView(gui_manager),
    LineIntersectionView(gui_manager),
    MinkowskiSumView(gui_manager),
    OrientationView(gui_manager),
    SutherlandHodgmanView(gui_manager),
    SweepLineView(gui_manager),
    TransformationView(gui_manager),
示例#23
0
    def game_over(self):
        manager = pgui.UIManager(self.screen_rect.size)
        bg = pg.Surface(self.screen_rect.size)
        bg.fill(pg.Color('#000000'))
        bg.set_alpha(100)

        font = pg.font.Font(None, 150)
        over_text = font.render('Game Over', True, pg.Color('#FF0000'))
        ot_rect = over_text.get_rect()
        text_x = (self.wind_width / 2) - (ot_rect.width / 2)
        text_y = 400

        # Buttons
        btn_width = 200
        btn_height = 50
        btn_x = (self.wind_width / 2) - (btn_width / 2)
        # Starting y-coordinate for the buttons so that there is room for the header
        btn_y_buffer = text_y + ot_rect.height + 200

        btn_play_again = pgui.elements.UIButton(
            relative_rect=pg.Rect(
                (btn_x, btn_y_buffer),
                (btn_width, btn_height)
            ),
            text='Play Again?',
            manager=manager
        )
        btn_y_buffer += btn_height + 10

        btn_exit = pgui.elements.UIButton(
            relative_rect=pg.Rect(
                (btn_x, btn_y_buffer),
                (btn_width, btn_height)
            ),
            text='Main Menu',
            manager=manager
        )

        self.window.blit(bg, (0, 0))
        self.window.blit(over_text, (text_x, text_y))

        ui_clock = pg.time.Clock()
        while True:
            time_delta = ui_clock.tick(self.fps)/1000.0
            # Event loop
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    self.state = GameState.EXIT
                    return
                if event.type == pg.USEREVENT:
                    if event.user_type == pgui.UI_BUTTON_PRESSED:
                        if event.ui_element == btn_play_again:
                            self.state = GameState.NEWGAME
                            return
                        elif event.ui_element == btn_exit:
                            self.state = GameState.TITLE
                            return
                manager.process_events(event)
            manager.update(time_delta)

            # Screen updates
            manager.draw_ui(self.window)

            pg.display.update()
示例#24
0
surface_color = white

display_size = game_settings.display_size
game_size = game_settings.game_size
workstation_size = game_settings.workstation_size

radius = game_settings.scale * 7
width = game_settings.asset_size[0]
height = game_settings.asset_size[1]
sides_width = 1
gap = 2
num_columns = int(game_size[0] / width)
num_rows = int(game_size[1] / height / (3 / 4))

gameBackground = pygame.display.set_mode(display_size)
manager = pygame_gui.UIManager(display_size)

assets_grass_path = './hexagon-pack/PNG/Tiles/Terrain/Grass/'
assets_dirt_path = './hexagon-pack/PNG/Tiles/Terrain/Dirt/'

green_land = [
    pygame.image.load(assets_grass_path + 'grass_05.png'),
]

green_selected_land = [
    pygame.image.load(assets_grass_path + 'grass_selection.png'),
    pygame.image.load(assets_grass_path + 'grass_06.png'),
    pygame.image.load(assets_grass_path + 'grass_07.png'),
    pygame.image.load(assets_grass_path + 'grass_08.png'),
    pygame.image.load(assets_grass_path + 'grass_09.png')
]
示例#25
0
    def __init__(self, screen_size, state):
        self.state = state
        self._manager = pygame_gui.UIManager(screen_size, 'theme.json')
        screen_width, screen_height = screen_size
        menu_width, menu_height = MENU_SIZE
        self.ui_window = pygame_gui.elements.ui_window.UIWindow(
            rect=pygame.Rect(
                (screen_width - menu_width, screen_height - menu_height),
                (menu_width, menu_height)),
            manager=self._manager)

        window_container = self.ui_window.get_container()
        start_rect = pygame.Rect((0, 0), (50, 30))
        self.start_button = pygame_gui.elements.UIButton(
            relative_rect=start_rect,
            text='Start',
            manager=self._manager,
            container=window_container)

        reset_rect = pygame.Rect((start_rect.right, 0), (50, 30))
        self.reset_button = pygame_gui.elements.UIButton(
            relative_rect=reset_rect,
            text='Reset',
            manager=self._manager,
            container=window_container)

        alg_label_rect = pygame.Rect((0, 0), (88, 20))
        alg_label_rect.centery = reset_rect.bottom + 20
        pygame_gui.elements.UILabel(
            text='Algorithm: ',
            relative_rect=alg_label_rect,
            container=window_container,
            manager=self._manager
        )

        alg_rect = pygame.Rect((95, reset_rect.bottom + 5), (50, 30))

        self.algorithm_drop_down = pygame_gui.elements.ui_drop_down_menu.UIDropDownMenu(
            relative_rect=alg_rect,
            starting_option=Algorithms.BFS.name,
            options_list=[Algorithms.BFS.name, Algorithms.DFS.name],
            manager=self._manager,
            container=window_container,
        )

        tile_label_rect = pygame.Rect((0, 0), (48, 20))
        tile_label_rect.centery = alg_rect.bottom + 20
        pygame_gui.elements.UILabel(
            text='Tile: ',
            relative_rect=tile_label_rect,
            container=window_container,
            manager=self._manager
        )

        tile_rect = pygame.Rect((95, alg_rect.bottom+5), (65, 30))
        self.tile_drop_down = pygame_gui.elements.ui_drop_down_menu.UIDropDownMenu(
            relative_rect=tile_rect,
            starting_option=Locations.WALL.name,
            options_list=[Locations.WALL.name,
                          Locations.START.name, Locations.END.name],
            manager=self._manager,
            container=window_container)

        save_btn_rect = pygame.Rect((0, tile_rect.bottom+5), (80, 30))
        self.save_map_button = pygame_gui.elements.UIButton(
            relative_rect=save_btn_rect,
            text='Save Map',
            manager=self._manager,
            container=window_container)

        load_btn_rect = pygame.Rect(
            (save_btn_rect.right, tile_rect.bottom+5), (80, 30))
        self.load_map_button = pygame_gui.elements.UIButton(
            relative_rect=load_btn_rect,
            text='Load Map',
            manager=self._manager,
            container=window_container)

        map_drop_down_rect = pygame.Rect((0, load_btn_rect.bottom), (80, 30))
        self.map_drop_down = pygame_gui.elements.UIDropDownMenu(
            relative_rect=map_drop_down_rect,
            starting_option='Map 0',
            options_list=['Map 0', 'Map 1', 'Map 2'],
            manager=self._manager,
            container=window_container)

        grid_rect = pygame.Rect((0, map_drop_down_rect.bottom + 5), (40, 0))
        self.grid_text_entry = pygame_gui.elements.UITextEntryLine(
            relative_rect=grid_rect,
            manager=self._manager,
            container=self.ui_window
        )
        self.grid_text_entry.set_allowed_characters('numbers')
        self.grid_text_entry.set_text_length_limit(3)

        grid_button_rect = pygame.Rect(
            (grid_rect.right+5, map_drop_down_rect.bottom + 5),
            (75, 30))
        self.grid_button = pygame_gui.elements.UIButton(
            relative_rect=grid_button_rect,
            text='Set Grid',
            manager=self._manager,
            container=window_container)

        speed_slider_rect = pygame.Rect(
            (0, grid_button_rect.bottom),
            (165, 20))
        self.speed_slider = pygame_gui.elements.UIHorizontalSlider(
            relative_rect=speed_slider_rect,
            start_value=50,
            value_range=[1, 100],
            manager=self._manager,
            container=window_container
        )

        # Doesen't let the user click the grid if they're clicking on the menu
        self.blocking = False
示例#26
0
def main():
    pygame.init()

    pygame.camera.init()
    cam_list = pygame.camera.list_cameras()
    cam = None
    if cam_list:
        cam = pygame.camera.Camera(cam_list[0], (640, 480))
        cam.start()

    display_surf = pygame.display.set_mode((640,480))
    pygame.display.set_caption("myAvatar")

    consolas_font = pygame.font.SysFont('Consolas', 20)
    title_font = pygame.font.SysFont('Consolas', 40)


    #Initializing UI Managers for each state in the application
    main_menu = pygame_gui.UIManager((640,480))
    take_picture = pygame_gui.UIManager((640,540))
    view_prev_models = pygame_gui.UIManager((640,480))

    #Initializing UI Elements for each UI Manager
    picture_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((195,150), (250,60)), text="Take Picture", manager=main_menu)
    previous_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((195,210), (250,60)), text="View Previous Models", manager=main_menu)
    exit_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((195,270), (250,60)), text="Exit", manager=main_menu)

    takepicture_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((0,480), (213,60)), text="Take Picture", manager=take_picture)
    rendermodel_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((213,480), (213,60)), text="Render Model", manager=take_picture)
    picture_back_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((426,480), (213,60)), text="Back", manager=take_picture)

    rendermodel_button.disable()

    pic_text = consolas_font.render("Position face within green box.", True, (255,255,255))
    text_rect = pic_text.get_rect()
    text_rect.center = (315,380)

    obj_loading = None
    file_dialog = None

    mode = "main_menu"

    clock = pygame.time.Clock()

    is_running = True
    error_loading = False

    #take_picture variables
    picture_taken = False
    currPicture = None

    title_text = title_font.render("myAvatar", True, (0,0,0))
    title_rect = title_text.get_rect()
    title_rect.center = (320,50)

    while is_running:
        time_delta = clock.tick(60)/1000.0

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                is_running = False
            if event.type == pygame.USEREVENT:
                if event.user_type == pygame_gui.UI_BUTTON_PRESSED:
                    #main_menu
                    if event.ui_element == picture_button:
                        mode = "take_picture"
                        display_surf = pygame.display.set_mode((640,540))
                    if event.ui_element == previous_button:
                        mode = "view_prev_models"
                        file_dialog = pygame_gui.windows.UIFileDialog(pygame.Rect((60,60), (520, 300)), view_prev_models, window_title="Select a .OBJ...", initial_file_path='model_output', allow_existing_files_only=True)
                    if event.ui_element == exit_button:
                        is_running = False
                    #take_picture
                    if event.ui_element == takepicture_button:
                        picture_taken = not picture_taken
                        if picture_taken:
                            takepicture_button.set_text("Retake Picture")
                            rendermodel_button.enable()
                        else:
                            takepicture_button.set_text("Take Picture")
                            rendermodel_button.disable()
                    if event.ui_element == rendermodel_button:
                        pygame.image.save(currPicture, 'userphoto/userinput.jpg')
                        cropImage()
                        obj_path = generateModel('userphoto/userinput_cropped.jpg')
                        view_obj(obj_path, display_surf)
                    if event.ui_element == picture_back_button:
                        mode = "main_menu"
                        picture_taken = False
                        currPicture = None
                        rendermodel_button.disable()
                        takepicture_button.set_text("Take Picture")
                        display_surf = pygame.display.set_mode((640,480))

                if event.user_type == pygame_gui.UI_WINDOW_CLOSE:
                    if event.ui_element == file_dialog:
                        if not error_loading:
                            mode = "main_menu"
                        file_dialog.kill()
                    if event.ui_element == obj_loading:
                        if error_loading:
                            file_dialog.kill()
                            file_dialog = pygame_gui.windows.UIFileDialog(pygame.Rect((60,60), (520, 300)), view_prev_models, window_title="Select a .OBJ...", initial_file_path='gui_models', allow_existing_files_only=True)
                            error_loading = False
                        obj_loading.kill()
                if event.user_type == pygame_gui.UI_FILE_DIALOG_PATH_PICKED:
                    if event.ui_element == file_dialog:
                        tmp = event.text.split('.')
                        if tmp[len(tmp) - 1] != 'obj':
                            obj_loading = pygame_gui.windows.UIMessageWindow(pygame.Rect((60,60), (520, 170)), "Error! Selected file is not a .obj!", view_prev_models)
                            error_loading = True
                        else:
                            file_arr = event.text.split('\\')
                            model_loc = file_arr[len(file_arr) - 2] + '/' + file_arr[len(file_arr) - 1]
                            view_obj(model_loc, display_surf)
            if mode == "main_menu":
                main_menu.update(time_delta)
            elif mode == "take_picture":
                take_picture.update(time_delta)
            elif mode == "view_prev_models":
                view_prev_models.update(time_delta)

                
        display_surf.fill((228,228,228))
        if mode == "main_menu":
            display_surf.blit(title_text, title_rect)
            main_menu.process_events(event)
            #main_menu.update(time_delta)
            main_menu.draw_ui(display_surf)
        elif mode == "view_prev_models":
            view_prev_models.process_events(event)
            #view_prev_models.update(time_delta)
            view_prev_models.draw_ui(display_surf)
        elif mode == "take_picture":
            take_picture.process_events(event)
            if cam is not None:
                if not picture_taken:
                    image = cam.get_image()
                    currPicture = image
                    display_surf.blit(image, (0, 0))
                    display_surf.blit(pic_text, text_rect)
                    pygame.draw.rect(display_surf, (0,255,0), pygame.Rect((190,110), (256,256)), 2)
                else:
                    display_surf.blit(currPicture, (0,0))
            #main_menu.update(time_delta)
            take_picture.draw_ui(display_surf)
    
        pygame.display.update()
示例#27
0
import requests
import pprint
from dotenv import load_dotenv
import convert

path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(path):
    load_dotenv(path)

    APP_ID = os.environ.get('APP_ID')
    APP_ID2 = os.environ.get('APP_ID2')
WIDTH, HEIGHT = 600, 450
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
h, w = GetSystemMetrics(1), GetSystemMetrics(0)
manager = pygame_gui.UIManager((WIDTH, HEIGHT))

user_input = input('Введите долготу и широту '
                   '(по умолчанию 44.559173,48.527201): ')
coords = '44.559173,48.527201' \
    if not user_input else user_input
zoom_map = 18
type_m = 'map'
available_type = ['map', 'sat', 'skl', 'trf']

entry = pygame_gui.elements.UITextEntryLine(relative_rect=pygame.Rect(
    (0, 0), (100, 30)),
                                            manager=manager)
clear_metka = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((100, 0),
                                                                     (50, 30)),
                                           manager=manager,
示例#28
0
    def __init__(self, screen_w, screen_h):
        self.__screen_w = screen_w
        self.__screen_h = screen_h

        self.__grid_w = None
        self.__grid_h = None

        self.__grid_centered_panel_pos_x = None
        self.__grid_centered_panel_pos_y = None

        ###########################################################
        #                  pygame Initialization
        ###########################################################

        # Initialize pygame display
        pygame.init()
        pygame.display.set_caption("Automated Warehouse Planner")

        # Create pygame surfaces
        self.__window_surface = pygame.display.set_mode(
            (self.__screen_w, self.__screen_h))
        self.__background_surface = pygame.Surface(
            (self.__screen_w, self.__screen_h))
        self.__centered_grid_surface = None

        ###########################################################
        #                pygame_gui Initialization
        ###########################################################

        # Create a pygame clock to track time
        self.__clock = pygame.time.Clock()

        # Create pygame_gui manager
        self.__ui_manager = pygame_gui.UIManager(
            (self.__screen_w, self.__screen_h),
            pygame_gui.PackageResource(package='data.themes',
                                       resource='test_theme2.json'))
        # Load Fonts
        self.__ui_manager.preload_fonts([{
            'name': 'fira_code',
            'point_size': 10,
            'style': 'bold'
        }, {
            'name': 'fira_code',
            'point_size': 10,
            'style': 'regular'
        }, {
            'name': 'fira_code',
            'point_size': 10,
            'style': 'italic'
        }, {
            'name': 'fira_code',
            'point_size': 14,
            'style': 'italic'
        }, {
            'name': 'fira_code',
            'point_size': 14,
            'style': 'bold'
        }])

        # Declare panels
        self.__grid_main_panel = None
        self.__grid_centered_panel = None
        self.__info_main_panel = None
        self.__edit_main_panel = None

        # Define grid objects
        self.__buttons_list = None
        self.__selected_button_id = None
        self.sizes = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
        self.cell_sizes = ['50', '60', '70', '80', '90']

        # Define info objects

        # Define UI objects
        self.num_rows = 4
        self.num_cols = 4
        self.cell_size = 70
        self.rows_drop_down = None
        self.cols_drop_down = None
        self.size_drop_down = None
        self.info_text_box = None

        ###########################################################
        #                 Finalize Initialization
        ###########################################################

        # Declare grid
        self.__grid = None

        # Create screen and prepare to run
        self.create_ui()
        self.running = True
示例#29
0
camera = False # Change to True to use camera instead of local file
file_name = 'video_2.mp4' # If using local file, location of the file
start_frame_file = 150 # If using local file, frame to start the video at
end_frame_file = 2000 # If using local file, frame to stop the video at

pygame.init()

pygame.display.set_caption('High Ping')
window_surface = pygame.display.set_mode((800, 600))

login_screen_background = pygame.Surface((800, 600))
login_screen_background.fill(pygame.Color('#343a40'))
room_screen_background = pygame.Surface((800, 600))
room_screen_background.fill(pygame.Color('#ffffff'))

login_screen_manager = pygame_gui.UIManager((800, 600), 'theme.json')
room_screen_manager = pygame_gui.UIManager((800, 600), 'theme.json')

#         Login screen UI         #
#   top padding
height_top = 220

high_ping_label = pygame_gui.elements.UILabel(relative_rect=pygame.Rect((300, height_top - 130), (200, 40)),
                                              text="High Ping",
                                              object_id="high_ping",
                                              manager=login_screen_manager)

welcome_label = pygame_gui.elements.UILabel(relative_rect=pygame.Rect((300, height_top - 90), (200, 40)),
                                            text="Welcome back!",
                                            object_id="welcome",
                                            manager=login_screen_manager)
示例#30
0
def gameloop():
    #pygame.mixer.music.load("assets/cry.mp3")
    #pygame.mixer.music.play(2)

    ##creating the classes (background, game manager, uimanager, player)
    bg = Background()
    player = Player()
    objects = [
        Toy(60, 220),
        Pod(300, 300),
        Pod(450, 300),
        Pod(300, 150),
        Pod(450, 150),
        Water(60, 30),
        Food(60, 130)
    ]
    gamemanager = GameManager(window_surface)
    uimanager = pygame_gui.UIManager((778, 633))
    end_manager = pygame_gui.UIManager((778, 633))

    ## create the ui for the game in motion
    score = gamemanager.score
    label = pygame_gui.elements.UILabel(
        relative_rect=pygame.Rect((678, 0), (100, 25)),
        text='Score: {}'.format(gamemanager.score),
        manager=uimanager)

    playeritem = pygame_gui.elements.UILabel(
        relative_rect=pygame.Rect((0, 0), (200, 25)),
        text='you are carrying: {}'.format(player.item),
        manager=uimanager)

    ## UI for the end screen

    clock = pygame.time.Clock()
    is_running = True

    gamemanager.receive_baby()

    #program loop
    while is_running:
        aliens = gamemanager.get_babies()

        time_delta = clock.tick(60) / 1000.0
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                is_running = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                if (pygame.mouse.get_pressed() == (0, 0, 1)):
                    player.deliver = True
                    target = pygame.mouse.get_pos()
                    player.target = target
                else:
                    target = pygame.mouse.get_pos()
                    player.target = target

            uimanager.process_events(event)

        ## checks if there is movement to be made
        if player.target != (player.sprite.rect.top, player.sprite.rect.left):
            player.move()

        ## checks for colisions with the utilities
        for i in objects:
            if player.sprite.rect.colliderect(i.rect):
                if (player.item == "alien" and i.name == "pod"
                        and not i.has_babie):
                    player.item = ""
                    i.has_babie = True
                    i.alien = player.baby
                    aliens[player.baby].show = True
                    aliens[player.baby].sprite.rect = aliens[
                        player.baby].sprite.rect.move(
                            i.rect.left -
                            aliens[player.baby].sprite.rect.left - 11,
                            i.rect.top - aliens[player.baby].sprite.rect.top +
                            20)
                    aliens[player.baby].show = True
                    aliens[player.baby].inpod = True
                elif (player.item != "alien" and i.name != "pod"):
                    player.item = i.name

            if i.name == "pod" and aliens[i.alien] == None:
                i.has_babie = False

        for a in aliens:
            if player.item != "alien" and a != None:
                if player.sprite.rect.colliderect(
                        a.sprite.rect) and not a.inpod:
                    player.item = "alien"
                    player.baby = a.tag
                    a.show = False
                elif player.sprite.rect.colliderect(
                        a.sprite.rect) and a.inpod and a.get_need(
                        ) == player.item:
                    if player.item == "water":
                        a.a_water()
                    if player.item == "food":
                        a.a_eat()
                    if player.item == "toy":
                        a.a_play()
                    player.item = ""
                elif player.sprite.rect.colliderect(
                        a.sprite.rect) and a.inpod and a.get_need() == "sleep":
                    a.a_sleep()
                    player.item = ""
                elif player.sprite.rect.colliderect(
                        a.sprite.rect) and a.timer <= 0 and player.deliver:
                    player.deliver = False
                    gamemanager.deliver_baby(a)

        #updates the ui
        label.set_text("score: {}".format(gamemanager.score))
        playeritem.set_text("you are carrying: {}".format(player.item))
        uimanager.update(time_delta)

        if (gamemanager.update(time_delta) == 0):
            window_surface.blit(bg.image, bg.rect)
            end_loop(gamemanager.score)

        #prints on the screen
        window_surface.blit(bg.image, bg.rect)

        for i in objects:
            window_surface.blit(i.image, i.rect)

        for a in aliens:
            if a != None:
                if a.show:
                    window_surface.blit(a.sprite.image, a.sprite.rect)
                    window_surface.blit(
                        a.text,
                        [a.sprite.rect.left + 10, a.sprite.rect.top + 23])
                    window_surface.blit(
                        a.need, [a.sprite.rect.left, a.sprite.rect.top - 23])

        window_surface.blit(player.sprite.image, player.sprite.rect)
        uimanager.draw_ui(window_surface)

        pygame.display.update()