Example #1
0
 def __init__(self, sd, dead_alert, f_father):
     self.title = CLOCK_TITLE
     Game.__init__(self, sd, dead_alert, f_father)
     self.max_time = 10 * SECOND 
     self.time = self.max_time
     self.redraw_group.add(self.timer)
     set_timer(TIMEEVENT, SECOND)
Example #2
0
 def __exit__(self, extype, exception, traceback):
     # Check exception type
     if extype is SystemExit:
         safe_exit()
     # Compute delta
     delta = self.enter_time + self.arg_ms - time.get_ticks()
     # Handle case delta == 0
     delta += not delta
     # Validate delta with sign of the argument
     delta *= self.arg_ms >= 0
     # Return if no need to wait
     if delta < 0:
         return
     # Prepare timer event
     custom_event = pyg.USEREVENT + 1
     clock = time.Clock()
     pyg.event.get()
     time.set_timer(custom_event, delta)
     # Game loop
     while True:
         for ev in pyg.event.get():
             if ev.type == pyg.QUIT or \
               (ev.type == pyg.KEYDOWN and ev.key == pyg.K_ESCAPE):
                 safe_exit()
             if ev.type in [custom_event, pyg.JOYBUTTONDOWN, pyg.KEYDOWN]:
                 time.set_timer(custom_event, 0)
                 return pyg.event.post(ev)
         clock.tick(FPS)
Example #3
0
 def death(self):
     # self.pause(True)
     # event.post(event.Event(constants.E_DEATH))
     set_timer(constants.E_DEATH, constants.INSPECTION)
     self.game_state.state = 'death'
     self.game_state.lives -= 1
     for i in range(self.pampuch.attr.img_dead.length()):
         self.pampuch.set(image=self.pampuch.attr.img_dead.frames[i][0])
         self.master.update_display()
         time.sleep(3 / constants.FPS)
Example #4
0
    def init_window(self):

        pygame.init()  # Инициализация pygame

        self.screen = pygame.display.set_mode(
            self.win_display)  # Создаем окошко

        pygame.display.set_caption('Tanks')  # название шапки "капчи"

        set_timer(self.TARGET, 2000)
Example #5
0
    def kill(self, drop=True):
        super().kill()

        if drop:
            gun = BonusBullet((self.rect.centerx, self.rect.centery))

            event.post(
                event.Event(CUSTOM_EVENTS['ADD_BONUS_BULLET'],
                            {'particle': gun}))
            pass

        time.set_timer(CUSTOM_EVENTS['ADD_BONUS'], randint(10000, 15000))
Example #6
0
    def _update_state(self) -> bool:

        if self._gameover:
            if self._gameover_over:
                return True  # return true to engine that we're done with the scene
            else:
                self._initGameOverText()
                return False

        if self._hasBegun and not self._timerBegun:
            self._timerBegun = True
            time.set_timer(self._TIMED_POINT_INCREASE_EVENT, 3000)
        if self.apple == None:
            self.apple = self._spawnApple()

        if self._checkAppleCollision():
            self._collectApple()

        selfHit = self._snakeSelfCollide()

        if (self._snake.snake_coords()[0][0] <= 0 and self._currentDir == Direction.LEFT) or \
        (self._snake.snake_coords()[0][0] >= self.CELLS_ACROSS - 1 and self._currentDir == Direction.RIGHT) or \
        (self._snake.snake_coords()[0][1] <= 0 and self._currentDir == Direction.UP) or \
        (self._snake.snake_coords()[0][1] >= self.CELLS_DOWN -1 and self._currentDir == Direction.DOWN) or \
        (selfHit == True):

            self._hitDetected = True
        else:
            if self._currentDir == Direction.UP:
                self._snake.move(Direction.UP)
            elif self._currentDir == Direction.DOWN:
                self._snake.move(Direction.DOWN)
            elif self._currentDir == Direction.LEFT:
                self._snake.move(Direction.LEFT)
            elif self._currentDir == Direction.RIGHT:
                self._snake.move(Direction.RIGHT)
            elif self._currentDir == Direction.NONE:
                pass

        if self._hitDetected:
            time.set_timer(self._TIMED_POINT_INCREASE_EVENT, 0)
            #TODO Instead call gameover script to run and display score and high scores/play again
            self._gameover = True
            self._score_text_rect.center = (
                WINDOW_WIDTH * .49, WINDOW_HEIGHT / 2
            )  # TODO make this more dynamic so the text actually centers regardless of length

        if self._pointTimerExpired and not self._hitDetected:
            self._points += 1
            self._pointTimerExpired = False

        return False  # "state not done"
