コード例 #1
0
def main(name):

    global players

    server = Network()
    current_id = server.connect(name)
    balls, players, game_time = server.send("get")

    clock = pygame.time.Clock()

    run = True
    while run:
        clock.tick(30)
        player = players[current_id]
        vel = START_VEL - round(player["score"] / 14)
        if vel <= 1:
            vel = 1

        keys = pygame.key.get_pressed()

        data = ""

        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            if player["x"] - vel - PLAYER_RADIUS - player["score"] >= 0:
                player["x"] = player["x"] - vel

        if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            if player["x"] + vel + PLAYER_RADIUS + player["score"] <= W:
                player["x"] = player["x"] + vel

        if keys[pygame.K_UP] or keys[pygame.K_w]:
            if player["y"] - vel - PLAYER_RADIUS - player["score"] >= 0:
                player["y"] = player["y"] - vel

        if keys[pygame.K_DOWN] or keys[pygame.K_s]:
            if player["y"] + vel + PLAYER_RADIUS + player["score"] <= H:
                player["y"] = player["y"] + vel

        data = "move " + str(player["x"]) + " " + str(player["y"])
        balls, players, game_time = server.send(data)

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

            if event.type == pygame.KEYDOWN:

                if event.key == pygame.K_ESCAPE:
                    run = False

        redraw_window(players, balls, game_time, player["score"])
        pygame.display.update()

    server.disconnect()
    pygame.quit()
    quit()
コード例 #2
0
def game(name) -> None:
    """
    Main function, opens connection between server and player, handles movement and redrawing
    :param name: str, name of player
    """
    global players
    server = Network()
    current_id = server.connect(name)
    balls, players, game_time = server.send("get")

    clock = pg.time.Clock()

    run = True
    while run:
        clock.tick(30)
        p = players[current_id]
        velocity = START_VELOCITY - round(p["score"] / 12)
        if velocity < 1:
            velocity = 1

        keys = pg.key.get_pressed()
        if keys[pg.K_a]:
            if p["x"] - velocity - PLAYER_RADIUS - p["score"] >= 0:
                p["x"] -= velocity
        if keys[pg.K_d]:
            if p["x"] + velocity + PLAYER_RADIUS + p["score"] <= WIDTH:
                p["x"] += velocity
        if keys[pg.K_w]:
            if p["y"] - velocity - PLAYER_RADIUS - p["score"] >= 0:
                p["y"] -= velocity
        if keys[pg.K_s]:
            if p["y"] + velocity + PLAYER_RADIUS + p["score"] <= HEIGHT:
                p["y"] += velocity

        data = f'move {p["x"]} {p["y"]}'
        balls, players, game_time, *_ = server.send(data)
        for event in pg.event.get():
            if event.type == pg.QUIT:
                run = False
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_ESCAPE:
                    run = False
        redraw_window(players, balls, game_time, p["score"])
        pg.display.update()

    server.disconnect()
    pg.quit()
    quit()
コード例 #3
0
ファイル: game.py プロジェクト: k4is3r/orbsWar-python
def main(name):
    """
    function for running the game,
    includes the main loop of the game
    players: a list of dicts representing a player
    return: None
    """
    global players

    #start by connection to the network
    server = Network()
    current_id = server.connect(name)
    #modifiying to recive to variables separate
    balls, players, game_time = server.send("get")
    #setup the clock, limit to 30 fps
    clock = pygame.time.Clock()

    run = True
