def changeName(self):
     # Check that no names are duplicated.
     name2 = "Bob" + str(random.randint(101, 999))
     self.note =self.note + ' ' + self._state.name + ' you shall now be named: ' + name2
     # it is possible (though unlikely) that two players might still end up with the
     # same name due to timing, (or 1/898 chance that the same Bob name is chosen)
     # but we do not deal with these corner cases.
     self._state.name = name2
     connection.Send({"action": "displayName", "name": name2})
     return name2
def get_users(ip):
    network_listener = NetworkListener(ip, 4330)
    Player_ID = 0
    while (True):
        connection.Pump()
        if Player_ID != 0:
            connection.Send({'action': 'top'})
        network_listener.Pump()
        if server_state['action'] == 'top':
            return (server_state['users'], server_state['users'][-1])
Exemple #3
0
 def Network_truco_asked(self, data):
     self.truco_asked = True
     self.just_asked = False
     self.team_mate_asked_truco = False
     cards = self.prepare_to_send_cards(self.me.hand)
     connection.Send({
         "action": "show_team_mate",
         "cards": cards,
         "player": self.num
     })
Exemple #4
0
 def Network_secondConnection(self, data):
     #Get the game ID and player number from the data
     #Set the second player's board equal to the first
     self.gameID = data["gameID"]
     self.player = data["player"]
     self.obstructions = self.unpackage(data["obstructions"])
     self.points = self.unpackage(data["points"])
     self.extrapoints = self.unpackage(data["extrapoints"])
     self.TOTALSCORE = len(self.points) + len(self.extrapoints) * 3
     connection.Send({"action": "start", "gameID": self.gameID})
Exemple #5
0
 def Network_initGame(self, data):
     #Get the game ID and player number from the data
     self.gameID = data["gameID"]
     self.player = data["player"]
     #Set the second player's board equal to the first
     if (self.player == 1):
         self.obstructions = self.unpackage(data["obstructions"])
         self.points = self.unpackage(data["points"])
         self.extrapoints = self.unpackage(data["extrapoints"])
         connection.Send({"action": "start", "gameID": self.gameID})
Exemple #6
0
 def send_challenge(self, otherPlayerId, playerName):
     if not self.pending_challenge:
         self.game_message = "Waiting for a response from {}".format(
             playerName)
         self.pending_challenge = PendingChallenge(otherPlayerId, self.id,
                                                   playerName)
         connection.Send({
             "action": "getChallenge",
             "id": self.id,
             "otherPlayer": int(otherPlayerId)
         })
Exemple #7
0
    def VerifyData(self):
        name = self.slots['name input'].GetText()
        password = self.slots['password input'].GetText()

        connection.Send({
            'action': 'Login',
            'name': name,
            'password': password
        })

        self.Die()
Exemple #8
0
 def send_action(self, action):
     # sends a specified action to the server
     if self.player == 0:
         return
     if self.player == 1:
         player = self.p1
     else:
         player = self.p2
     Pos = [player.Pos.x,player.Pos.y]
     angle = player.angle
     connection.Send({"action": action, "p": 'p'+str(self.player), "p_pos": Pos,'ang':angle})
Exemple #9
0
 def play_card(self, card_index):
     if self.me.turn and self.just_played <= 0:
         self.just_played = 300
         self.me.turn = False
         card = self.me.playCard(card_index)
         self.board_cards[self.num] = card
         connection.Send({
             "action": "play_card",
             "card": card.__dict__,
             "player": self.num
         })
Exemple #10
0
 def on_event(self, event):
     if event.type == pygame.QUIT:
         self._running = False
     elif event.type == pygame.KEYDOWN:
         if event.key == pygame.K_SPACE:
             self.dice.roll()
         elif event.key == pygame.K_ESCAPE:
             self.init_pieces()
     else:
         self.handle_piece_events(event)
         if event.type == pygame.MOUSEMOTION:
             connection.Send({'action': 'mousemotion', 'pos': event.pos})
