Exemplo n.º 1
0
 def Network_error(self, data):
     # Notifies client of fatal network error
     self.ready = False
     import traceback
     traceback.print_exc()
     self.statusLabel = data['error'][1]
     connection.Close()
Exemplo n.º 2
0
 def Network_error(self, data):
     print('ERROR', data)
     import traceback
     traceback.print_exc()
     # вывести информацию об ошибке в строку состояния:
     self.statusLabel = data['error'][1]
     # в случае ошибки закрыть соединение
     connection.Close()
Exemplo n.º 3
0
 def Network_error(self, data):
     if (self.game.connecting or self.game.connected):
         self.game.connecting = False
         if (type(data['error']) == ConnectionRefusedError):
             api.send_message('[{}] {}'.format(data['error'].errno,
                                               data['error'].strerror),
                              color=(255, 50, 70))
         else:
             api.send_message('[{}] {}'.format(*data['error']),
                              color=(255, 50, 70))
         connection.Close()
Exemplo n.º 4
0
 def run(self):
     while not self.pyboy.tick():
         if self.gameOptions:
             self.checkMapChange()
             if self.gameOptions["position"]:
                 self.updatePos()
                 self.checkRivalInView()
             if self.gameOptions["items"]:
                 self.missableObjectsFlags()
             if self.gameOptions["wilds"]:
                 self.checkPokedexUpdate()
                 self.checkInBattleIfLockedOut()
             if self.gameOptions["badge_win"]:
                 self.sendBadgesIfChanged()
         connection.Pump()
         self.Pump()
     connection.Close()
Exemplo n.º 5
0
    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.has_won():
                connection.Close()
            connection.Send({
                "action":
                "next",
                "game_obj": (pickle.dumps(self.game).decode('latin-1'))
            })

            # print('*'*50, "game object self.game before sending", self.game)
            # print("self.turn before is ", self.turn)
            # print("game cards in hand", id(self.game))
            self.turn = self.changeturn()
            # print("self.turn is ", self.turn)
            print()
Exemplo n.º 6
0
    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()
Exemplo n.º 7
0
 def Network_error(self, data):
     print('Error:', data)
     connection.Close()
 def CloseNetwork(self):  #called when we want to close network
     print "Disconnected from server"
     self.start_pump = False
     connection.Close()
Exemplo n.º 9
0
 def Network_error(self, data):
     print('error:', data['error'][1])
     connection.Close()
Exemplo n.º 10
0
 def Network_disconnected(self, data):
     print("disconnected from the server")
     connection.Close()
     exit()
Exemplo n.º 11
0
 def Network_error(self, data):
     print self.playerID, 'error:', data['error'][1]
     self.serverconnection = 2
     connection.Close()
Exemplo n.º 12
0
 def Network_error(self, data):
     print(f"{data['error'][0]} Error: {data['error'][1]}")
     connection.Close()
Exemplo n.º 13
0
 def close(self):
     connection.Close()
