def _get_msg_from_server_socket (self):
		""" Function doc """

		try:
			print("Blocked: wait for msg from server...")
			msg = ttc.get_msg_from_socket(self.s)
			return msg

		except Exception as exp:
			ttc.d("2 {}".format(exp))
			self.show_error_dialog(str(exp))
			self.on_TicTacToeWindow_delete_event(self.TicTacToeWindow, "delete-event")
Пример #2
0
    def _get_msg_from_server_socket(self):
        """ Function doc """

        try:
            print("Blocked: wait for msg from server...")
            msg = ttc.get_msg_from_socket(self.s)
            return msg

        except Exception as exp:
            ttc.d("2: {}".format(exp))
            self.show_error_dialog(str(exp))
            self.on_TicTacToeWindow_delete_event(self.TicTacToeWindow,
                                                 "delete-event")
Пример #3
0
    def _get_client_socket(self):
        """
		return client socket connected to the server. fail if error with msg
		"""

        self.statusbar.push(0, "Connecting to the server...")

        try:
            s = ttc.get_client_socket(exception=True)
            self.statusbar.push(0, "Connected")

            greeting = ttc.get_msg_from_socket(s)
            ttc.d(greeting)

        except Exception as exp:
            ttc.d("1 {}".format(exp))
            self.show_error_dialog(str(exp))
            sys.exit(1)

        return s
Пример #4
0
    def _get_client_socket(self):
        """
		return client socket connected to the server. fail if error with msg
		"""

        self.statusbar.push(0, "Connecting to the server...")

        try:
            s = ttc.get_client_socket(exception=True)
            self.statusbar.push(0, "Connected")

            greeting = ttc.get_msg_from_socket(s)
            ttc.d(greeting)

        except Exception as exp:
            ttc.d("1 {}".format(exp))
            self.show_error_dialog(str(exp))
            sys.exit(1)

        return s
def main():

	s = get_server_socket()

	try:
		### endless loop, for multiple linear games
		while True:

			print ('Waiting for a player...')
			(clientsocket, address) = s.accept() # blocking line
			print ('New player came from {0}\n'.format(address))
			clientsocket.sendall("Tic Tac Toe server greeting you!\nYou are Welcome!")

			gf = copy.deepcopy(ttc.GAME_FIELD)

			### one game, loop until winner or disconnect
			while True:


				#B get user's turn
				try:
					print("Wait for user's turn...")
					user_step = ttc.get_msg_from_socket(clientsocket, exception=True, ex=False)
				except Exception as exp:
					ttc.d(exp)
					break;


				# validate step #
				step_check = {}

				ttc.d("user raw turn: {}".format(user_step))
				#user_turn_json_index = ttc.convert_json_turn_human_to_machine(user_step)
				#ttc.d("user turn in term of indexes: {}".format(user_turn_json_index))

				# thus, if True -> error = False
				step_check["error"] = not ttc.is_step_correct(user_step, gf) 


				if not step_check["error"]:
					ttc.apply_turn(user_step, gf, ttc.USER_RAW_STEP)
					step_check["winner"] = get_winner(gf)
					ttc.print_game_field(gf)
				else:
					step_check["winner"] = 0


				#B answer, is step correct #
				step_check_str = json.dumps(step_check)
				ttc.d("I will send: {0}".format(step_check_str))
				clientsocket.sendall(step_check_str)
				time.sleep(0.1)


				# if an error occured earlier -- get new answer from user
				if True == step_check["error"] or 0 != step_check["winner"]:
					continue;

				# do server step #
				ttc.d("proceed server turn")

				server_step_dict = do_server_step(gf)
				ttc.d("server step: {}".format(server_step_dict))
				ttc.apply_turn(json.dumps(server_step_dict), gf, ttc.SERVER_RAW_STEP)



				# check for winners
				server_step_dict["winner"] = get_winner(gf)
				server_step_dict["error"]  = False


				#B send server turn with winner result
				clientsocket.sendall( json.dumps(server_step_dict) )


				ttc.print_game_field(gf)


	except KeyboardInterrupt as exp:
		print ("\nShutting down... {0}".format(exp))
	except Exception as exp:
		print("Sorry, but: {0}".format(exp))
	except:
		print("Unexpected error:", sys.exc_info()[0])



	try:
		clientsocket.close()
		s.close()
	except Exception as exp:
		# not an error on most cases
		ttc.d("may be you will be interested, but {0}".format(exp))

	sys.exit(0)
