示例#1
0
def main():
    """Main function"""
    pygame.init()
    screen = pygame.display.set_mode((600, 600))
    clock = pygame.time.Clock()
    rect = pygame.Rect(0, 0, 50, 50)
    network = Network()

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        data = network.send("get")
        print(data)
        if data and "," in data:
            speed = [int(x) for x in data.split(",")]
            rect = rect.move(speed)

        screen.fill((0, 0, 0))
        pygame.draw.rect(screen, (255, 255, 255), rect)
        pygame.display.flip()
        clock.tick(60)

    pygame.quit()
示例#2
0
class Game:
    def __init__(self):
        global datab, winmulti
        winmulti = False
        datab = "none"
        try:
            self.net = Network()
        except:
            print("Erreur de connexion")
            try:
                main.fen.destroy()
                main.fen2.destroy()
            except:
                print("")
            os.system('python jeu.py')
            exit()
        self.player = Player()
        self.player2 = Player()

    def update(self):
        global winmulti, datab
        while winmulti != True:
            self.player2.up = self.parse_data(self.send_data())
            print("RECV", self.player2.up)
            time.sleep(1)
        datab = "WINNER"
        self.player2.up = self.parse_data(self.send_data())
        time.sleep(1)

    def send_data(self):
        global datab
        data = str(self.net.id) + ":" + str(datab)
        reply = self.net.send(data)
        return reply

    @staticmethod
    def parse_data(data):
        global xm, ym, colorm, g
        try:
            d = data.split(":")[1]
            print("Data : ", d)
            if ("WINNER" in d):
                if messagebox.askyesno("C'est perdu !", "Dommage ! Rejouer ?"):
                    main.fen.destroy()
                    os.system('python jeu.py')
                else:
                    main.fen.destroy()
                    os.system('python menu.py')
            else:
                if ("NONE" not in d):
                    xm = d.split(",")[0].replace("(", "")
                    xm = int(xm.replace(" ", ""))
                    ym = d.split(",")[1]
                    ym = int(ym.replace(" ", ""))
                    colorm = d.split(",")[2].replace(")", "")
                    colorm = colorm.replace("'", "")
                    colorm = colorm.replace(" ", "")
            return d
        except:
            return 0
示例#3
0
def menu_screen():
    run = True
    while run:
        win.fill((128, 128, 128))
        font = pygame.font.SysFont("comicsans", 80)
        title = font.render("Chess Game!", 1, (0, 200, 0))
        join = font.render("Click To Join a Game!", 1, (0, 128, 0))
        font2 = pygame.font.SysFont("comicsans", 20)
        made_by = font2.render("Made by DNSLV-PMTKV", 1, (0, 0, 0))
        win.blit(title, (WIDTH / 2 - title.get_width() / 2, 200))
        win.blit(join, (WIDTH / 2 - join.get_width() / 2, 400))
        win.blit(made_by, (825, 775))
        pygame.display.update()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                run = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                run = False
    while True:
        try:
            global board, n
            n = Network()
            board = n.board
            break
        except:
            print("Server offline")

    main()
示例#4
0
 def __init__(self):
     global datab, winmulti
     winmulti = False
     datab = "none"
     try:
         self.net = Network()
     except:
         print("Erreur de connexion")
         try:
             main.fen.destroy()
             main.fen2.destroy()
         except:
             print("")
         os.system('python jeu.py')
         exit()
     self.player = Player()
     self.player2 = Player()
示例#5
0
def main():
    run = True
    clock = pygame.time.Clock()
    socket = Network()
    p = socket.getData()

    while run:
        clock.tick(60)
        p2 = socket.send(p)

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

        p.move()
        redrawWindow(win, p, p2)
