Exemple #1
0
def again(winner, lost, kicked):
    global repeat
    if kicked:
        text = m_font.render("You timed outed!", True, (10, 10, 10))
    elif lost:
        text = m_font.render("Sorry,You lost!", True, (10, 10, 10))
    elif winner != '':
        text = m_font.render(winner, True, (10, 10, 10))
    else:
        text = m_font.render("GAME OVER", True, (10, 10, 10))
    x = screen.get_size()[0] // 2 - text.get_size()[0] // 2
    y = screen.get_size()[1] // 2 - text.get_size()[1] // 2
    text_r = m_font.render('Press "R" key to reload session', True, (0, 0, 0))
    x1 = screen.get_size()[0] // 2 - text_r.get_size()[0] // 2
    y1 = y + text.get_size()[1] + 25

    rep_loop = True
    while rep_loop:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                rep_loop = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    rep_loop = False
                if event.key == pygame.K_r:
                    rep_loop = False
                    repeat = True

        screen.fill((200, 200, 200))
        screen.blit(text, (x, y))
        screen.blit(text_r, (x1, y1))
        pygame.display.flip()
Exemple #2
0
def loop():
    gameobj = GameObject.GameObject()

    while not gameobj.close:
        gameobj.update()
        gameobj.draw()

        pygame.display.update(screenRect)
        clock.tick()
Exemple #3
0
    def start(self):
        run = True
        while run:
            clock.tick(30)
            self.events = pygame.event.get()
            self.keys = pygame.key.get_pressed()
            run = self.isWindowClose()
            self.gamePause()
            if not self.pause:
                self.worlds_generator.action(self.keys, self.events)
            else:
                self.pauseMenu()

        pygame.quit()
        sys.exit()
Exemple #4
0
def menu():
    global screen, clock, Gmode
    buttons = []
    solo = Button('Solo Game', 100, 200, l_font, (0, 0, 0), (100, 255, 100),
                  (16, 128, 16), start)
    buttons.append(
        solo)  #НИ В КОЕМ СЛУЧАЕ НЕ ТРОГАТЬ ПРОБЕЛЫ В ТЕКСТЕ, ВСЕ СЛОМАЕТСЯ
    online = Button('Online       ', 100, 250, l_font, (0, 0, 0),
                    (200, 200, 50), (128, 128, 16), start)
    buttons.append(
        online)  #НИ В КОЕМ СЛУЧАЕ НЕ ТРОГАТЬ ПРОБЕЛЫ В ТЕКСТЕ, ВСЕ СЛОМАЕТСЯ
    aiM = Button('AI mod      ', 100, 300, l_font, (0, 0, 0), (100, 100, 255),
                 (16, 16, 128), start)
    buttons.append(
        aiM)  #НИ В КОЕМ СЛУЧАЕ НЕ ТРОГАТЬ ПРОБЕЛЫ В ТЕКСТЕ, ВСЕ СЛОМАЕТСЯ
    quit = Button('Quit          ', 100, 350, l_font, (0, 0, 0),
                  (255, 100, 100), (128, 16, 16), start)
    buttons.append(
        quit)  #НИ В КОЕМ СЛУЧАЕ НЕ ТРОГАТЬ ПРОБЕЛЫ В ТЕКСТЕ, ВСЕ СЛОМАЕТСЯ
    LoopMenu = True
    while LoopMenu:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                LoopMenu = False
            pos = pygame.mouse.get_pos()
            for button in buttons:
                dist_x = pos[0] - button.button_x
                dist_y = pos[1] - button.button_y
                if 0 <= dist_x <= button.button_w and 0 <= dist_y <= button.button_h:
                    button.is_active = True
                    if event.type == pygame.MOUSEBUTTONDOWN:
                        Gmode = button.run(button.text)
                        LoopMenu = False
                else:
                    button.is_active = False

        screen.blit(poster, (0, 0))
        for button in buttons:
            button.draw()

        pygame.display.flip()