コード例 #4
0
def main(name):
    """
    function for running the game,
    includes the main loop of the game
    :param players: a list of dicts represting a player
    :return: None
    """
    global players

    run = True
    while run:
        # start by connecting to the network
        server = Network()
        current_id = server.connect(name)
        players = server.send("get")

        # setup the clock, limit to 30fps
        clock = pygame.time.Clock()

        while run:
            clock.tick(60)  # 60 fps max
            player = players[current_id]

            data = ""
            handleInput(player, current_id)
            data = "move " + str(player["x"]) + " " + str(
                player["y"]) + " " + str(player["direction"])
            players = server.send(data)
            if current_id not in players:
                break
            data = ""
            for newShot in newShots:
                data += "shoot " + str(newShot["x"]) + " " + str(
                    newShot["y"]) + " " + str(newShot["dir_x"]) + " " + str(
                        newShot["dir_y"]) + " " + str(newShot["owner_id"])
            if len(data) > 0:
                shots = server.send(data)
                newShots.clear()

            # ======First compute the lighting information======

            #   Returns a greyscale surface of the shadows and the coordinates to draw it at.
            #   False tell it to not consider the occluders' interiors to be shadowed.  True
            #   means that the occluders' interiors are shadowed.  Note that if the light is
            #   within any occluder, everything is always shadowed.
            mask, draw_pos = shad.get_mask_and_position(False)

            #   Falloff (just multiplies the black and white mask by the falloff to make it
            #   look smoother).  Disabling "with_falloff" might make the algorithm more clear.
            mask.blit(surf_falloff, (0, 0), special_flags=BLEND_MULT)

            #   Ambient light
            surf_lighting.fill(AMBIENT_LIGHT)
            #   Add the contribution from the shadowed light source
            surf_lighting.blit(mask, draw_pos, special_flags=BLEND_MAX)

            #pygame.image.save(surf_lighting, "Test.JPG")

            WIN.fill((110, 170, 140))

            draw_players(players, current_id)

            # ======Now multiply the lighting information onto the scene======

            #   If you comment this out, you'll see the scene without any lighting.
            #   If you comment out just the special flags part, the lighting surface
            #   will overwrite the scene, and you'll see the lighting information.
            WIN.blit(surf_lighting, (0, 0), special_flags=BLEND_MULT)

            # ======Post processing======

            #   Hack to outline the occluders.  Don't use this yourself.
            for occluder in occluders:
                pygame.draw.lines(WIN, (255, 255, 255), True, occluder.points)

            pygame.display.update()

    server.disconnect()
    pygame.quit()
    quit()
コード例 #5
0
def main(name):
    """
	function for running the game,
	includes the main loop of the game

	:param players: a list of dicts represting a player
	:return: None
	"""
    global players

    # start by connecting to the network
    server = Network()
    current_id = server.connect(name)
    balls, players, game_time = server.send("get")

    # setup the clock, limit to 30fps
    clock = pygame.time.Clock()

    run = True
    while run:
        clock.tick(30)  # 30 fps max
        player = players[current_id]
        vel = START_VEL - round(player["score"] / 14)
        if vel <= 1:
            vel = 1

        # get key presses
        keys = pygame.key.get_pressed()

        data = ""
        # movement based on key presses
        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            if player["x"] - vel - PLAYER_RADIUS - player["score"] >= 0:
                player["x"] = player["x"] - vel

        if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            if player["x"] + vel + PLAYER_RADIUS + player["score"] <= W:
                player["x"] = player["x"] + vel

        if keys[pygame.K_UP] or keys[pygame.K_w]:
            if player["y"] - vel - PLAYER_RADIUS - player["score"] >= 0:
                player["y"] = player["y"] - vel

        if keys[pygame.K_DOWN] or keys[pygame.K_s]:
            if player["y"] + vel + PLAYER_RADIUS + player["score"] <= H:
                player["y"] = player["y"] + vel

        data = "move " + str(player["x"]) + " " + str(player["y"])

        # send data to server and recieve back all players information
        balls, players, game_time = server.send(data)

        for event in pygame.event.get():
            # if user hits red x button close window
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.KEYDOWN:
                # if user hits a escape key close program
                if event.key == pygame.K_ESCAPE:
                    run = False

        # redraw window then update the frame
        redraw_window(players, balls, game_time, player["score"])
        pygame.display.update()

    server.disconnect()
    pygame.quit()
    quit()