示例#6
0
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
示例#7
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()
示例#8
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()
示例#9
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()
示例#10
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()
示例#11
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()
示例#12
0
class Rebel(Log):
    def __init__(self,
                 menuWidth,
                 menuHeight,
                 mainWidth,
                 mainHeight,
                 configFile=os.path.join("..", "config", "config.txt")):

        # initialize
        pygame.init()
        pygame.mixer.pre_init(frequency=44100, size=16, channels=1)
        pygame.mixer.init()
        pygame.font.init()

        if getattr(sys, 'frozen', False):
            # In a bundle
            self.exeDir = os.path.dirname(sys.executable)
        else:
            # In normal python
            self.exeDir = ""

        self.font = Font(directory=os.path.join(self.exeDir, "..", "fonts"))

        self.logFile = os.path.join(self.exeDir, "..", "log", "log.txt")
        Log.__init__(self, logFile=self.logFile)
        self.clearLog()

        self.reBelClientVersion = "v1.0.1"
        self.log("[INFO] Running ReBel client {}".format(
            self.reBelClientVersion))

        self.menuWidth = menuWidth
        self.menuHeight = menuHeight

        self.mainWidth = mainWidth
        self.mainHeight = mainHeight

        self.configFile = os.path.join(self.exeDir, configFile)

        self.win = pygame.display.set_mode((self.menuWidth, self.menuHeight))
        pygame.display.set_caption("ReBel")
        self.gameIcon = pygame.image.load(
            os.path.join(self.exeDir, "..", "img", "ReBel_Icon.png"))
        pygame.display.set_icon(self.gameIcon)

        self.config = Config(fileName=self.configFile)

        self.frameRate = self.config.get('frameRate')
        self.log("[INFO] FrameRate set to {}".format(self.frameRate))

        self.network = Network(self.logFile, frameRate=self.frameRate)
        self.aboutScreen = AboutScreen(self.win,
                                       font=self.font,
                                       frameRate=self.frameRate,
                                       version=self.reBelClientVersion)
        self.helpScreen = HelpScreen(self.win,
                                     font=self.font,
                                     frameRate=self.frameRate)
        self.menuScreen = MenuScreen(win=self.win,
                                     font=self.font,
                                     network=self.network,
                                     frameRate=self.frameRate,
                                     logFile=self.logFile,
                                     config=self.config)
        self.optionsScreen = OptionsScreen(win=self.win,
                                           font=self.font,
                                           config=self.config,
                                           frameRate=self.frameRate)
        self.ringingScreen = RingingScreen(network=self.network,
                                           width=self.mainWidth,
                                           height=self.mainHeight,
                                           font=self.font,
                                           frameRate=self.frameRate,
                                           logFile=self.logFile,
                                           config=self.config)

        self.screen = 'menuScreen'

    def quit(self):
        self.running = False
        if self.network.connected == True:
            self.network.send("clientDisconnect:Disconnecting")
        self.log("[INFO] Quitting...")
        pygame.quit()
        sys.exit(0)

    def updateScreenSize(self, width, height):
        self.win = pygame.display.set_mode((width, height))

    def run(self):
        self.running = True
        while self.running:
            if self.screen == 'menuScreen':
                self.ringingScreen.initialised = False
                self.updateScreenSize(self.menuWidth, self.menuHeight)
                self.previousScreen = 'menuScreen'
                self.screen = self.menuScreen.display()
                if self.screen == 'quit':
                    self.quit()
            elif self.screen == 'aboutScreen':
                self.screen = self.aboutScreen.display(
                    win=self.win, source=self.previousScreen)
                if self.screen == 'quit':
                    self.quit()
            elif self.screen == 'helpScreen':
                self.screen = self.helpScreen.display(
                    win=self.win, source=self.previousScreen)
                if self.screen == 'quit':
                    self.quit()
            elif self.screen == 'optionsScreen':
                self.screen = self.optionsScreen.display(
                    win=self.win, source=self.previousScreen)
                if self.screen == 'quit':
                    self.quit()
                elif self.optionsScreen.bellKeysUpdated:
                    self.ringingScreen.updateBellKeys()
                    self.ringingScreen.updateBellDisplayLocations()
                    self.optionsScreen.bellKeysUpdated = False
            elif self.screen == 'ringingScreen':
                self.updateScreenSize(self.mainWidth, self.mainHeight)
                self.previousScreen = 'ringingScreen'
                self.screen = self.ringingScreen.display()
                if self.screen == 'quit':
                    self.quit()
            else:
                self.quit()
示例#13
0
    def __init__(self,
                 menuWidth,
                 menuHeight,
                 mainWidth,
                 mainHeight,
                 configFile=os.path.join("..", "config", "config.txt")):

        # initialize
        pygame.init()
        pygame.mixer.pre_init(frequency=44100, size=16, channels=1)
        pygame.mixer.init()
        pygame.font.init()

        if getattr(sys, 'frozen', False):
            # In a bundle
            self.exeDir = os.path.dirname(sys.executable)
        else:
            # In normal python
            self.exeDir = ""

        self.font = Font(directory=os.path.join(self.exeDir, "..", "fonts"))

        self.logFile = os.path.join(self.exeDir, "..", "log", "log.txt")
        Log.__init__(self, logFile=self.logFile)
        self.clearLog()

        self.reBelClientVersion = "v1.0.1"
        self.log("[INFO] Running ReBel client {}".format(
            self.reBelClientVersion))

        self.menuWidth = menuWidth
        self.menuHeight = menuHeight

        self.mainWidth = mainWidth
        self.mainHeight = mainHeight

        self.configFile = os.path.join(self.exeDir, configFile)

        self.win = pygame.display.set_mode((self.menuWidth, self.menuHeight))
        pygame.display.set_caption("ReBel")
        self.gameIcon = pygame.image.load(
            os.path.join(self.exeDir, "..", "img", "ReBel_Icon.png"))
        pygame.display.set_icon(self.gameIcon)

        self.config = Config(fileName=self.configFile)

        self.frameRate = self.config.get('frameRate')
        self.log("[INFO] FrameRate set to {}".format(self.frameRate))

        self.network = Network(self.logFile, frameRate=self.frameRate)
        self.aboutScreen = AboutScreen(self.win,
                                       font=self.font,
                                       frameRate=self.frameRate,
                                       version=self.reBelClientVersion)
        self.helpScreen = HelpScreen(self.win,
                                     font=self.font,
                                     frameRate=self.frameRate)
        self.menuScreen = MenuScreen(win=self.win,
                                     font=self.font,
                                     network=self.network,
                                     frameRate=self.frameRate,
                                     logFile=self.logFile,
                                     config=self.config)
        self.optionsScreen = OptionsScreen(win=self.win,
                                           font=self.font,
                                           config=self.config,
                                           frameRate=self.frameRate)
        self.ringingScreen = RingingScreen(network=self.network,
                                           width=self.mainWidth,
                                           height=self.mainHeight,
                                           font=self.font,
                                           frameRate=self.frameRate,
                                           logFile=self.logFile,
                                           config=self.config)

        self.screen = 'menuScreen'