Example #7
0
 def restart(self):
     # self.restarting = False
     set_timer(constants.E_DEATH, 0)
     if self.game_state.lives >= 0:
         self.game_state.state = 'stopped'
         self.pampuch.reset_image()
         self.pampuch.move_resize(self.pampuch.starting_position, 1)
         self.pampuch.direction = None
         self.pampuch.new_direction = list()
         for m in self.monsters:
             m.move_resize(m.starting_position, 1)
             m.direction = None
             m.direction_old = None
             m.cooldown = 0
         # set_timer(constants.E_GAME_STARTED, constants.INSPECTION)
         return
     self.game_state.state = 'gameover'
Example #8
0
    def run(self):
        threads = [
            Thread(target=self.control_player),
            Thread(target=self.run_aliens),
            Thread(target=self.run_bonus),
            Thread(target=self.run_players),
            Thread(target=self.run_player_bullets),
            Thread(target=self.run_alien_bullets),
        ]

        for thread in threads:
            thread.start()

        time.set_timer(CUSTOM_EVENTS['ADD_ALIEN'], 500)
        self.run_main()

        for thread in threads:
            thread.join()
Example #9
0
 def check_events(self):
     for evt in event.get():
         if evt.type == QUIT:
             self.should_exit = True
             self.running = False
         elif evt.type == CUSTOM_EVENTS['ADD_ALIEN']:
             self.aliens.add(load_aliens(randint(0, 4), randint(0, 8)))
             time.set_timer(CUSTOM_EVENTS['ADD_ALIEN'],
                            randint(5000, 10000))
         elif evt.type == CUSTOM_EVENTS['ADD_PLAYER_BULLET']:
             if len(self.player_bullets) < 2:
                 self.player_bullets.add(evt.particle)
         elif evt.type == CUSTOM_EVENTS['ADD_ALIEN_BULLET']:
             if len(self.alien_bullets) < 6:
                 self.alien_bullets.add(evt.particle)
         elif evt.type == CUSTOM_EVENTS['ADD_BONUS']:
             self.bonus.add(Bonus())
         elif evt.type == CUSTOM_EVENTS['ADD_BONUS_BULLET']:
             self.alien_bullets.add(evt.particle)
    def __init__(self, win):
        self.win = win

        self.satiety_gauge = Gauge(self.win, Gauge.TYPE_HIGH_IS_GOOD,
                                   load_image(images.PLATE_EMOJI),
                                   scale_pair((144, 595)))

        self.hygiene_gauge = Gauge(self.win, Gauge.TYPE_HIGH_IS_GOOD,
                                   load_image(images.SHOWER_EMOJI),
                                   scale_pair((439, 595)))

        self.toilet_gauge = Gauge(self.win, Gauge.TYPE_LOW_IS_GOOD,
                                  load_image(images.TOILET_EMOJI),
                                  scale_pair((748, 595)))

        self.components = [
            self.satiety_gauge, self.hygiene_gauge, self.toilet_gauge
        ]

        self.background = load_image(images.BRICK_WALL_BACKGROUND)
        self.marble = load_image(images.MARBLE)
        self.game_canvas = load_image(images.GAME_CANVAS)

        self.map_tiles = get_tiles()
        self.map_layers = LAYERS
        self.map_matrix = get_map()
        self.current_player_pos = (6, 7)

        self.map_surface = pygame.Surface(self.game_canvas.get_size())

        self.is_player_moving = False
        self.last_player_moving_direction = None

        self.time_event_id = pygame.USEREVENT + 1
        self.walk_event_id = pygame.USEREVENT + 2
        time.set_timer(self.time_event_id, 3000)
        self.clock = time.Clock()

        self.count_eaten_food = 0
        self.spawned_food = []
        self.spawn_food()