コード例 #6
0
def main(name):
    global p1_input
    pygame.init()
    base_font = pygame.font.Font(None, 32)

    input_rect = pygame.Rect(90, 785, 140, 32)
    active = False

    color_active = (0, 255, 0)
    color_passive = (255, 255, 255)
    color = color_passive
    """
    function for running the game,
    includes the main loop of the game

    :param players: a list of dicts represting a player
    :return: None
    """
    global players

    # start by connecting to the network
    server = Network()
    current_id = server.connect(name)
    balls, players, game_time = server.send("get")

    # setup the clock, limit to 30fps
    clock = pygame.time.Clock()
    assignImposter()

    started = False
    run = True
    while run:
        clock.tick(30)  # 30 fps max
        player = players[current_id]
        #print(players[current_id]) # print player id
        #print(current_id)
        # print(player["x"]) # player x
        # print("draw player")
        #drawPlayer(200,100, player)
        #drawPlayer(player["x"], player["y"])

        if (current_id == 4):
            # WIN.blit("red.png", (player["x"], player["x"]))
            print('')
        vel = START_VEL - round(player["score"] / 14)
        if vel <= 1:
            vel = 1

        # get key presses
        keys = pygame.key.get_pressed()

        data = ""
        # movement based on key presses
        if keys[pygame.K_LEFT]:
            if player["x"] - vel - PLAYER_RADIUS - player["score"] >= 0:
                player["x"] = player["x"] - vel

        if keys[pygame.K_RIGHT]:
            if player["x"] + vel + PLAYER_RADIUS + player["score"] <= W:
                player["x"] = player["x"] + vel

        if keys[pygame.K_UP]:
            if player["y"] - vel - PLAYER_RADIUS - player["score"] >= 0:
                player["y"] = player["y"] - vel

        if keys[pygame.K_DOWN]:
            if player["y"] + vel + PLAYER_RADIUS + player["score"] <= H:
                player["y"] = player["y"] + vel

        data = "move " + str(player["x"]) + " " + str(player["y"])

        # send data to server and recieve back all players information
        balls, players, game_time = server.send(data)

        for event in pygame.event.get():
            # if user hits red x button close window
            if event.type == pygame.QUIT:
                run = False

            # Check if mouse is clicked into rectangles to take in input
            if event.type == pygame.MOUSEBUTTONDOWN:
                # Check if mouse is clicked into 1ST rectangle to take in input for player 1
                if input_rect.collidepoint(event.pos):
                    active = True
                else:
                    active = False

            if event.type == pygame.KEYDOWN:
                # if user hits a escape key close program
                if event.key == pygame.K_ESCAPE:
                    run = False
                # If enter is pressed, lobby will close and game will start
                if event.key == pygame.K_RETURN:
                    started = True
                    #run = False

                # If 1ST rectangle is clicked on and green/active then take in user input from keyboard
                if active == True:
                    if event.key == pygame.K_BACKSPACE:
                        p1_input = p1_input[0:-1]
                    else:
                        p1_input += event.unicode

        # redraw window then update the frame
        if started:
            map = Map(1700, 850, "Version 1.0")
            map.drawMapBackground()
            redraw_gameWindow(players, balls, game_time, player["score"],
                              current_id, map)
            ###########Player Input text chat#####################################################################
            if active:
                color = color_active
            else:
                color = color_passive

            # CHAT BOX SHIT#
            font = pygame.font.Font(None, 30)
            p1_text = font.render("player: ", 1,
                                  (255, 255, 255))  # player 1 text
            map.screen.blit(p1_text, (15, 790))
            # Draw input rectangle 1
            pygame.draw.rect(map.screen, color, input_rect, 2)
            text_surface = base_font.render(p1_input, True, (255, 255, 255))
            map.screen.blit(
                text_surface,
                (input_rect.x + 5, input_rect.y + 5))  # Blit text into rect
            input_rect.w = max(100, text_surface.get_width() + 10)
            ########################################################################################################
            #drawChatBox(map)
        else:
            redraw_window(players, balls, game_time, player["score"],
                          current_id)
        pygame.display.update()

        #redraw_gameWindow(players, balls, game_time, player["score"], current_id)

    server.disconnect()
    pygame.quit()
    quit()