Exemple #11
0
 def UpdateShip(self):
     if self.playerId > -1:
         playerShip = self.world.getPlayerShip()
         connection.Send({
             "action": "update_player",
             "player_id": self.playerId,
             "x": playerShip.getX(),
             "y": playerShip.getY(),
             "velocityX": playerShip.getVelocityX(),
             "velocityY": playerShip.getVelocityY(),
             "rotation": playerShip.getRotation()
         })
Exemple #12
0
 def update_game_state_with_move(self, start_row, start_column, end_row,
                                 end_column):
     connection.Send({
         "action": "updateBoard",
         "move": {
             "startRow": start_row,
             "startColumn": start_column,
             "endRow": end_row,
             "endCol": end_column
         },
         "id": self.id
     })
Exemple #13
0
 def __init__(self, host, port, name="ANON", sort_hand_ascending=False):
     self.Connect((host, port))
     print("Oh Hell client started")
     print("Ctrl-C to exit")
     self.name = name
     self.gb = None
     # get a nickname from the user before starting
     connection.Send({
         "action": "name",
         "name": name,
         'reverse_sort': sort_hand_ascending
     })
Exemple #14
0
 def Network_roll(self, data):
     self.slot_machine = data["rolls"]
     num = data["num"]
     self.move = self.slot_machine.count(True)
     if data["hasRolled"]:
         self.hasRolled = True
     if self.move == 0 and self.hasRolled and num == self.player_num:
         connection.Send({
             "action": "lorTurn",
             "lorTurn": "lost",
             "num": self.player_num
         })
Exemple #15
0
 def menu_pause(self, escapePressed, touches):
     # Menu pause et la touche escape
     if (touches[K_ESCAPE]):
         if not escapePressed:
             escapePressed = True
             connection.Send({
                 "action": "pause",
                 "idJoueur": self.idServeur
             })
     else:
         escapePressed = False
     return escapePressed
Exemple #16
0
    def Network_connected(self, data):
        if verbose:
            print("connected to the server")

        self.connected = True
        self.recievedping = True
        global numthreads
        connection.Send({
            'action': 'nickname',
            'nick': name,
            'cores': numthreads
        })
 def __init__(self, host, port):
     self.Connect((host, port))
     print("Chat client started")
     print("Ctrl-C to exit")
     # get a nickname from the user before starting
     print("Enter your nickname: ")
     connection.Send({
         "action": "nickname",
         "nickname": stdin.readline().rstrip("\n")
     })
     # launch our threaded input loop
     t = start_new_thread(self.InputLoop, ())
Exemple #18
0
 def UpdateObjectOnServer(self, game_object):
     print(f"UpdateObjectOnServer({game_object.object_hash})")
     if game_object.remote_object:
         raise ValueError(
             f"tried to update remote object: " +
             f"{type(game_object).__name__}/{game_object.object_hash}")
     connection.Send({
         "action": "updateobjectonserver",
         "object_hash": game_object.object_hash,
         "position": game_object.position,
         "direction": game_object.direction
     })
    def playing(self):
        if self.turn:
            self.print_valid_moves(self.valid_moves)

            self.game.curr_player.play_move(self.valid_moves, self.game.deck)
            if self.game.curr_player.is_last_card(self.game.deck):
                connection.Send({
                    "action": "last_card",
                    "is_last_card": True,
                    'p_id': self.id
                })
            if self.game.curr_player.has_won():
                connection.Close()
            connection.Send({
                "action":
                "next",
                "game_obj": (pickle.dumps(self.game).decode('latin-1'))
            })

            self.turn = self.changeturn()
            print()