Example #11
0
    def _loop(self):
        """T._loop () -> None

        Overrides default _loop() so that it will not stop until
        self._running is false.
        """
        # Emit the tick event every 10 ms.
        PygameTime.set_timer(SIG_TICK, 10)
        delay = PygameTime.delay
        event_get = event.get
        pump = event.pump

        while self._running:
            pump()
            # Get events and distribute them.
            events = event_get()

            if not self.distribute_events(*events):
                return  # QUIT event
            if self.timer > 0:
                delay(1000 / self.timer)
    def _loop (self):
        """T._loop () -> None

        Overrides default _loop() so that it will not stop until
        self._running is false.
        """
        # Emit the tick event every 10 ms.
        PygameTime.set_timer (SIG_TICK, 10)
        delay = PygameTime.delay
        event_get = event.get
        pump = event.pump

        while self._running:
            pump ()
            # Get events and distribute them.
            events = event_get ()

            if not self.distribute_events (*events):
                return # QUIT event
            if self.timer > 0:
                delay (1000 / self.timer)
    def render(self, **args):
        for event in args['events']:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return {'goto': START_SCENE}
                elif event.key == pygame.K_UP:
                    time.set_timer(self.walk_event_id, 400)
                    self.move_player('up')
                elif event.key == pygame.K_RIGHT:
                    time.set_timer(self.walk_event_id, 400)
                    self.move_player('right')
                elif event.key == pygame.K_DOWN:
                    time.set_timer(self.walk_event_id, 400)
                    self.move_player('down')
                elif event.key == pygame.K_LEFT:
                    time.set_timer(self.walk_event_id, 400)
                    self.move_player('left')
                elif event.key == pygame.K_SPACE:
                    self.handle_interaction()
            elif event.type == pygame.KEYUP:
                if event.key in (pygame.K_UP, pygame.K_RIGHT, pygame.K_DOWN,
                                 pygame.K_LEFT):
                    self.stop_player()
            elif event.type == self.time_event_id:
                self.handle_gauges()
            elif event.type == self.walk_event_id:
                self.move_player()

        self.win.blit(self.background, scale_pair((0, 0)))
        self.win.blit(self.marble, scale_pair((110, 24)))
        self.win.blit(self.map_surface, scale_pair((129, 40)))

        for component in self.components:
            component.draw()

        self.draw_map()

        if self.is_game_over():
            return {
                'goto': GAME_OVER_SCENE,
                'more_args': {
                    'clock': self.clock.tick(),
                    'food_eaten': self.count_eaten_food
                }
            }

        return {'goto': GAME_SCENE, 'more_args': args['more_args']}
Example #14
0
from pygame import event, mixer, time
from pygame.locals import *
import classGame

game = classGame.Game()


time.set_timer(USEREVENT, 4444)
time.set_timer(USEREVENT + 1, 44440)


while not game.over:
    for e in event.get():
        print(e.type)
        if e.type == QUIT:
            game.over = True
        if e.type == USEREVENT:
            game.spawnenemy()
        if e.type == MOUSEBUTTONUP:
            if e.button == 3:
                #game.spawnturel(e.pos)
                game.showmenu(e.pos)
            if e.button == 1:
                game.shootall(e.pos)
        if e.type == (USEREVENT + 1):
                print('oda')
                game.spawnModernEnemy()
    game.update()