コード例 #7
0
def rungame(name):
    #CHAT BOX REQUIREMENTS#
    global p1_input
    pygame.init()
    base_font = pygame.font.Font(None, 32)
    input_rect = pygame.Rect(90, 805, 140, 32)
    active = False
    color_active = (0, 255, 0)
    color_passive = (255, 255, 255)
    color = color_passive
    font = pygame.font.Font(None, 30)
    chatText = font.render('', 1, (255, 255, 255))  # player 1 text


    start_ticks = pygame.time.get_ticks()  # start timer
    max_time = 30  # set max time
    vote = 2
# CHAT BOX REQUIREMENTS END#
    global players
    # start by connecting to the network
    server = Network()
    current_id = server.connect(name)
    balls, players, game_time = server.send("get")
    # setup the clock, limit to 30fps
    clock = pygame.time.Clock()
    assignImposter()

    # Declaring array storing bullets
    bullets = []
    shotLoop = 0  # bullet cool down

    # start killing timer
    startKILL = pygame.time.get_ticks()
    maxKILL = 30  # set overall kill interval time

    started = False
    run = True
    while run:
        clock.tick(30) # 30 fps max
        player = players[current_id]

        # setting basic timer for projectiles
        if shotLoop > 0:
            shotLoop += 1
        if shotLoop > 3:
            shotLoop = 0
        #print(players[current_id]) # print player id
        #print(current_id)
        # print(player["x"]) # player x
        # print("draw player")
        #drawPlayer(200,100, player)
        #drawPlayer(player["x"], player["y"])

        if(current_id == 4):
            # WIN.blit("red.png", (player["x"], player["x"]))
            print('')
        vel = START_VEL - round(player["score"]/14)
        if vel <= 1:
            vel = 1

        # get key presses
        keys = pygame.key.get_pressed()

        data = ""
        # movement based on key presses
        if keys[pygame.K_LEFT]:
            if player["x"] - vel - PLAYER_RADIUS - player["score"] >= 0:
                player["x"] = player["x"] - vel

        if keys[pygame.K_RIGHT]:
            if player["x"] + vel + PLAYER_RADIUS + player["score"] <= W:
                player["x"] = player["x"] + vel

        if keys[pygame.K_UP]:
            if player["y"] - vel - PLAYER_RADIUS - player["score"] >= 0:
                player["y"] = player["y"] - vel

        if keys[pygame.K_DOWN]:
            if player["y"] + vel + PLAYER_RADIUS + player["score"] <= H:
                player["y"] = player["y"] + vel

        data = "move " + str(player["x"]) + " " + str(player["y"])

        # allow user to shoot projectile if bullet cooldown is met
        if keys[pygame.K_SPACE] and shotLoop == 0:
            if len(bullets) < 5:
                bullets.append(projectile(player["x"], player["y"], 6, (255, 0, 0), 1, map.screen))
            shotLoop = 1

        # send data to server and recieve back all players information
        balls, players, game_time = server.send(data)

        for event in pygame.event.get():
            # if user hits red x button close window
            if event.type == pygame.QUIT:
                run = False

            # Check if mouse is clicked into rectangles to take in input
            if event.type == pygame.MOUSEBUTTONDOWN:
                # Check if mouse is clicked into 1ST rectangle to take in input for player 1
                if input_rect.collidepoint(event.pos):
                    active = True
                else:
                    active = False

            if event.type == pygame.KEYDOWN:
                # if user hits a escape key close program
                if event.key == pygame.K_ESCAPE:
                    run = False
                # If enter is pressed, lobby will close and game will start
                if event.key == pygame.K_RETURN:
                    started = True
                    #run = False

                # If 1ST rectangle is clicked on and green/active then take in user input from keyboard
                if active == True:
                    if event.key == pygame.K_BACKSPACE:
                        p1_input = p1_input[0:-1]
                    else:
                        p1_input += event.unicode


        # redraw window then update the frame
        if started:
            map = Map(1700, 850, "Version 1.0")
            map.drawMapBackground()
            #DRAW IN ALL OBSTACLES AND TASKS FOR GAME WITH redraw_MAP
            redraw_MAP(players, balls, game_time, player["score"], current_id, map)
            ##Player Input text chat###
            if active:
                color = color_active
            else:
                color = color_passive
            font = pygame.font.Font(None, 30)
            p1_text = font.render("player: ", 1, (255, 255, 255))  # player 1 text
            map.screen.blit(p1_text, (15, 810))
            pygame.draw.rect(map.screen, color, input_rect, 2)
            text_surface = base_font.render(p1_input, True, (255, 255, 255))
            map.screen.blit(text_surface, (input_rect.x + 5, input_rect.y + 5))  # Blit text into rect
            input_rect.w = max(100, text_surface.get_width() + 10)
            if keys[pygame.K_RETURN]:
                chatText = font.render(p1_input, 1, (255, 255, 255))  # player 1 text
            map.screen.blit(chatText, (90, 780))
            ##Player Input text chat END###







            # Imposter Mission Cover UP
            if player["role"] == "imposter":
                # Imposter label
                font = pygame.font.Font(None, 30)
                eLabel = font.render(player["role"], 1, (255, 255, 255))
                map.getMap().blit(eLabel, (550, 15))

                #Cover up aliens for imposter
                bg_img1 = pygame.image.load('Images/gone.png')
                map.getMap().blit(bg_img1, (1000, 25))
                map.getMap().blit(bg_img1, (1060, 25))
                map.getMap().blit(bg_img1, (1120, 25))

                # coverup mission prompt
                mission_text = font.render("Exterminate all aliens on board", 1, (0, 0, 0))  # player 1 text
                map.getMap().blit(mission_text, (625, 790))

                #Cover up mission list
                coverUP_rect = pygame.Rect(90, 805, 140, 32)

                mission_write_y = 550  # 1380 for x
                map.getMap().blit(font.render("Exterminate all aliens on board", 1, (0, 0, 0)), (1380, mission_write_y))
                mission_write_y = mission_write_y + 40
                map.getMap().blit(font.render("Acquire Jewel", 1, (0, 0, 0)), (1380, mission_write_y))
                mission_write_y = mission_write_y + 40
                map.getMap().blit(font.render("Destroy Obstacle Covering Front Entrance of Main Room", 1, (0, 0, 0)), (1380, mission_write_y))
                mission_write_y = mission_write_y + 40
                map.getMap().blit(font.render("Simon says", 1, (0, 0, 0)), (1380, mission_write_y))
                mission_write_y = mission_write_y + 40
                map.getMap().blit(font.render("Move to your colored circle", 1, (0, 0, 0)), (1380, mission_write_y))

                #Kill Cooldown Timer
                secs = (pygame.time.get_ticks() - startKILL) / 1000  # calculate how many seconds
                dif = int(maxKILL - secs)
                if (dif < 0):
                    maxKILL += 30
                if (dif > 15 and dif < 31):
                    time = "ALLOWED TO KILL!"
                    timer_txt = font.render(time, 1, (0, 255, 0))  # player 1 text
                    map.getMap().blit(timer_txt, (640, 790))
                    # KILLING CHARACTERS#
                    # USE 2 KEY TO KILL PLAYER 2
                    #if keys[pygame.K_2]:

                if (dif > -1 and dif < 16):
                    time = "Kill Cooldown: " + str(dif)
                    timer_txt = font.render(time, 1, (255, 0, 0))  # player 1 text
                    map.getMap().blit(timer_txt, (640, 790))






            #####ALIEN TASk
            alien = Alien(1000, 25, 40, 29, 'Images/alien.png', 'Images/gone.png', map)
            alien2 = Alien(1060, 25, 40, 29, 'Images/alien.png', 'Images/gone.png', map)
            alien3 = Alien(1120, 25, 40, 29, 'Images/alien.png', 'Images/gone.png', map)

            # DRAWING BULLETS TO APPEAR IN GAME
            for bullet in bullets:
                # bg_img = pygame.image.load('Images/gone.png').convert_alpha()
                bullet.draw()

            for bullet in bullets:
                # ADDING COLLISON DETECTION FOR THE 3 ALIENS
                if alien.current_image == alien.images[0]:
                    if bullet.y - bullet.radius < alien.hitbox[1] + alien.hitbox[3] and bullet.y + bullet.radius > \
                            alien.hitbox[1]:  # checks if we are above the bottom and below the top of the rectangle
                        if bullet.x + bullet.radius > alien.hitbox[0] and bullet.x - bullet.radius < alien.hitbox[0] + \
                                alien.hitbox[2]:
                            alien.current_image = alien.images[1]  # Change alien image to alienGone image
                            bg_img1 = pygame.image.load('Images/gone.png').convert_alpha()
                            map.screen.blit(bg_img1, (1000, 25))
                            map.screen.blit(bg_img1, (1060, 25))
                            map.screen.blit(bg_img1, (1120, 25))
                            bullets.pop(bullets.index(bullet))

                if alien2.current_image == alien2.images[0]:
                    if bullet.y - bullet.radius < alien2.hitbox[1] + alien2.hitbox[3] and bullet.y + bullet.radius > \
                            alien2.hitbox[1]:  # checks if we are above the bottom and below the top of the rectangle
                        if bullet.x + bullet.radius > alien2.hitbox[0] and bullet.x - bullet.radius < alien2.hitbox[0] + \
                                alien2.hitbox[2]:
                            alien2.current_image = alien2.images[1]  # Change alien image to alienGone image
                            bullets.pop(bullets.index(bullet))

                if alien3.current_image == alien3.images[0]:
                    if bullet.y - bullet.radius < alien3.hitbox[1] + alien3.hitbox[3] and bullet.y + bullet.radius > \
                            alien3.hitbox[1]:  # checks if we are above the bottom and below the top of the rectangle
                        if bullet.x + bullet.radius > alien3.hitbox[0] and bullet.x - bullet.radius < alien3.hitbox[0] + \
                                alien3.hitbox[2]:
                            alien3.current_image = alien3.images[1]  # Change alien image to alienGone image
                            bg_img1 = pygame.image.load('Images/gone.png').convert_alpha()
                            bullets.pop(bullets.index(bullet))
                if bullet.x < 1700 and bullet.x > 0:
                    bullet.x += bullet.vel
                else:
                    bullets.pop(bullets.index(bullet))

                alien.draw(map.screen)
                alien2.draw(map.screen)
                alien3.draw(map.screen)
            #####ALIEN TASk END



            # Voting labels
            red_text = font.render("red", 1, (255, 255, 255))  # player 1 text
            map.screen.blit(red_text, (1530, 260))
            blue_text = font.render("blue", 1, (255, 255, 255))  # player 1 text
            map.screen.blit(blue_text, (1530, 310))
            cyan_text = font.render("cyan", 1, (255, 255, 255))  # player 1 text
            map.screen.blit(cyan_text, (1530, 360))
            orange_text = font.render("orange", 1, (255, 255, 255))  # player 1 text
            map.screen.blit(orange_text, (1530, 410))
            if ((vote % 2) == 0):
                vote_text = font.render("vote", 1, (255, 255, 255))  # player 1 text
                map.screen.blit(vote_text, (1530, 200))

            else:
                vote_text = font.render("vote", 1, (0, 255, 0))  # set vote text to green
                map.screen.blit(vote_text, (1530, 200))
                number_of_players = len(players)
                alive_players = 0

                i = 0
                while (i < number_of_players):
                    if (players[i]["alive"] == 0):
                        alive_players = alive_players + 1
                        #print(players[i].color)
                        if (players[i]["pid"] == 1): # red, cyan, orange, blue
                            cyan_text = font.render("cyan", 1, (0, 255, 255))  # player 1 text
                            map.screen.blit(cyan_text, (1530, 360))
                        elif (players[i]["pid"] == 2):
                            orange_text = font.render("orange", 1, (255, 160, 0))  # player 1 text
                            map.screen.blit(orange_text, (1530, 410))
                        elif (players[i]["pid"] == 0):
                            red_text = font.render("red", 1, (255, 0, 0))  # player 1 text
                            map.screen.blit(red_text, (1530, 260))
                        elif (players[i]["pid"] == 3):
                            blue_text = font.render("blue", 1, (0, 0, 255))  # player 1 text
                            map.screen.blit(blue_text, (1530, 310))


                    i = i + 1

            # Timer
            seconds = (pygame.time.get_ticks() - start_ticks) / 1000  # calculate how many seconds
            # print(seconds) #print how many seconds
            # print(int(max_time - seconds))  # debug
            diff = int(max_time - seconds)
            if (diff < 0):
                # start_ticks = 0
                max_time += 30
                vote += 1
            time_diff = "timer: " + str(diff)
            timer_text = font.render(time_diff, 1, (255, 255, 255))  # player 1 text
            map.screen.blit(timer_text, (1500, 475))

        else:
            redraw_LOBBY(players, balls, game_time, player["score"], current_id)



        pygame.display.update()

        #redraw_gameWindow(players, balls, game_time, player["score"], current_id)


    server.disconnect()
    pygame.quit()
    quit()