Пример #6
0
def main():

    s = ttc.get_client_socket()

    try:
        # Recebe mensagem de olá
        hello_msg = ttc.get_msg_from_socket(s)
        print("\n{0}\n".format(hello_msg))

        print('''
Você é a cruz/o xis (X).
Entre com as coordenadas, onde você deseja colocar o X.
Exemplo, canto do topo a esquerda será (0, 0).
No seguinte formato: <numero> <numero> <aperte Enter>
''')
        gf = copy.deepcopy(ttc.GAME_FIELD)
        ttc.print_game_field(gf)

        ### Loop do jogo até ter um ganhador ou CTRL+C
        while True:

            #Pega a jogada do usuário
            turn_json = ttc.get_turn_from_user(gf)

            #Manda a jogada ao servidor
            s.sendall(turn_json.encode(encoding='utf-8'))

            #Pega a resposta do servidor sobre a jogada do usuario
            res = ttc.get_msg_from_socket(s, exception=False, ex=True)

            # se for um erro, pergunta a jogada normalmente
            if is_error_in_answer(res):
                print(
                    "Servidor não está gostando da resposta, tente de novo.\n")
                continue
            else:
                ttc.apply_turn(turn_json, gf, ttc.USER_RAW_STEP)
                ttc.print_game_field(gf)

            # Procura por ganhadores, se tiver um o jogo termina
            handle_winner_variable(res)

            #Pega a jogada do servidor
            print("Esperando a resposta do servidor...")
            server_step = ttc.get_msg_from_socket(s)
            ttc.d("server step: {0}\n".format(server_step))
            ttc.apply_turn(server_step, gf, ttc.SERVER_RAW_STEP)
            handle_winner_variable(server_step)

            ttc.print_game_field(gf)

    except KeyboardInterrupt as k:
        print("\nDesligando... {0}".format(k))
    except Exception as exp:
        print(": {0}".format(exp))
        ttc.print_game_field(gf)
    except:
        print("Erro inesperado:", sys.exc_info()[0])

    s.close()
    sys.exit(0)
Пример #7
0
def main():

    s = ttc.get_client_socket()

    try:
        # get hello
        hello_msg = ttc.get_msg_from_socket(s)
        print("\n{0}\n".format(hello_msg))

        print('''
You are a cross (X).
Enter coordinats, where to put next cross.
Suppose, left top corner is (0, 0).
Input in format: <int> <int> <hit Return>
''')
        gf = copy.deepcopy(ttc.GAME_FIELD)
        ttc.print_game_field(gf)

        ### loop for a game, untill winner or ^C
        while True:

            #B get a step from user
            turn_json = ttc.get_turn_from_user(gf)

            #B send step to the server
            s.sendall(turn_json.encode('utf-8'))

            #B get server answer about user step
            res = ttc.get_msg_from_socket(s, exception=False, ex=True)

            # if error - ask step again
            if is_error_in_answer(res):
                print(
                    "Ou, server not pleasent about your answer, try again.\n")
                continue
            else:
                ttc.apply_turn(turn_json, gf, ttc.USER_RAW_STEP)
                ttc.print_game_field(gf)

            # check for winners in the answer, if exist any - game ends.
            handle_winner_variable(res)

            #B get server step
            print("Wait for server response...")
            server_step = ttc.get_msg_from_socket(s)
            ttc.d("server step: {0}\n".format(server_step))
            ttc.apply_turn(server_step, gf, ttc.SERVER_RAW_STEP)
            handle_winner_variable(server_step)

            ttc.print_game_field(gf)

    except KeyboardInterrupt as k:
        print("\nShutting down... {0}".format(k))
    except Exception as exp:
        print(": {0}".format(exp))
        ttc.print_game_field(gf)
    except:
        print("Unexpected error:", sys.exc_info()[0])

    s.close()
    sys.exit(0)