Exemple #20
0
 def getInput(self):
     #Check if the user exited
     if self.exitnext:
         pygame.quit()
         sys.exit()
     if self.escapenext:
         self.escapenext = False
         self.gamestate = "mainmenu"
         self.connectionstate = ""
     for event in pygame.event.get():
         if event.type == QUIT:
             if (self.connectionstate == "connected"):
                 connection.Send({
                     "action": "exit",
                     "player": self.player,
                     "gameID": self.gameID
                 })
             self.exitnext = True
         if event.type == KEYDOWN:
             if event.key == K_LALT or event.key == K_RALT:
                 self.alt = True
             if event.key == K_F4 and self.alt:
                 if (self.connectionstate == "connected"):
                     connection.Send({
                         "action": "exit",
                         "player": self.player,
                         "gameID": self.gameID
                     })
                 self.exitnext = True
             if event.key == K_ESCAPE and self.gamestate != "mainmenu":
                 if (self.connectionstate == "connected"):
                     connection.Send({
                         "action": "exit",
                         "player": self.player,
                         "gameID": self.gameID
                     })
                 self.escapenext = True
         if event.type == KEYUP:
             if event.key == K_LALT:
                 self.alt = False
Exemple #21
0
	def InputLoop(self, q):
		console = HistoryConsole(locals())
		# horrid threaded input loop
		# continually reads from stdin and sends whatever is typed to the server
		quit = False
		while not quit:
			print q.get(block=True),
			try:
				sendcommand = console.raw_input("I8BP:" + self.hostname + "> ")
				connection.Send({"action": "console", "command": sendcommand, "id": self.playerid})
			except EOFError:
				print
				quit = True
Exemple #22
0
 def __init__(self, addr="localhost", port=25565):
     self.blockdata = {}
     self.newdata = []
     self.nicknamereceived = False
     self.Connect((addr, port))
     print "Client started"
     print "Ctrl-C to exit"
     # get a nickname from the user before starting
     print "request"
     connection.Send({"action": "nicknamerequest", "value": "1"})
     print "request"
     # launch our threaded input loop
     t = start_new_thread(self.InputLoop, ())
Exemple #23
0
 def Network_changesquare(self,data):
   #print for testing purposes
     print("CHANGING SQUARE")
     #setting the current square array at place zero to the value for x
     self.currentsquare[0] = data['x']
     #setting the current square array at place one to the value for y 
     self.currentsquare[1] = data['y']
     #added to capture counter
     #setting the current square array at place one to the value for counter
     self.currentsquare[2] = data['counter']
     #setting the xcoord variable to the x value in the array
     xcoord = self.currentsquare[0]
     #setting the ycoord variable to y value in the
     ycoord = self.currentsquare[1]
     
     #determining position of the square in arrayofcoords
     for i in range(len(arrayofcoords[0])):
       for j in range(len(arrayofcoords[0])):
         if xcoord == arrayofcoords[0][j] and ycoord == arrayofcoords[1][j]:
           #setting position as where the action tile was found
           self.position = j
           #break out of the loop if the position is required
           break
     # update values
     connection.Pump()
     client.Pump()
     #if position is in the first two
     if self.position <=1:
       #set the action value to be the tiles descrp 
       self.action = tilesdescrp[self.position]
          ############## ACCESS TO TILES 
       tiles[0][self.position] = tiles[1][self.position]
       game2(arrayofcoords,tiles,money,True,True)
       #testing purposes
       print("Client action: ", self.action)
     else:
       self.action = moneydescrp[self.position-2]
       money[0][self.position-2] = money[1][self.position-2]
       #self.points is an array
       game2(arrayofcoords,tiles,money,True,True,self.points[self.num-1],self.rounds)
       #testing purposes
       print("Client action: ", self.action)
     
     #sending the action back to the server
       #is self.num 2 for player 2 or 1???
       # player 2 for player 2 
     connection.Send({'action':'actiontodo','actionsarray':self.action, 'number':self.num})
     #Pumping the server and the client to ensure they receive new data
     connection.Pump()
     client.Pump()
Exemple #24
0
 def Network_forceGamestateUpdate(self, data):
     #resend all info to server upon a new player joining so that they have initial states
     self.Send({"action": "badgeUpdate", "badges": self.badges.badges})
     connection.Send({
         "action": "updatePos",
         "x": self.x,
         "y": self.y,
         "sprite": self.sprite
     })
     self.Send({"action": "mapChange", "newMap": self.currMap})
     self.Send({
         "action": "pokedexUpdate",
         "lockouts": self.pokedex.createLockouts()
     })