Example #15
0
def init():
    set_timer(USEREVENT, 100)
Example #16
0
bar2vie100 = pygame.image.load('Barre2vie100.png')
bar2vie75 = pygame.image.load('Barre2vie75.png')
bar2vie50 = pygame.image.load('Barre2vie50.png')
bar2vie25 = pygame.image.load('Barre2vie25.png')
bar2vie0 = pygame.image.load('Barre2vie0.png')

bar2vie100_boss = pygame.image.load('Barre2vie100_boss.png')
bar2vie75_boss = pygame.image.load('Barre2vie75_boss.png')
bar2vie50_boss = pygame.image.load('Barre2vie50_boss.png')
bar2vie25_boss = pygame.image.load('Barre2vie25_boss.png')
bar2vie0_boss = pygame.image.load('Barre2vie0_boss.png')

v1 = [Chauve_souris(5, 500), Chauve_souris(15, 500), Chauve_souris(15, 500), Chauve_souris(15, 500)]
v2 = [Chauve_souris(5, 500),Chauve_souris(5, 500),Chauve_souris(5, 500),Chauve_souris(5, 500),Chauve_souris(5, 500)]
v3 = [Monster_Truck(5, 500),]
set_timer(pygame.USEREVENT, 60)
n_vague = v1

#-----[Fonctions]-----#

def barre2vie(mob):
    """Affiche les pvs du mob au dessus de sa tête"""
    if mob.health == mob.max_health:
        ecran.blit(bar2vie100, (mob.rect.x + 10, mob.rect.y - 20))
    elif mob.health > mob.max_health*0.75:
        ecran.blit(bar2vie75, (mob.rect.x + 10, mob.rect.y - 20))
    elif mob.health > mob.max_health*0.5:
        ecran.blit(bar2vie50, (mob.rect.x + 10, mob.rect.y - 20))
    elif mob.health > mob.max_health*0.25:
        ecran.blit(bar2vie25, (mob.rect.x + 10, mob.rect.y - 20))
    elif mob.health == mob.max_health*0:
Example #17
0
 def _beat(self):
     Game._beat(self)
     self.time = self.max_time
     set_timer(TIMEEVENT, 0)
     set_timer(TIMEEVENT, SECOND)
Example #18
0
 def stop(self):
     set_timer(TIMEEVENT, 0)
Example #19
0
 def play(self):
     set_timer(TIMEEVENT, SECOND/2)