コード例 #8
0
ファイル: game.py プロジェクト: Intarium/survivor
def main(name):
    WIN = pygame.display.set_mode((W, H))
    pygame.display.set_caption("Survivor")
    global players, WALK_COUNT, isJump, jumpCount
    # start by connecting to the network
    server = Network()
    current_id = server.connect(name)
    players, game_time = server.send("get")

    # setup the clock, limit to 30fps
    clock = pygame.time.Clock()

    run = True
    while run:
        clock.tick(60)
        player = players[current_id]
        vel = START_VEL
        if vel <= 1:
            vel = 1
        keys = pygame.key.get_pressed()
        lastkey = ''
        data = "map "
        map = server.send(data)

        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            player["x"] = player["x"] - vel
            player["left"] = True
            player["right"] = False

        if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            player["x"] = player["x"] + vel
            player["right"] = True
            player["left"] = False

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

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    run = False
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                    player["right"] = False
                    player["left"] = False
                    lastkey = 'left'
                if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                    player["right"] = False
                    player["left"] = False
                    lastkey = 'right'

        data = "move " + str(player["x"]) + " " + str(player["y"]) + " " + str(
            player["left"]) + " " + str(player["right"]) + " " + str(lastkey)

        players, game_time = server.send(data)

        redraw_window(players, game_time, player["score"], map, WIN)
        pygame.display.update()

    server.disconnect()
    pygame.quit()
    quit()