Exemple #25
0
 def updatePos(self):
     newx = self.pyboy.get_memory_value(0xD362)
     newy = self.pyboy.get_memory_value(0xD361)
     if self.sprite != self.getViewSprites(0):
         #if self.y != newy or self.x != newx:
         self.y = newy
         self.x = newx
         self.sprite = self.getViewSprites(0)
         connection.Send({
             "action": "updatePos",
             "x": self.x,
             "y": self.y,
             "sprite": self.sprite
         })
    def __init__(self, host, port=8080, nickname="nobody"):
        """ """
        super(ClientPlayLayer, self).__init__()

        self.host = host
        self.port = port

        if None == self.host:
            self.host = ClientPlayLayer.ownID
        if None == self.port:
            self.port = 8080

        self.client = ClientPlayLayerClient(self.host, self.port)
        connection.Send({"action": "nickname", "nickname": nickname})
    def setName(self):
        """Set up a display name and send it to the server"""

        # to prevent duplicate names, displayname = 'guest' is forbidden.
        # Forbidden names are defined at the beginning of this controller.
        # May as well allow other names to be forbidden, too (for fun :) )
        # if name is in list of forbidden names, then changeName is called.
        displayName = input("Enter a display name: ")
        if displayName in Forbidden_Names:
            self.note = "Sorry, but the name "+displayName+" is forbidden."
            self.changeName()
        else:
            self._state.name = displayName
            connection.Send({"action": "displayName", "name": displayName})
    def Network_changesquare(self, data):
        self.currentsquare[0] = data['x']
        self.currentsquare[1] = data['y']
        ########## added to capture counter
        self.currentsquare[2] = data['counter']
        print("Received the updated square")
        print(self.currentsquare)
        xcoord = self.currentsquare[0]
        print("X co-ordinate")
        print(xcoord)
        ycoord = self.currentsquare[1]
        print("Y co-ordinate")
        print(ycoord)

        ############################
        #determining position of the square in arrayofcoords
        for i in range(len(arrayofcoords[0])):
            for j in range(len(arrayofcoords[0])):
                if xcoord == arrayofcoords[0][j] and ycoord == arrayofcoords[
                        1][j]:
                    position = j
                    break
        print("Position of the co-ordinate in array")
        print(position)
        #determine what square the user has
        if position <= 1:
            self.action = tilesdescrp[position]
            ###################
            print("Client action: ", self.action)
        else:
            self.action = moneydescrp[position - 2]
            ##############
            print("Client action: ", self.action)
        #print(self.action)
        #send the action back
        #self.actions[self.playnum-1] = action
        #update self.actions
        ####### send a different action through
        #connection.Send({"action": "playready", "playr": self.num})
        #connection.Send({'action': 'presskey', 'pressplay': self.num})
        print("bEFORE SEND")
        connection.Send({
            'action': 'actiontodo',
            'actionsarray': self.action,
            'number': self.num
        })
        connection.Pump()
        client.Pump()
        print("AftER SEnd")
Exemple #29
0
	def __init__(self, host, port):
		self.hostname = host
		self.Connect((host, port))
		print "I8BP console started"
		# fetch the player ID from infinite platformer config
		self.playerid = config.Get("playerID", default=None)
		print "using PlayerID:", self.playerid
		# pass results back to the input thread
		self.q = Queue()
		# launch our threaded input loop
		self.t = Thread(target=self.InputLoop, args=(self.q,))
		self.t.daemon = True
		self.t.start()
		# initiate the connection with our ID
		connection.Send({"action": "admin", "id": self.playerid})
Exemple #30
0
 def RegisterObjectWithServer(self, game_object):
     print(f"RegisterObjectWithServer({game_object.object_hash})")
     if game_object.remote_object:
         raise ValueError(
             f"tried to register remote object: " +
             f"{type(game_object).__name__}/{game_object.object_hash}")
     connection.Send({
         "action": "registerobjectwithserver",
         "nickname": game_object.nickname,
         "object_hash": game_object.object_hash,
         "position": game_object.position,
         "direction": game_object.direction,
         "color": game_object.color,
         "class": type(game_object).__name__
     })