Exemple #5
0
def solo():
    global clock, screen
    bullets, tanks, walls = [], [], []
    spawnpoints = []
    free_spaces = []
    #
    # КАРТЫ МЕНЯТЬ В РУЧНУЮ 1-10 #UPD добавил генератор на вторую карту, меняется всегда.
    #
    #.txt формат. W - walls, P - players, Пробел = Пробел :/
    # Карты 38x20 символов
    with open('TanksRss/Maps/map2.txt') as map:
        lines = map.readlines()
        i = 0
        for line in lines:
            j = 0
            for symb in line:
                if symb == 'W':
                    walls.append(Wall([j * 32, i * 32]))
                elif symb == 'P':
                    spawnpoints.append([j * 32, i * 32])
                elif symb == ' ':
                    free_spaces.append([j * 32, i * 32])
                j += 1
            i += 1
    tank1 = Tank(spawnpoints[0][0],
                 spawnpoints[0][1],
                 800 // 6, (62, 132, 45),
                 32,
                 'Player 1',
                 fire=pygame.K_RETURN)  #ЦВЕТ ТАНКА (62, 132, 45)
    tank2 = Tank(
        spawnpoints[1][0],
        spawnpoints[1][1],
        800 // 6,
        (62, 132, 45),
        32,
        'Player 2',  #ЦВЕТ ТАНКА (62, 132, 45)
        d_right=pygame.K_d,
        d_left=pygame.K_a,
        d_up=pygame.K_w,
        d_down=pygame.K_s)
    tanks += [tank1, tank2]
    box = 0, 0
    cycle = 0
    winner = ''
    game_over = False
    mainloop = True
    while mainloop:
        millis = clock.tick(FPS)
        seconds = millis / 1000
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                mainloop = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    mainloop = False
                    game_over = True
                for tank in tanks:
                    if event.key == tank.fire_key:
                        bullets.append(Bullet(tank))

        pressed = pygame.key.get_pressed()
        for tank in tanks:
            # print(tank.direction)
            # stay = True
            for key in tank.KEY.keys():
                if pressed[key]:
                    tank.changeDirection(tank.KEY[key])
                    tank.is_static = False
                    # stay = False
            # if stay:
            #     tank.is_static = True

        screen.fill((200, 150, 200))
        screen.blit(bg, (0, 0))
        for wall in walls:
            wall.draw()

        for i in range(len(tanks)):
            tanks[i].move(seconds, box, tanks)
            txt = s_font.render(
                f'{tanks[i].name}: {tanks[i].lifes} lifes, {tanks[i].score} points',
                True, (0, 0, 0))
            screen.blit(txt, (5, i * txt.get_size()[1] + 5))
            for j in range(len(walls)):
                if checkCollisions(tanks[i], walls[j], False, True):
                    tanks[i].lifes -= 1
                    del walls[j]
                    break
            for j in range(len(bullets)):
                if checkCollisions(tanks[i], bullets[j], False, False):
                    explosion_sound.play()
                    bullets[j].tank.score += 1
                    tanks[i].lifes -= 1
                    del bullets[j]
                    break
            if tanks[i].lifes <= 0:
                del tanks[i]
                break

        for i in range(len(bullets)):
            bullets[i].move(seconds)
            if bullets[i].lifetime > bullets[i].destroytime:
                del bullets[i]
                break
            for j in range(len(walls)):
                if checkCollisions(bullets[i], walls[j], False, True):
                    bullets[i].lifetime = 10
                    del walls[j]
                    break

        pygame.display.flip()

        if len(tanks) == 0:
            winner = ''
            game_over = True
            mainloop = False
        if len(tanks) == 1:
            win_tank = tanks[0]
            winner = f'Congrats! Score: {win_tank.score}. Winner(-s): {win_tank.name}'
            game_over = True
            mainloop = False

    return game_over, winner, False, False