Пример #8
0
def main():

	s = get_server_socket()

	try:
		### endless loop, for multiple linear games
		while True:

			print ('Waiting for a player...')
			(clientsocket, address) = s.accept() # blocking line
			print ('New player came from {0}\n'.format(address))
			clientsocket.sendall("Tic Tac Toe server greeting you!\nYou are Welcome!")

			gf = copy.deepcopy(ttc.GAME_FIELD)

			### one game, loop until winner or disconnect
			while True:


				#B get user's turn
				try:
					print("Wait for user's turn...")
					user_step = ttc.get_msg_from_socket(clientsocket, exception=True, ex=False)
				except Exception as exp:
					ttc.d(exp)
					ttc.d("\n" + 40*"=" + "\n")
					break;


				# validate step #
				step_check = {}

				ttc.d("user raw turn: {}".format(user_step))
				#user_turn_json_index = ttc.convert_json_turn_human_to_machine(user_step)
				#ttc.d("user turn in term of indexes: {}".format(user_turn_json_index))

				# thus, if True -> error = False
				step_check["error"] = not ttc.is_step_correct(user_step, gf) 


				if not step_check["error"]:
					ttc.apply_turn(user_step, gf, ttc.USER_RAW_STEP)
					step_check["winner"] = get_winner(gf)
					ttc.print_game_field(gf)
				else:
					step_check["winner"] = 0


				#B answer, is step correct #
				step_check_str = json.dumps(step_check)
				ttc.d("I will send: {0}".format(step_check_str))
				clientsocket.sendall(step_check_str)
				time.sleep(0.1)


				# if an error occured earlier -- get new answer from user
				if True == step_check["error"] or 0 != step_check["winner"]:
					continue;

				# do server step #
				ttc.d("proceed server turn")

				server_step_dict = do_server_step(gf)
				ttc.d("server step: {}".format(server_step_dict))
				ttc.apply_turn(json.dumps(server_step_dict), gf, ttc.SERVER_RAW_STEP)



				# check for winners
				server_step_dict["winner"] = get_winner(gf)
				server_step_dict["error"]  = False


				#B send server turn with winner result
				clientsocket.sendall( json.dumps(server_step_dict) )


				ttc.print_game_field(gf)


	except KeyboardInterrupt as exp:
		print ("\nShutting down... {0}".format(exp))
	except Exception as exp:
		print("Sorry, but: {0}".format(exp))
	except:
		print("Unexpected error:", sys.exc_info()[0])



	try:
		clientsocket.close()
		s.close()
	except Exception as exp:
		# not an error on most cases
		ttc.d("may be you will be interested, but {0}".format(exp))

	sys.exit(0)