Exemplo n.º 14
0
def start(display, login, ip):
    global client_display, user_state, server_state, Player_ID, is_exit, user_login, player1_stats, player2_stats
    client_display = display
    user_login = login

    is_exit = False

    # Instantiate clock to help control the framerate.
    client_clock = pygame.time.Clock()

    # Background color of the game pad.

    # Font object for rendering text onto display surface.
    fnt = pygame.font.SysFont("Arial", 14)

    hull_surf = pygame.image.load('hull.png').convert()
    hull_surf.set_colorkey((255, 255, 255))
    hull_surf = pygame.transform.rotate(hull_surf, -90)

    turret_surf = pygame.image.load('turret.png').convert()
    turret_surf.set_colorkey((255, 0, 0))
    turret_surf = pygame.transform.rotate(turret_surf, -90)

    field_surf = pygame.image.load('th.jpeg').convert()
    #field_surf = pygame.transform.chop(field_surf, pygame.Rect(0, 0, 300, 300))

    Player_ID = 0

    parser = argparse.ArgumentParser(description='Input client parameters.')
    # Example IP address used here; edit this line.
    print(ip)
    parser.add_argument('serverIP', type=str, nargs='?', default=ip)
    args = parser.parse_args()
    print("args:", args.serverIP)

    # Initialize the state dictionary
    user_state = {}
    server_state = {}

    # Note, the connection can take place in the NetworkListener or here.
    # This "connection" is an instatiation of the EndPoint class that is done in the Connection.py file.
    # Note, if you do this here, you have to call the "DoConnect" method, not the "Connect" method that
    # is indicated on the web site.
    # connection.DoConnect((args.serverIP, 4330))
    #connection.DoConnect((args.serverIP, 4330))
    network_listener = NetworkListener(args.serverIP, 4330)

    framerate_limit = 30
    flip_timer = 0.0

    print(Player_ID)

    while True:

        dt_s = float(client_clock.tick(framerate_limit) * 1e-3)
        # client_clock.tick(framerate_limit)

        connection.Pump()
        if Player_ID != 0:
            #print "user_state", user_state
            connection.Send(user_state)

        object_methods = [
            method_name for method_name in dir(connection)
            if callable(getattr(connection, method_name))
        ]

        network_listener.Pump()

        checkforUserInput(user_state)
        if is_exit:
            connection.Close()
            object_methods = [
                method_name for method_name in dir(network_listener)
                if callable(getattr(network_listener, method_name))
            ]
            print('close')
            player1_stats = None
            player2_stats = None
            break

        client_display.fill((0, 0, 0))
        #ClearWindow(display, field_surf)

        DrawWalls()
        if 'tanks' in server_state:
            for tank_data in server_state['tanks']:
                DrawImage(hull_surf, tank_data[0], tank_data[1], tank_data[2])

        if 'turrets' in server_state:
            for turret in server_state['turrets']:
                DrawImage(turret_surf, turret[0], turret[1], turret[2])

        if 'bullets' in server_state:
            for bullet in server_state['bullets']:
                pygame.draw.circle(client_display, (255, 0, 0),
                                   (bullet[0], bullet[1]), round(bullet[2]))

        if 'healths' in server_state:
            #print(Player_ID)
            position1 = (server_state['tanks'][0][0],
                         server_state['tanks'][0][1])
            DrawHealth(position1, (Player_ID == 1),
                       server_state['healths'][0] / 200)
            position2 = (server_state['tanks'][1][0],
                         server_state['tanks'][1][1])
            DrawHealth(position2, (Player_ID == 2),
                       server_state['healths'][1] / 200)
            #print(server_state['healths'][0])
        if 'kills' in server_state:
            kill1 = server_state['kills'][0]
            kill2 = server_state['kills'][1]
            color1 = (255, 0, 0)
            color2 = (0, 255, 0)
            if Player_ID == 1:
                color1, color2 = color2, color1
            DrawKills('kills = ' + str(kill1), display, 25, color1, 50, 825)
            if player1_stats != None and player1_stats.username != '':
                DrawKills(
                    'player: ' + player1_stats.username + ' ' +
                    str(player1_stats.killed) + '/' + str(player1_stats.died),
                    display, 25, color1, 150, 825)
            DrawKills('kills = ' + str(kill2), display, 25, color2, 750, 825)
            if player2_stats != None and player2_stats.username != '':
                DrawKills(
                    'player: ' + player2_stats.username + ' ' +
                    str(player2_stats.killed) + '/' + str(player2_stats.died),
                    display, 25, color2, 650, 825)

        pygame.display.update()
Exemplo n.º 15
0
 def Network_error(self, data):
     logging.error('error:', data['error'][1])
     connection.Close()
Exemplo n.º 16
0
 def Disconnect(self):
     if self.serverconnection == 1:
         print self.playerID, 'disconnecting randomly'
         connection.Close()
     self.serverconnection = 2
Exemplo n.º 17
0
 def Network_error(self, data):
     print "Error:", data["error"][1]
     connection.Close()
Exemplo n.º 18
0
 def Network_ping(self, data):
     print("got:", data)
     if data["count"] == 10:
         connection.Close()
     else:
         connection.Send(data)
Exemplo n.º 19
0
 def Network_connectionDenied(self, data):
     """Server denied the connection, likely due to a game already in progress"""
     print('Server denied connection request')
     self.note = "Server denied connection request :("
     connection.Close()
Exemplo n.º 20
0
 def Disconnect(self):
     if self.serverconnection == 1:
         connection.Close()
     self.serverconnection = 2
Exemplo n.º 21
0
 def Network_error(self, data):
     print(data)
     self.statusLabel = data['error'][1]
     connection.Close()
Exemplo n.º 22
0
 def Network_error(self, data):  #called when a tryConnection fail
     print "error ", data["error"]
     self.networkErrorDef(
         data["error"]
     )  #call our error function that handles what happends when there is an error
     connection.Close()  #close connection
Exemplo n.º 23
0
 def Network_error(self, data):
     print('[error] ', data['error'])
     connection.Close()
Exemplo n.º 24
0
 def Network_error(self, data):
     print(data)
     import traceback
     traceback.print_exc()
     self.statusLabel = data['error'][1]
     connection.Close()
Exemplo n.º 25
0
 def Network_error(self, data):
     print 'error:', data['error'][1]
     connection.Close()
     sys.exit()