Exemple #6
0
def aiM():
    global clock, screen
    screen = pygame.display.set_mode((1200, 640))

    rpc = RpcClient()
    rpc_response = {}
    for i in range(1, 31):
        rpc_response = rpc.room_register(f'room-{i}')
        if rpc_response.get('status', 200) == 200: break
        else: print(rpc_response)
    room, name = rpc_response['roomId'], rpc_response['tankId']
    room_state = RoomEvents(room)
    room_state.start()

    ai = AI(name)

    counter = 0
    seconds = 0

    winner = ''
    lost = False
    kicked = False
    game_over = False
    mainloop = True
    while mainloop:
        millis = clock.tick(FPS)
        seconds += millis / 1000
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                mainloop = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    mainloop = False
                    game_over = True

        if not room_state.ready:
            wait_text = 'Wait, loading in progress.'
            wait_text = l_font.render(wait_text, True, (255, 255, 255))
            screen.fill((50, 50, 50))
            text_rect = wait_text.get_rect(center=(screen.get_size()[0] // 2, screen.get_size()[1] // 2))
            screen.blit(wait_text, text_rect)

        elif room_state.response:
            screen.fill((200, 200, 200))
            screen.blit(bg, (0, 0))
            cur_state = room_state.response
            tanks = cur_state['gameField']['tanks']
            bullets = cur_state['gameField']['bullets']

            ai.start(tanks, bullets)
            if ai.fire:
                rpc_response = rpc.fire()
                ai.fire = False
            if ai.turn_direction:
                print(ai.turn_direction)
                rpc_response = rpc.turn_tank(ai.turn_direction)
                ai.turn_direction = ''

            remaining_time = cur_state.get('remainingTime', 0)
            text = m_font.render(f'Remaining time: {remaining_time}', True, (0, 0, 0))
            text_rect = text.get_rect(center=(400, 50))
            screen.blit(text, text_rect)

            drawScoreboard(name, tanks, room)
            for tank in tanks:
                draw_tank(seconds, name, **tank)

            for bullet in bullets:
                draw_bullet(name, **bullet)
            if len(bullets) > counter: shoot_sound.play(maxtime=1600)
            counter = len(bullets)

            if room_state.new and cur_state['hits']:
                room_state.new = False
                explosion_sound.play()

            if next((x for x in cur_state['losers'] if x['tankId'] == name), None):
                lost = True
                mainloop = False
                game_over = True

            elif next((x for x in cur_state['kicked'] if x['tankId'] == name), None):
                kicked = True
                mainloop = False
                game_over = True

            elif cur_state['winners']:
                mainloop = False
                game_over = True
                win_text = 'Congrats! Score: {}. Winner(-s): '.format(cur_state["winners"][0]["score"])
                winner = win_text + ', '.join(map(lambda i: i['tankId'] if i['tankId'] != name else 'You', cur_state['winners']))

            elif not next((x for x in tanks if x['id'] == name), None):
                lost = True
                mainloop = False
                game_over = True
        pygame.display.flip()
    room_state.kill = True
    room_state.join()
    screen = pygame.display.set_mode((1200, 640))
    return game_over, winner, lost, kicked
Exemple #7
0
def online():
    global clock, screen
    screen = pygame.display.set_mode((1200, 640))
    rpc = RpcClient()
    rpc_response = {}
    for i in range(1, 31):
        rpc_response = rpc.room_register(f'room-{i}')
        if rpc_response.get('status', 200) == 200: break
        else: print(rpc_response)
    room, name = rpc_response['roomId'], rpc_response['tankId']
    room_state = RoomEvents(room)
    room_state.start()

    #КНОПОЧКИ------------------------------------

    KEYS = {
        pygame.K_w: 'UP',
        pygame.K_a: 'LEFT',
        pygame.K_d: 'RIGHT',
        pygame.K_s: 'DOWN'
    }

    #СТРЕЛЬБА.

    FIRE_KEY = pygame.K_SPACE

    counter = 0
    seconds = 0
    winner = ''
    lost = False
    kicked = False
    game_over = False
    mainloop = True
    while mainloop:
        millis = clock.tick(FPS)
        seconds += millis / 1000
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                mainloop = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    mainloop = False
                    game_over = True
                if event.key == FIRE_KEY:
                    rpc_response = rpc.fire()
                if event.key in KEYS:
                    direction = KEYS[event.key]
                    rpc_response = rpc.turn_tank(direction)

#ЗАГРУЗКА

        if not room_state.ready:
            wait_text = 'Hold on.Game is Loading...'
            wait_text = l_font.render(wait_text, True, (250, 250, 250))

            screen.fill((0, 0, 0))  #НАРИСОВАТЬ ЗАГР. ЭКРАН!

            text_rect = wait_text.get_rect(center=(screen.get_size()[0] // 2,
                                                   screen.get_size()[1] // 2))
            screen.blit(wait_text, text_rect)

        elif room_state.response:
            screen.fill((125, 125, 125))
            screen.blit(bg, (0, 0))
            cur_state = room_state.response
            tanks = cur_state['gameField']['tanks']
            bullets = cur_state['gameField']['bullets']

            remaining_time = cur_state.get('remainingTime', 0)
            text = m_font.render(f'Time Left: {remaining_time}', True,
                                 (255, 0, 0))

            text_rect = text.get_rect(center=(600, 75))
            screen.blit(text, text_rect)

            #ТАБЛИЦА СЧЕТА, НЕ ТРОГАТЬ, МОГУТ БЫТЬ ОШИБКИ

            drawScoreboard(name, tanks, room)
            for tank in tanks:
                draw_tank(seconds, name, **tank)

#СТРЕЛЬБА

            for bullet in bullets:
                draw_bullet(name, **bullet)
            if len(bullets) > counter: shoot_sound.play(maxtime=1600)
            counter = len(bullets)

            #ЗВУК ПОПАДАНИЯ

            if room_state.new and cur_state['hits']:
                room_state.new = False
                explosion_sound.play()

#ПРОИГРАВШИЕ

            if next((x for x in cur_state['losers'] if x['tankId'] == name),
                    None):
                lost = True
                mainloop = False
                game_over = True

#КИКНУТЫЕ

            elif next((x for x in cur_state['kicked'] if x['tankId'] == name),
                      None):
                kicked = True
                mainloop = False
                game_over = True

#ПОБЕДИТЕЛИ

            elif cur_state['winners']:
                mainloop = False
                game_over = True
                win_text = 'Good game! Winner with score: {} is : '.format(
                    cur_state["winners"][0]["score"])
                winner = win_text + ', '.join(
                    map(
                        lambda i: i['tankId']
                        if i['tankId'] != name else 'YOU',
                        cur_state['winners']))

            elif not next((x for x in tanks if x['id'] == name), None):
                lost = True
                mainloop = False
                game_over = True

        pygame.display.flip()

#ВОЗВРАТ В МЕНЮ ПОСЛЕ ИГРЫ

    room_state.kill = True
    room_state.join()
    screen = pygame.display.set_mode((1200, 640))
    return game_over, winner, lost, kicked