Example #20
0
def main():
    pygame.init()
    screen = pygame.display.set_mode(SCREEN_RESOLUTION)
    clock = Clock()
    set_timer(USEREVENT_EACH_SECOND, 1000)

    font = Font('resources/Arial Rounded Bold.ttf', 14)
    background_color = (0, 0, 0)
    grid = BackgroundGrid(SCREEN_RESOLUTION, Color(20, 20, 20), 32)

    fps_text = FormattedText(font, COLOR_WHITE, "FPS: %i", 0)
    debug_texts = [
        fps_text,
        StaticText(font, COLOR_WHITE, "debug: 2"),
        StaticText(font, COLOR_WHITE, "debug: 3"),
    ]
    debug_window = ListContainer(width=200,
                                 height="fit_contents",
                                 children=debug_texts,
                                 margin=5,
                                 padding=5,
                                 orientation=Orientation.VERTICAL,
                                 style=Style(border_color=COLOR_WHITE))

    left_buttons = [
        button(font, (200, 48), callback=lambda: print("hello"),
               label="click"),
        button(font, (200, 48), callback=lambda: print("hello"),
               label="click"),
        button(font, (200, 48), callback=lambda: print("hello"),
               label="click"),
    ]
    counter = Counter((50, 50),
                      FormattedText(font, COLOR_WHITE, "%i", 0),
                      style=Style(background_color=Color(100, 100, 100)))
    right_buttons = [
        button(font, (200, 32),
               callback=lambda: counter.increment(),
               label="Increment (I)",
               hotkey=pygame.K_i),
        button(font, (200, 32),
               callback=lambda: counter.decrement(),
               label="Decrement (D)",
               hotkey=pygame.K_d),
        checkbox(font, (200, 32),
                 callback=lambda checked: debug_window.set_visible(checked),
                 label="Show debug",
                 checked=debug_window.is_visible()),
        checkbox(font, (200, 32),
                 callback=lambda checked: print("B: %s" % checked),
                 label="B"),
        checkbox(font, (200, 32),
                 callback=lambda checked: print("C: %s" % checked),
                 label="C"),
        checkbox(font, (200, 32),
                 callback=lambda checked: print("D: %s" % checked),
                 label="D"),
        checkbox(font, (200, 32),
                 callback=lambda checked: print("E: %s" % checked),
                 label="E"),
        checkbox(font, (200, 32),
                 callback=lambda checked: print("F: %s" % checked),
                 label="F"),
    ]
    left_menu_bar = ListContainer(width="fit_contents",
                                  height="fill_parent",
                                  children=left_buttons,
                                  margin=5,
                                  padding=5,
                                  orientation=Orientation.VERTICAL,
                                  style=Style(background_color=Color(
                                      150, 150, 255),
                                              border_color=COLOR_WHITE))
    right_menu_bar = ScrollContainer(height=166,
                                     children=right_buttons,
                                     margin=5,
                                     padding=5,
                                     orientation=Orientation.VERTICAL,
                                     style=Style(background_color=Color(
                                         150, 210, 255),
                                                 border_color=COLOR_WHITE))

    text_field = TextArea(font,
                          COLOR_WHITE, (100, 100),
                          padding=5,
                          style=Style(border_color=COLOR_WHITE))

    icon_background = load_and_scale_image('resources/stone_tile.png',
                                           (32, 32))

    grid_children = [
        number_button(font, text_field, "1", pygame.K_1),
        number_button(font, text_field, "2", pygame.K_2),
        number_button(font, text_field, "3", pygame.K_3),
        number_button(font, text_field, "4", pygame.K_4),
        number_button(font, text_field, "5", pygame.K_5),
        number_button(font, text_field, "6", pygame.K_6),
        icon(font, (32, 32), icon_background, "A", pygame.K_a),
        icon(font, (32, 32), icon_background, "B", pygame.K_b),
        icon(font, (32, 32), icon_background, "C", pygame.K_c),
        number_button(font, text_field, "0", pygame.K_0),
        backspace_button(font, text_field)
    ]
    grid_container = GridContainer(children=grid_children,
                                   dimensions=(3, 4),
                                   padding=5,
                                   margin=2,
                                   style=Style(background_color=Color(
                                       150, 130, 100),
                                               border_color=COLOR_WHITE))

    img = image_surface('resources/stone_tile.png', (100, 100))

    hud = ListContainer(
        width=800,
        height=200,
        children=[right_menu_bar, counter, grid_container, text_field, img],
        margin=5,
        padding=5,
        orientation=Orientation.HORIZONTAL,
        style=Style(border_color=COLOR_WHITE,
                    background_color=Color(0, 0, 150)))
    container = AbsolutePosContainer(SCREEN_RESOLUTION,
                                     [(Vector2(5, 5), debug_window),
                                      (Vector2(0, 400), hud)])
    container.set_pos(Vector2(0, 0))

    while True:
        for event in pygame.event.get():
            handle_exit(event)
            if event.type == pygame.MOUSEBUTTONDOWN:
                container.handle_mouse_was_clicked(pygame.mouse.get_pos())
            elif event.type == pygame.MOUSEBUTTONUP:
                container.handle_mouse_was_released()
            elif event.type == pygame.MOUSEMOTION:
                container.handle_mouse_motion(pygame.mouse.get_pos())
            elif event.type == USEREVENT_EACH_SECOND:
                fps_text.format_text(int(clock.get_fps()))
            elif event.type == pygame.KEYDOWN:
                container.handle_key_was_pressed(event.key)
            elif event.type == pygame.KEYUP:
                container.handle_key_was_released(event.key)
        elapsed_time = clock.tick()

        container.update(elapsed_time)

        screen.fill(background_color)
        grid.render(screen)
        container.render(screen)
        pygame.display.flip()