コード例 #9
0
    def game_page(self, online=False):

        self.loading_page()

        self.win.fill((255, 0, 0))

        bg = pg.image.load('./assets/board.jpg')
        bg = pg.transform.scale(bg, (680, self.win_height))

        computer = Label('Computer')
        computer.config(color=(57, 62, 70), font_size=54)

        user = Label('User')
        user.config(color=(240, 240, 240), font_size=54)

        black_timer = Label('Black')
        black_timer.config(color=(57, 62, 70), font_size=48)

        black_time = Label('15:00')
        black_time.config(color=(57, 62, 70), font_size=32)

        white_timer = Label('White')
        white_timer.config(color=(240, 240, 240), font_size=48)

        white_time = Label('15:00')
        white_time.config(color=(240, 240, 240), font_size=32)

        player = Network()

        board = Board()
        player_turn = 1

        if online:
            player.connect()
            color = player.recv(13)

            player_turn = 1 if color == 'w' else 0

        message1 = Label('')
        message1.config(color=(255, 255, 255), font_size=48)

        message2 = Label('')
        message2.config(color=(255, 255, 255), font_size=32)

        w_time = b_time = 900

        while True:

            if online and not board.game_over:
                board = player.get_board()
                if board.turn == 1:
                    w_time = 900 - board.white_time_elapsed
                else:
                    b_time = 900 - board.black_time_elapsed

            self.win.blit(bg, (0, 0))

            pg.draw.rect(self.win, (1, 1, 1), (690, 0, 310, 680))

            if online:
                black_timer.draw(self.win, 780, 20)
                black_time.change_text(
                    f'{b_time // 60}:{ f"0{b_time % 60}" if b_time % 60 < 10 else b_time % 60}'
                )
                black_time.draw(self.win, 800, 100)
            else:
                computer.draw(self.win, 750, 20)

            pg.draw.rect(self.win, (255, 0, 0),
                         (690, 150, 310, 10))  # Red Line

            board_message1 = message1.get_rect()
            board_message1.center = (680 + 160, 200)
            message1.draw(self.win, board_message1.x, board_message1.y)

            board_message2 = message2.get_rect()
            board_message2.center = (680 + 160, 250)
            message2.draw(self.win, board_message2.x, board_message2.y)

            pg.draw.rect(self.win, (255, 0, 0),
                         (690, 530, 310, 10))  # Red Line

            if online:
                white_timer.draw(self.win, 780, 550)
                white_time.change_text(
                    f'{w_time // 60}:{ f"0{w_time % 60}" if w_time % 60 < 10 else w_time % 60}'
                )
                white_time.draw(self.win, 800, 630)
            else:
                user.draw(self.win, 790, 550)

            if not online and not board.turn:
                self.call_ai(board)

            for event in pg.event.get():
                if event.type == pg.QUIT:
                    self.quit()

                if event.type == pg.KEYDOWN:
                    if event.key == pg.K_q:
                        if online:
                            player.disconnect()
                        self.menu_page()

                if event.type == pg.MOUSEBUTTONDOWN:
                    mx, my = event.pos
                    if board.turn == player_turn and not board.game_over:
                        board.select(mx // 85, my // 85)

                        if online:
                            player.send_board(board)

            self.draw(board)

            for i in range(len(board.history)):
                turn, source, dest = board.history[i]
                source = self.get_square(*source)
                dest = self.get_square(*dest)

                history = Label(f'{source}-{dest}')
                history.config(color=(240, 240, 240) if turn == 1 else
                               (57, 62, 70),
                               font_size=24)
                history.draw(self.win, 810, 280 + (i * 40))

            if w_time == 0 or b_time == 0:
                board.game_over = True
                message1.change_text("Time's Up")
                message2.change_text(
                    f'{"Black" if board.turn == 1 else "White"} Wins')
                if online:
                    player.disconnect()
            elif board.game_over and board.check_mate:
                message1.change_text('Check Mate')
                message2.change_text(
                    f'{"Black" if board.turn == 1 else "White"} Wins')
                if online:
                    player.disconnect()
            elif board.game_over:
                message2.change_text('Other Player Left')
                if online:
                    player.disconnect()
            elif board.check:
                message1.change_text('Check')
            else:
                message1.change_text('')
                message2.change_text('')

            pg.display.update()