示例#14
0
from client import Network
import time


n = Network() 


while True:
	print('running')
	time.sleep(5)
	pass
示例#15
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()
示例#16
0
    def run(self):

        game_over = False
        turn = 0
        #grid =self.grid
        grid = np.zeros((self.rows, self.columns), int)
        pg.init()

        WINDOW_SIZE = [self.width, self.height]

        screen = pg.display.set_mode(WINDOW_SIZE)
        self.draw_grid(screen, grid)
        pg.display.update()

        fontType = pg.font.SysFont("Arial", 30)

        while not game_over:
            grid = self.connect()

            for event in pg.event.get():
                if event.type == pg.QUIT:
                    game_over = True
                    #sys.exit()
                if event.type == pg.MOUSEMOTION:

                    pg.draw.rect(screen, WHITE, (0, 0, self.width, CELL_SIZE))
                    posx = event.pos[0]
                    col = posx // CELL_SIZE
                    if turn == 0:
                        pg.draw.circle(screen, RED,
                                       (int(CELL_SIZE * col + CELL_SIZE / 2),
                                        int(CELL_SIZE / 2)), RADIUS)
                    else:
                        pg.draw.circle(screen, YELLOW,
                                       (int(CELL_SIZE * col + CELL_SIZE / 2),
                                        int(CELL_SIZE / 2)), RADIUS)
                pg.display.update()

                if event.type == pg.MOUSEBUTTONDOWN:
                    pg.draw.rect(screen, WHITE, (0, 0, self.width, CELL_SIZE))
                    # Player 1 moves
                    if turn == 0:
                        posx = event.pos[0]
                        col = posx // CELL_SIZE
                        if grid[self.rows - 1][col] == 0:
                            row = self.find_empty_row(grid, col)
                            grid[row][col] = 1

                            if self.is_winning(grid, 1):
                                label = fontType.render(
                                    "Player 1 won!", 1, BLACK)
                                screen.blit(label, (self.width / 2 - 70, 10))
                                game_over = True

                    # Player 2 moves
                    else:
                        posx = event.pos[0]
                        col = posx // CELL_SIZE
                        if grid[self.rows - 1][col] == 0:
                            row = self.find_empty_row(grid, col)
                            grid[row][col] = 2

                            if self.is_winning(grid, 2):
                                label = fontType.render(
                                    "Player 2 won!", 1, BLACK)
                                screen.blit(label, (self.width / 2 - 70, 10))
                                game_over = True

                            if self.is_full(grid):
                                label = fontType.render(
                                    "Nobody wins! Game over!", 1, BLACK)
                                screen.blit(label, (self.width / 2 - 130, 10))
                                game_over = True
                    Network().send(grid)
                    self.draw_grid(screen, grid)

                    if game_over:
                        pg.time.wait(3000)
                        # quit pygame to avoid hanging on exit
                        pg.quit()
示例#17
0
 def connect(self):
     global n
     n = Network()
     return n.grid
示例#18
0
def connect():
    global n
    n = Network()
    return n.board
示例#19
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()
示例#20
0
def connect(connection_config):
    global n
    n = Network(**connection_config)
    return n.board
示例#21
0
# -*- coding: utf-8 -*-
"""
Created on Sun May 16 18:46:57 2021

@author: Korean_Crimson
"""
import pygame
from client import Network

# pylint: disable=no-member

pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((100, 100))
network = Network()


def get_speed(keys):
    """Returns the speed as a string depending on the key state. This can be
    sent directly to the server to communicate this speed to another machine.
    """
    if keys[pygame.K_LEFT]:
        speed = "-1,0"
    elif keys[pygame.K_RIGHT]:
        speed = "1,0"
    elif keys[pygame.K_DOWN]:
        speed = "0,1"
    elif keys[pygame.K_UP]:
        speed = "0,-1"
    else:
        speed = "0,0"
示例#22
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()