Example #21
0
        rk["x"] <= 0 and 0<=rk["angle"]<=180):
        rk["angle"] = - rk["angle"]
    if (rk["y"] >= screen_height and abs(rk["angle"])>=90) or (
        rk["y"] <= 0 and (abs(rk["angle"])<=90)):
        if rk["angle"] <= 0:
            rk["angle"] = -180 - rk["angle"]
        else:
            rk["angle"] = 180 - rk["angle"]
        

#########################
#     ОСНОВНОЙ ЦИКЛ     #
#########################

running = True
time.set_timer(USEREVENT + 1, milsec_update)

while running:
    for event in pg.event.get():
        #событие завершения
        if event.type == QUIT:
            running = False
        #обновление координат
        if event.type == USEREVENT + 1:
            planet_rotate(planet)
            satellite1 = satellite_move(satellite1)
            satellite2 = satellite_move(satellite2)
            if sat_colission_check(satellite1,satellite2):
                satellite1["da"] = -satellite1["da"]
                satellite2["da"] = -satellite2["da"]
            rocket_move(rocket)
Example #22
0
 def init_game(self):
     """Initializes the game"""
     self.state = GameState.RUNNING
     pgtime.set_timer(OBSTACLE_SPAWN_EVENT, OBSTACLE_SPAWN_RATE_MS)
Example #23
0
from pygame.time import set_timer
from pygame import transform
from pygame import mixer

mixer.pre_init(44100, -16, 3, 512)
mixer.init()

# Параметры экрана
SIZE = [1200, 720]
FPS = 65
GRAVITY_POWER = 1.5
SCORE = 0

# Таймеры
BLINKING_RECT = USEREVENT + 1
set_timer(BLINKING_RECT, 10 * 80)

# Параметры спрайтов
ALL_SPRITES = Group()  # Все спрайты
BULLETS = Group()  # Спрайты пуль
ENEMY_BULLETS = Group()  # Спрайты вражеских пуль
MOBS = Group()  # Спрайты мобов
PLATFORMS = Group()  # Спрайты плаформ
STAIRS = Group()  # Спрайты лестниц
SPIKES = Group()  # Спрайты шипов
BONUS_BALLS = Group()  # Спрайты бонусных шаров
HEAL_CUPSULES = Group()  # Спрайты банок со здоровьем
BOSSES = Group()  # Спрайты боссов