Пример #9
0
def main():

	s = ttc.get_client_socket()

	try:
		# get hello
		hello_msg = ttc.get_msg_from_socket(s)
		print("\n{0}\n".format(hello_msg))

		print('''
You are a cross (X).
Enter coordinats, where to put next cross.
Suppose, left top corner is (0, 0).
Input in format: <int> <int> <hit Return>
''')
		gf = copy.deepcopy(ttc.GAME_FIELD)
		ttc.print_game_field(gf)

		### loop for a game, untill winner or ^C
		while True:


			#B get a step from user
			turn_json = ttc.get_turn_from_user(gf)


			#B send step to the server
			s.sendall(turn_json)


			#B get server answer about user step
			res = ttc.get_msg_from_socket(s, exception=False, ex=True)


			# if error - ask step again
			if is_error_in_answer(res):
				print("Ou, server not pleasent about your answer, try again.\n")
				continue;
			else:
				ttc.apply_turn(turn_json, gf, ttc.USER_RAW_STEP)
				ttc.print_game_field(gf)


			# check for winners in the answer, if exist any - game ends.
			handle_winner_variable(res)


			#B get server step
			print("Wait for server response...")
			server_step = ttc.get_msg_from_socket(s)
			ttc.d("server step: {0}\n".format(server_step))
			ttc.apply_turn(server_step, gf, ttc.SERVER_RAW_STEP)
			handle_winner_variable(server_step)

			ttc.print_game_field(gf)


	except KeyboardInterrupt as k:
		print ("\nShutting down... {0}".format(k))
	except Exception as exp:
		print(": {0}".format(exp))
		ttc.print_game_field(gf)
	except:
		print("Unexpected error:", sys.exc_info()[0])


	s.close()
	sys.exit(0)
Пример #10
0
def main():

    s = get_server_socket()

    try:
        ### Loop infinito para multiplos jogos
        while True:

            print('Esperando um jogador...')
            (clientsocket, address) = s.accept()  # bloqueio de linha aqui
            print('Novo jogador vindo de {0}\n'.format(address))
            clientsocket.sendall(
                "Servidor de Jogo da velha!\nSeja bem vindo!".encode(
                    encoding='UTF-8'))

            gf = copy.deepcopy(ttc.GAME_FIELD)

            ### um jogo, loop termina caso haja um vencedor
            while True:

                #Pega a jogada do usuário
                try:
                    print("Esperando o turno do usuario")
                    user_step = ttc.get_msg_from_socket(clientsocket,
                                                        exception=True,
                                                        ex=False)
                except Exception as exp:
                    ttc.d(exp)
                    ttc.d("\n" + 40 * "=" + "\n")
                    break

                #valida jogada#
                step_check = {}

                ttc.d("user raw turn: {}".format(user_step))

                step_check["error"] = not ttc.is_step_correct(user_step, gf)

                if not step_check["error"]:
                    ttc.apply_turn(user_step, gf, ttc.USER_RAW_STEP)
                    step_check["winner"] = get_winner(gf)
                    ttc.print_game_field(gf)
                else:
                    step_check["winner"] = 0

                #B resposta se a jogada está correta #
                step_check_str = json.dumps(step_check)
                ttc.d("I will send: {0}".format(step_check_str))
                clientsocket.sendall(step_check_str.encode(encoding='UTF-8'))
                time.sleep(0.1)

                # se ocorrer um erro pede uma nova resposta do usuário
                if True == step_check["error"] or 0 != step_check["winner"]:
                    continue

                # Jogada do servidor#
                ttc.d("proceed server turn")

                server_step_dict = do_server_step(gf)
                ttc.d("server step: {}".format(server_step_dict))
                ttc.apply_turn(json.dumps(server_step_dict), gf,
                               ttc.SERVER_RAW_STEP)

                # Valida se há algum ganhador
                server_step_dict["winner"] = get_winner(gf)
                server_step_dict["error"] = False

                #B manda a jogada do servidor com a resposta de quem venceu
                clientsocket.sendall(
                    json.dumps(server_step_dict).encode(encoding='UTF-8'))

                ttc.print_game_field(gf)

    except KeyboardInterrupt as exp:
        print("\nDesligando... {0}".format(exp))
    except Exception as exp:
        print("Desculpas, mas: {0}".format(exp))
    except:
        print("Erro inesperado:", sys.exc_info()[0])

    try:
        clientsocket.close()
        s.close()
    except Exception as exp:
        # Não é um erro mas...
        ttc.d("Você podera se interessar, mas {0}".format(exp))

    sys.exit(0)