Exemple #1
0
 def __init__(self,
              name,
              position,
              difficulty,
              game_board=None,
              game_rules=None):
     Player.__init__(self, name, position)
     self.game_board = game_board
     self.game_rules = game_rules
     self.difficulty = difficulty
     self.position = position
Exemple #2
0
 async def connectPlayer(self, player: Player):
     while len(self.__players) < 2:
         await asyncio.sleep(1)
         try:
             await player.ping()
         except ConnectionClosedOK:
             logger.info("{} has disconnected.".format(player.getAddress()))
             return
         except ConnectionClosedError as e:
             logger.error(
                 "{}: Connection with {} has been terminated. Reason: {}".
                 format(e.code, player.getAddress(), e.reason))
             return
     await self.__start()
Exemple #3
0
    async def askIfReady(player: Player) -> bool:
        """
        Ready = True, AFK = False.
        """
        player.clearMessages()
        await player.sendMessage("READY_CHECK")

        for _ in range(10):  # A player has 10 seconds to send the ready signal.
            msg = player.getMessageIfReceived()
            if msg == "READY":
                return True
            await player.ping()
            await asyncio.sleep(1)

        return False
Exemple #4
0
    async def getBase(player: Player):

        player.clearMessages()
        await player.sendMessage("GET_BASE")

        for _ in range(5):
            msg = player.getMessageIfReceived()
            if msg == "OK":
                return
            await player.ping()
            await asyncio.sleep(1)

        logger.error("{} received a GET_BASE signal but didn't respond!".format(player.getAddress()))
        await player.sendMessageSafe("KICKED:NO_RESPONSE")
        await player.disconnect()
        raise PlayerKickedException(player, "No response")
Exemple #5
0
    async def __verifyPlayer(player: Player):
        for _ in range(5):
            code = player.getMessageIfReceived()
            if code:
                break
            await asyncio.sleep(1)
        else:
            return False

        try:
            playerId = HttpPipe.players.pop(code)
        except KeyError:
            return False

        player.setId(playerId)
        return True
Exemple #6
0
 def tryToAddPlayer(self, player: Player) -> bool:
     """
     Returns True if added and False if not.
     """
     if not self.isFull():
         logger.debug("Adding {} to room {}.".format(
             player.getAddress(), str(self.__ID)))
         self.__players.add(player)
     else:
         return False
     return True
Exemple #7
0
    async def userHandler(cls, websocket: websockets.WebSocketClientProtocol,
                          _):  # _ is path.
        player = Player(websocket)
        if (not await cls.__verifyPlayer(player)):
            await player.sendMessageSafe("BAD_CODE")
            logger.warning(
                player.getAddress() +
                " has tried to connect but didn't pass the verification!")
            return

        cls.__cooldown += 4
        await asyncio.sleep(cls.__cooldown
                            )  # Players can join once per 4 seconds.
        cls.__cooldown -= 4

        cls.__ID += 1
        logger.info(player.getAddress() + " has connected.")

        room = RoomList.addPlayer(player)
        await room.connectPlayer(player)

        RoomList.removeRoom(room.getID())
        await player.disconnect()
        logger.info("The game in room #{} is over.".format(room.getID()))
Exemple #8
0
    def init_players(self):
        print('GameBoard -- init_players')
        self.players = []
        self.players.append(
            Player(self.parameters[0]["name"], self.parameters[0]["position"]))
        self.human_player = self.players[0]

        for i in range(1, self.nb_players):
            from src.player.AI import AI
            self.players.append(
                AI(self.parameters[i]["name"], self.parameters[i]["position"],
                   self.parameters[i]["difficulty"], self, self.game_rules))
        self.current_player = 0

        self.players.sort(key=lambda x: int(x.position), reverse=False)

        self.help_text = GameStateString.get_text(
            GameState.PLAYER_TURN,
            self.get_current_player().nickname)
 def addPlayer(self, name, userId):
     player = Player(name)
     self.playerList[userId] = player
def create_player(name):
    return Player(name=name,
                  health=PLAYER_HEALTH,
                  max_food=PLAYER_MAX_FOOD,
                  food=PLAYER_FOOD,
                  hunger=PLAYER_HUNGER)
Exemple #11
0
 def __init__(self):
     self.game_state = GameState.MENU
     self.last_state = GameState.MENU
     self.player = Player()
     self.rooms = []
Exemple #12
0
class Game:
    def __init__(self):
        self.game_state = GameState.MENU
        self.last_state = GameState.MENU
        self.player = Player()
        self.rooms = []

    def start(self):
        while self.game_state != GameState.EXIT:
            self.clear_screen()
            if self.game_state == GameState.MENU:
                print(Scripts.menu)
                user = input("Enter menu: ")
                if user.__eq__("P") or user.__eq__("p"):
                    self.game_state = GameState.PLAY
                elif user.__eq__("H") or user.__eq__("h"):
                    self.game_state = GameState.HELP
                elif user.__eq__("A") or user.__eq__("a"):
                    self.game_state = GameState.ABOUT
                elif user.__eq__("E") or user.__eq__("e"):
                    self.game_state = GameState.EXIT
                else:
                    print("Invalid input")
            elif self.game_state == GameState.PLAY:
                self.clear_screen()
                print(self.rooms[self.player.currRoom].info)
                user = input("What to do? ")
                words = user.split()
                if words[0].__eq__("use"):
                    self.rooms[self.player.currRoom].trigger(words[1], self)
                elif (words[0].__eq__("open") and words[1].__eq__(
                        self.rooms[self.player.currRoom].door.name)):
                    self.rooms[self.player.currRoom].open_door(self)
                elif words[0].__eq__("back"):
                    if self.player.currRoom == 0:
                        print("There is no previous room.")
                    elif self.player.currRoom > 0:
                        self.player.currRoom -= 1
                        print("You go back.")
                elif words[0].__eq__("take") and words[1].__eq__("out"):
                    self.player.find(words[2])
                elif words[0].__eq__("inventory"):
                    for item in self.player.inventory.values():
                        print(f"Item: {item.name}")
                        print(item.info)
                elif words[0].__eq__("help"):
                    self.last_state = GameState.PLAY
                    self.game_state = GameState.HELP
                elif words[0].__eq__("exit"):
                    self.game_state = GameState.EXIT
                else:
                    print(
                        f"Command {words[0]} not found! Enter \'help\' to see the\n"
                        + "command list.")
                input("Press enter to continue...")

            elif self.game_state == GameState.HELP:
                self.clear_screen()
                print(Scripts.help_menu)
                input("Press enter to go back..")
                self.game_state = self.last_state
            elif self.game_state == GameState.ABOUT:
                self.clear_screen()
                print(Scripts.about_menu)
                input("Press enter to go back..")
                self.game_state = GameState.MENU

    def add_room(self, room):
        self.rooms.append(room)

    def clear_screen(self):
        if platform.system().__eq__("Linux"):
            os.system("clear")
        elif platform.system().__eq__("Windows"):
            os.system("cls")
        else:
            print("Error. You OS is not supported!")
            exit(self, 69)
Exemple #13
0
 async def __gameOver(winner: Player, loser: Player):
     HttpPipe.addWin(winner.getId())
     await winner.disconnect()
     HttpPipe.addGame(loser.getId())
     await loser.disconnect()