# Пареметры и спрайты игрока
JUMP_POWER = 4
def main():
    '''
    Run the slideshow
    '''

    args = handle_arguments()

    if args.debug:
        args.log_level = 'INFO'
        # 5 seconds is too fast once images are cached: one cannot interupt easily
        args.show_time = 10 * 1000

    # Configure logging
    logging.basicConfig(
        format='%(levelname)s:%(module)s.%(funcName)s:%(message)s',
        level=getattr(logging, args.log_level.upper()))

    # pylint: disable=no-member
    pygame.init()

    # init the pygame dislay (Sloooooow)
    init_display()

    info = display.Info()

    slide_show = Slideshow(gallery_id=args.gallery_id,
                           gallery_url=args.gallery_url,
                           downscale=args.downscale_only,
                           height=info.current_h,
                           width=info.current_w)

    # init fonts
    fonts = init_fonts()

    # Load main display area
    main_surface = pygame.display.get_surface()
    main_surface.fill(pygame.Color('black'))

    center_x = main_surface.get_rect().centerx
    center_y = main_surface.get_rect().centery

    # Display startup message for 5 seconds
    draw_multiline_text(surface=main_surface,
                        text=STARTUP_TEXT,
                        pos=(center_x, center_y),
                        font=fonts['medium'])
    display.flip()
    pygame.time.delay(5000)

    # Start by drawing the first image
    update = draw_image(image_file=BytesIO(slide_show.current()))
    # update = draw_image(image_file=slide_show.current())
    if update:
        display.flip()

    # draw an image at set intervals by sending an event on an interval
    # pylint: disable=no-member
    time.set_timer(pygame.USEREVENT, args.show_time)

    # the event loop
    while 1:

        update = True
        try:
            # pylint: disable=no-member
            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    sys.exit(0)

                # keypresses
                if event.type == pygame.KEYUP:
                    # look for escape key
                    if event.key == pygame.K_ESCAPE:
                        sys.exit(0)

                    # left arrow - display the previous image
                    if event.key == pygame.K_LEFT:
                        # Draw the image
                        update = draw_image(
                            image_file=BytesIO(slide_show.previous()))

                    # right arrow - display the next image
                    if event.key == pygame.K_RIGHT:
                        # Draw the image
                        update = draw_image(
                            image_file=BytesIO(slide_show.next()))

                # image display events
                if event.type == pygame.USEREVENT:
                    # Draw the image
                    update = draw_image(image_file=BytesIO(slide_show.next()))

                # Update the display - sometimes can't find a good image size match
                if update:
                    display.flip()
        except KeyboardInterrupt:
            sys.exit(0)
Example #25
0
def gameloop(
    playerOrder: bool,
    p1Char: str,
    nick1: str,
    p2Char: str,
    nick2: str,
    udp: UDP_P2P,
) -> str:
    # region DocString
    """
    Function that starts the loop for pygame

    ### Arguments
        `playerOrder {bool}`:
            `summary`: true if this host is the first player, false otherwise
        `p1Char {str}`:
            `summary`: the character chosen by this host
        `nick1 {str}`:
            `summary`: the username of this host
        `p2Char {str}`:
            `summary`: the character chosen by the remote player
        `nick2 {str}`:
            `summary`: the username of the remote player
        `udp {UDP_P2P}`:
            `summary`: the udp object

    ### Returns
        `str`: the exit status. It can be 'Lost' if this host lose, 'Quit' if this host closed the window,\n
        'Win' if the remote host lose, 'Quitted' if the remote host closed the window
    """
    # endregion

    global gamestate
    clock = Clock()
    COORDSYNC = USEREVENT + 1
    set_timer(COORDSYNC, 1000)

    # region Screen setup

    screen = set_mode((Game.SIZE[0] + 400, Game.SIZE[1]))
    set_caption(Game.TITLE)
    set_icon(load(Game.ICON_PATH))
    bg = load(Game.BG_PATH).convert_alpha()
    bg = scale(bg, Game.SIZE)

    manager = UIManager((Game.SIZE[0] + 400, Game.SIZE[1]))
    chat = Chat((400, Game.SIZE[1]), manager, udp, nick1)

    # endregion

    all_sprites = Group()

    # region Players setup

    if p1Char == "Ichigo":
        pl = Ichigo(playerOrder, nick1, all_sprites)
    elif p1Char == "Vegeth":
        pl = Vegeth(playerOrder, nick1, all_sprites)

    if p2Char == "Ichigo":
        pl2 = Ichigo(not playerOrder, nick2, all_sprites)
    elif p2Char == "Vegeth":
        pl2 = Vegeth(not playerOrder, nick2, all_sprites)

    # endregion

    rcvT = udp.receptionThread(
        lambda data, addr, time: rcv(pl2, data, addr, time, chat), rcvErr)
    rcvT.start()

    while True:

        dt = clock.tick(Game.FPS) / 1000

        # region Handle window close

        pressed_keys = get_pressed()

        for event in get():
            if event.type == QUIT:
                snd(nick1, "Quit", udp)
                gamestate = "Quit"

            if event.type == COORDSYNC:
                sndCoords(nick1, (pl.rect.x, pl.rect.y), udp)

            manager.process_events(event)

        # endregion

        manager.update(dt)

        # region Handle key press and update sprites

        all_sprites.update(pressed_keys)
        sndKeys(
            nick1,
            (
                pressed_keys[K_LEFT],
                pressed_keys[K_RIGHT],
                pressed_keys[K_UP],
                pressed_keys[K_z],
            ),
            udp,
        )
        if pl.update(pressed_keys):
            snd(nick1, "Lost", udp)
            gamestate = "Lost"

        # endregion

        # region Sprite drawing

        screen.fill(Color.WHITE)
        screen.blit(bg, (0, 0))
        all_sprites.draw(screen)
        pl.draw(screen)
        pl2.draw(screen)
        pl.health.draw(screen)
        pl2.health.draw(screen)

        # endregion

        manager.draw_ui(screen)
        flip()

        if gamestate:
            udp.stopThread()
            quit()
            return gamestate
        elif laser['direction'] == 'down':
            pygame.draw.line(DISPLAYSURF, RED, (laser['x'], laser['y']), (laser['x'], laser['y'] + 20), 2)
        elif laser['direction'] == 'left':
            pygame.draw.line(DISPLAYSURF, RED, (laser['x'], laser['y']), (laser['x'] - 20, laser['y']), 2)


while True:  # the main game loop


    keys = pygame.key.get_pressed()
    if keys[K_LCTRL]:
        TankSpeed = MIN_SPEED

    if keys[K_LSHIFT]:
        TankSpeed = MAX_SPEED
        set_timer(USEREVENT, 1000)  # trigger speed reset

    if keys[K_SPACE]:
        if not firing and len(lasers) < MAXLASERS:
            fire_laser()
            firing = True
    else:
        firing = False

    if keys[K_RIGHT]:
        direction = 'right'
        TankImg = TankImgRight
        move_tank()

    elif keys[K_LEFT]:
        direction = 'left'
Example #27
0
 def update_phase(self):
     '''
     This method update the phase of the game base on the score of
     the player
     '''
     score = self.ui.get_score()
     if score < 40:
         if self.phase < 1:
             self.phase = 1
             set_timer(events.ADD_ENEMY, 300)
     elif score < 60:
         if self.phase < 2:
             self.phase = 2
             self.bg.increase_frame_move()
             set_timer(events.ADD_ENEMY, 200)
     elif score < 100:
         if self.phase < 3:
             self.phase = 3
             self.bg.increase_frame_move()
             set_timer(events.ADD_ENEMY, 250)
     elif score < 120:
         if self.phase < 4:
             self.phase = 4
             self.bg.increase_frame_move()
             set_timer(events.ADD_ENEMY, 150)
     elif score < 160:
         if self.phase < 5:
             self.phase = 5
             self.bg.increase_frame_move()
             set_timer(events.ADD_ENEMY, 200)
     elif score < 180:
         if self.phase < 6:
             self.phase = 6
             self.bg.increase_frame_move()
             set_timer(events.ADD_ENEMY, 100)
     elif score < 220:
         if self.phase < 7:
             self.phase = 7
             self.bg.increase_frame_move()
             set_timer(events.ADD_ENEMY, 150)
     elif score < 240:
         if self.phase < 8:
             self.phase = 8
             self.bg.increase_frame_move()
             set_timer(events.ADD_ENEMY, 50)
     else:
         if self.phase < 9:
             self.phase = 9
             self.bg.increase_frame_move()
             set_timer(events.ADD_ENEMY, 100)
Example #28
0
 def clear(self):
     self.enemies.empty()
     self.phase = 0
     set_timer(events.ADD_ENEMY, 0)