def on_TicTacToeWindow_delete_event(self, window, event):
		"""
		Close button press handler
		"""

		ttc.d("Close button pressed")
		self.s.close()

		gtk.main_quit()
Esempio n. 2
0
    def on_TicTacToeWindow_delete_event(self, window, event):
        """
		Close button press handler
		"""

        ttc.d("Close button pressed")
        self.s.close()

        gtk.main_quit()
Esempio n. 3
0
def get_winner(game_field):
    """
	Analyze game (@game_field) and check, if a Winner exist.

	Return
		0 : nobody
		1 : user one (server | zero  | 5)
		2 : user two (client | cross | 2)
		3 : tie (no more free space)
	"""

    winner = 0
    gf = game_field  # weak reference

    empty = ttc.EMPTY_RAW_STEP  # 1
    cross = ttc.USER_RAW_STEP  # 2
    zeros = ttc.SERVER_RAW_STEP  # 5

    length = len(game_field)

    try:
        ### check for a winner

        # by rows and cols...
        for j in range(length):
            row = [gf[j][i] for i in range(length)]
            col = [gf[i][j] for i in range(length)]
            if col.count(cross) == length or row.count(cross) == length:
                winner = 2
                raise Exception("User wins!")
            elif col.count(zeros) == length or row.count(zeros) == length:
                winner = 1
                raise Exception("Server wins!")

        # by diagonals
        for diag in [[gf[0][0], gf[1][1], gf[2][2]],
                     [gf[0][2], gf[1][1], gf[2][0]]]:
            if diag.count(cross) == length:
                winner = 2
                raise Exception("User wins!")
            elif diag.count(zeros) == length:
                winner = 1
                raise Exception("Server wins!")

        ### check for tie, by counting empty cells on every line
        empty_count = 0
        for line in game_field:
            empty_count += line.count(empty)
        if 0 == empty_count:
            winner = 3
            raise Exception("TIE! no more free space")

    except Exception as ex:
        # do nothing, just goto
        ttc.d(ex)

    return winner
Esempio n. 4
0
def is_error_in_answer(msg):

    try:
        ttc.d("your step validation: {0}".format(msg))
        tmp = json.loads(msg)

        if tmp["error"] == 1:
            return True

    except Exception as exp:
        print("eeem, {0}".format(exp))
        return False
	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")
Esempio n. 6
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")
Esempio n. 7
0
def get_winner(game_field):

    winner = 0
    gf = game_field  # weak reference

    empty = ttc.EMPTY_RAW_STEP  # 1
    cross = ttc.USER_RAW_STEP  # 2
    zeros = ttc.SERVER_RAW_STEP  # 5

    length = len(game_field)

    try:
        ### verifica se há ganhador

        # pelas colunas e linhas
        for j in range(length):
            row = [gf[j][i] for i in range(length)]
            col = [gf[i][j] for i in range(length)]
            if col.count(cross) == length or row.count(cross) == length:
                winner = 2
                raise Exception("User wins!")
            elif col.count(zeros) == length or row.count(zeros) == length:
                winner = 1
                raise Exception("Server wins!")

        # pelas diagonais
        for diag in [[gf[0][0], gf[1][1], gf[2][2]],
                     [gf[0][2], gf[1][1], gf[2][0]]]:
            if diag.count(cross) == length:
                winner = 2
                raise Exception("User wins!")
            elif diag.count(zeros) == length:
                winner = 1
                raise Exception("Server wins!")

        ### verifica por empate contando os espaços vazios nas colunas
        empty_count = 0
        for line in game_field:
            empty_count += line.count(empty)
        if 0 == empty_count:
            winner = 3
            raise Exception("Empate, sem campos vazios")

    except Exception as ex:
        # do nothing, just goto
        ttc.d(ex)

    return winner
Esempio n. 8
0
    def convert_str_to_json_dict_step(self, data):
        """
		"""
        ttc.d("convert input: {}".format(data))

        parts = re.split("\s*", data)
        row = int(float(parts[0]))
        col = int(float(parts[1]))

        answer = {}
        answer["step"] = [row, col]
        turn_json = json.dumps(answer)

        ttc.d("convert result: {}".format(turn_json))

        return turn_json
	def convert_str_to_json_dict_step (self, data):
		"""
		"""
		ttc.d("convert input: {}".format(data))

		parts = re.split("\s*", data)
		row = int(float(parts[0]))
		col = int(float(parts[1]))

		answer = {}
		answer["step"] = [row, col]
		turn_json = json.dumps(answer)

		ttc.d("convert result: {}".format(turn_json))

		return turn_json
Esempio n. 10
0
def handle_winner_variable(res):

    try:
        tmp = json.loads(res)
        winner = tmp["winner"]

        if 0 == winner:
            pass
        elif 1 == winner:
            raise Exception("Desculpas, mas você perdeu... =\\")
        elif 2 == winner:
            raise Exception("Você ganhou!")
        elif 3 == winner:
            raise Exception("Deu velha! (Empate)")
        else:
            print("Valor inesperado")

    except (KeyError, TypeError) as e:
        ttc.d(e)
def handle_winner_variable (res):
	""" Function doc """

	try:
		tmp = json.loads(res)
		winner = tmp["winner"]

		if 0 == winner :
			pass
		elif 1 == winner:
			raise Exception("Sorry, but you are a loser... =\\")
		elif 2 == winner:
			raise Exception("You win!")
		elif 3 == winner:
			raise Exception("Friendship wins! (tie)")
		else:
			print("unexpected value")

	except (KeyError, TypeError) as e:
		ttc.d(e)
Esempio n. 12
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
Esempio n. 13
0
def handle_winner_variable(res):
    """ Function doc """

    try:
        tmp = json.loads(res)
        winner = tmp["Wow - You are the Winner"]

        if 0 == winner:
            pass
        elif 1 == winner:
            raise Exception("Sorry, but you lost... =\\")
        elif 2 == winner:
            raise Exception("You win!")
        elif 3 == winner:
            raise Exception("Tie! (tie)")
        else:
            print("unexpected value")

    except (KeyError, TypeError) as e:
        ttc.d(e)
Esempio n. 14
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 is_error_in_answer (msg):
	"""
	Check for error field in @msg.

	@param
		msg --- string in json format

	@return
		True, if field exist and it's 1
		False otherwise
	"""

	try:
		ttc.d("your step validation: {0}".format(msg))
		tmp = json.loads(msg)

		if tmp["error"] == 1:
			return True

	except Exception as exp:
		print("eeem, {0}".format(exp))
		return False
Esempio n. 16
0
def is_error_in_answer(msg):
    """
	Check for error field in @msg.

	@param
		msg --- string in json format

	@return
		True, if field exist and it's 1
		False otherwise
	"""

    try:
        ttc.d("your step validation: {0}".format(msg))
        tmp = json.loads(msg)

        if tmp["error"] == 1:
            return True

    except Exception as exp:
        print("error, {0}".format(exp))
        return False
Esempio n. 17
0
def do_server_step(game_field):

    tmp = {}

    cell = ()
    if it_is_first_server_turn(game_field):
        i = 0
        for line in game_field:
            if 0 != line.count(ttc.USER_RAW_STEP):
                cell = (i, line.index(ttc.USER_RAW_STEP))
            i += 1

        ttc.d("How server see the cell of user first turn {0}".format(cell))

        if cell == (0, 0) or cell == (0, 2) or cell == (2, 0) or cell == (2,
                                                                          2):
            tmp["step"] = [1, 1]
        else:
            tmp["step"] = [0, 0]

        return tmp

    has_line_with_2_friendly_cells = has_line_with_two_moves(
        game_field, ttc.SERVER_RAW_STEP)
    if has_line_with_2_friendly_cells[0]:
        tmp["step"] = has_line_with_2_friendly_cells[1]
        ttc.d("step 2 attack {0}".format(tmp["step"]))
        return tmp

    has_line_with_2_enemy_cell = has_line_with_two_moves(
        game_field, ttc.USER_RAW_STEP)
    if has_line_with_2_enemy_cell[0]:
        tmp["step"] = has_line_with_2_enemy_cell[1]
        ttc.d("step 2 def {0}".format(tmp["step"]))
        return tmp

    random.seed()
    tmp["step"] = [random.randrange(3), random.randrange(3)]

    while True:
        tmp_json_str = json.dumps(tmp)
        ttc.d("server step: {0}".format(tmp_json_str))
        if not ttc.is_step_correct(tmp_json_str, game_field):
            tmp["step"] = [random.randrange(3), random.randrange(3)]
            continue
        else:
            break

    return tmp
	def apply_server_turn(self, server_turn_json):
		""" Function doc """

		ttc.d("apply server turn: {}".format(server_turn_json))
		try:
			tmp_dict = json.loads(server_turn_json)
			row = tmp_dict["step"][0]
			col = tmp_dict["step"][1]

			cell_name = "cell" + str(row) + str(col)
			ttc.d("apply server step, try to access : {}".format(cell_name))

			cell = self.get_object(cell_name)
			cell.set_sensitive(False)
			cell.set_label(ttc.SERVER_STEP)

		except Exception as exp:
			ttc.d(exp)
			self.show_error_dialog(str(exp))
			sys.exit(1)
Esempio n. 19
0
    def handle_server_answer(self, msg):
        """check for error and winner variables,
		if non zero - show dialog and exit

		@param
			msg: json-string from server
		"""

        ttc.d("handle server answer: {}".format(msg))

        try:
            tmp_dict = json.loads(msg)

            winner = tmp_dict["winner"]
            error = tmp_dict[
                "error"]  # suppose, we can't get an error from server

            if error:
                error_text = "smth bad happend"
                ttc.d(error_text)
                self.show_error_dialog(error_text)
                sys.exit(1)

            if 0 == winner:
                pass
            else:
                winner_text = {
                    1: "Sorry, but you are a loser... =\\",
                    2: "You win!",
                    3: "Friendship wins! (tie)"
                }.get(winner, "wtf")

                self.show_info_dialog(winner_text)
                sys.exit(0)

        except Exception as exp:
            # should not happend
            ttc.d("3 {}".format(exp))
            self.show_error_dialog(str(exp))
            self.on_TicTacToeWindow_delete_event(self.TicTacToeWindow,
                                                 "delete-event")
	def handle_server_answer (self, msg):
		"""check for error and winner variables,
		if non zero - show dialog and exit

		@param
			msg: json-string from server
		"""

		ttc.d("handle server answer: {}".format(msg))

		try:
			tmp_dict = json.loads(msg)

			winner = tmp_dict["winner"]
			error  = tmp_dict["error"]	# suppose, we can't get an error from server

			if error:
				error_text = "smth bad happend"
				ttc.d(error_text)
				self.show_error_dialog(error_text)
				sys.exit(1)


			if 0 == winner :
				pass
			else:
				winner_text = {
					1: "Sorry, but you are a loser... =\\",
					2: "You win!",
					3: "Friendship wins! (tie)"
				}.get(winner, "wtf")

				self.show_info_dialog(winner_text)
				sys.exit(0)

		except Exception as exp:
			# should not happend
			ttc.d("3 {}".format(exp))
			self.show_error_dialog(str(exp))
			self.on_TicTacToeWindow_delete_event(self.TicTacToeWindow, "delete-event")
Esempio n. 21
0
    def apply_server_turn(self, server_turn_json):
        """ Function doc """

        ttc.d("apply server turn: {}".format(server_turn_json))
        try:
            tmp_dict = json.loads(server_turn_json)
            row = tmp_dict["step"][0]
            col = tmp_dict["step"][1]

            # server sends coordinates - indexes (from 0,0)
            # but buttons in the gui named from 1,1
            # so, plus one.
            cell_name = "cell" + str(row + 1) + str(col + 1)
            ttc.d("apply server step, try to access : {}".format(cell_name))

            cell = self.get_object(cell_name)
            cell.set_sensitive(False)
            cell.set_label(ttc.SERVER_STEP)

        except Exception as exp:
            ttc.d(exp)
            self.show_error_dialog(str(exp))
            sys.exit(1)
Esempio n. 22
0
    def apply_server_turn(self, server_turn_json):
        """ Function doc """

        ttc.d("apply server turn: {}".format(server_turn_json))
        try:
            tmp_dict = json.loads(server_turn_json)
            row = tmp_dict["step"][0]
            col = tmp_dict["step"][1]

            # server sends coordinates - indexes (from 0,0)
            # but buttons in the gui named from 1,1
            # so, plus one.
            cell_name = "cell" + str(row + 1) + str(col + 1)
            ttc.d("apply server step, try to access : {}".format(cell_name))

            cell = self.get_object(cell_name)
            cell.set_sensitive(False)
            cell.set_label(ttc.SERVER_STEP)

        except Exception as exp:
            ttc.d(exp)
            self.show_error_dialog(str(exp))
            sys.exit(1)
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)
def get_winner (game_field):
	"""
	Analyze game (@game_field) and check, if a Winner exist.

	Return
		0 : nobody
		1 : user one (server | zero  | 5)
		2 : user two (client | cross | 2)
		3 : tie (no more free space)
	"""

	winner = 0
	gf = game_field  # weak reference

	empty = ttc.EMPTY_RAW_STEP	# 1
	cross = ttc.USER_RAW_STEP 	# 2
	zeros  = ttc.SERVER_RAW_STEP	# 5

	length = len(game_field)


	try:

		### check for tie, by counting empty cells on every line
		empty_count = 0
		for line in game_field:
			empty_count += line.count(empty)
		if 0 == empty_count:
			winner = 3
			raise Exception("TIE! no more free space")


		### check for winner

		# by rows and cols...
		for j in range(length):
			row = [ gf[j][i] for i in range(length) ]
			col = [ gf[i][j] for i in range(length) ]
			if col.count(cross) == length or row.count(cross) == length:
				winner = 2
				raise Exception("User wins!")
			elif col.count(zeros) == length or row.count(zeros) == length:
				winner = 1
				raise Exception("Server wins!")


		# by diagonals...
		for diag in [ [gf[0][0], gf[1][1], gf[2][2]], [gf[0][2], gf[1][1], gf[2][0]] ]:
			if diag.count(cross) == length:
				winner = 2
				raise Exception("User wins!")
			elif diag.count(zeros) == length:
				winner = 1
				raise Exception("Server wins!")


	except Exception as ex:
		# do nothing, just goto
		ttc.d(ex)


	return winner
def do_server_step (game_field):
	"""
	Analyze situations on @game_field
	and try to do a step.

	or ask a user about the turn, if it is a multiplayer mode.

	@return
		dict in json format with field 'step':[int, int]
	"""
	tmp = {}

	"""
	if MULTIPLAYER_MODE == 1:
		tmp_str = ttc.get_turn_from_user (game_field)
		ttc.d("Your step is : {}".format(tmp_str))

		tmp = json.loads(tmp_str)

	else:
		# generally, good to check, that empty sections on @game_field even exist
	"""



	# если первый ход, то тут два определенных хода #

	cell=()
	if it_is_first_server_turn(game_field):
		i = 0
		for line in game_field:
			if 0 != line.count( ttc.USER_RAW_STEP ):
				cell = ( i, line.index(ttc.USER_RAW_STEP) )
			i += 1

		ttc.d("How server see the cell of user first turn {0}".format(cell))

		if cell==(0,0) or cell==(0,2) or cell==(2,0) or cell==(2,2):
			tmp["step"] = [1, 1]
		else:
			tmp["step"] = [0, 0]

		return tmp


	# если на линии две чужие -- разбиваем #
	has_line_with_2_enemy_cell = has_line_with_two_moves(game_field, ttc.USER_RAW_STEP)
	if has_line_with_2_enemy_cell[0]:
		tmp["step"] = has_line_with_2_enemy_cell[1]
		ttc.d("step 2- {0}".format(tmp["step"]))
		return tmp


	# если на линии две наши -- дополняем #
	has_line_with_2_friendly_cells = has_line_with_two_moves(game_field, ttc.SERVER_RAW_STEP)
	if has_line_with_2_friendly_cells[0]:
		tmp["step"] = has_line_with_2_friendly_cells[1]
		ttc.d("step 2+' {0}".format(tmp["step"]))
		return tmp



	# иначе - раааандомааааайззззззз!

	random.seed()
	tmp["step"] = [random.randrange(3), random.randrange(3)]

	while True:
		tmp_json_str = json.dumps(tmp)
		ttc.d("server step: {0}".format(tmp_json_str))
		if not ttc.is_step_correct(tmp_json_str, game_field):
			tmp["step"] = [random.randrange(3), random.randrange(3)]
			continue
		else:
			break

	return tmp
Esempio n. 26
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)
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)
Esempio n. 28
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)
Esempio n. 29
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)
Esempio n. 30
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)
Esempio n. 31
0
def do_server_step (game_field):
	"""
	Analyze situations on @game_field
	and try to do a step.

	or ask a user about the turn, if it is a multiplayer mode.

	@return
		dict in json format with field 'step':[int, int]
	"""
	tmp = {}

	"""
	if MULTIPLAYER_MODE == 1:
		tmp_str = ttc.get_turn_from_user (game_field)
		ttc.d("Your step is : {}".format(tmp_str))

		tmp = json.loads(tmp_str)

	else:
		# generally, good to check, that empty sections on @game_field even exist
	"""



	# если первый ход, то тут два определенных хода #

	cell=()
	if it_is_first_server_turn(game_field):
		i = 0
		for line in game_field:
			if 0 != line.count( ttc.USER_RAW_STEP ):
				cell = ( i, line.index(ttc.USER_RAW_STEP) )
			i += 1

		ttc.d("How server see the cell of user first turn {0}".format(cell))

		if cell==(0,0) or cell==(0,2) or cell==(2,0) or cell==(2,2):
			tmp["step"] = [1, 1]
		else:
			tmp["step"] = [0, 0]

		return tmp


	# если на линии две наши -- дополняем #
	has_line_with_2_friendly_cells = has_line_with_two_moves(game_field, ttc.SERVER_RAW_STEP)
	if has_line_with_2_friendly_cells[0]:
		tmp["step"] = has_line_with_2_friendly_cells[1]
		ttc.d("step 2 attack {0}".format(tmp["step"]))
		return tmp


	# если на линии две чужие -- разбиваем #
	has_line_with_2_enemy_cell = has_line_with_two_moves(game_field, ttc.USER_RAW_STEP)
	if has_line_with_2_enemy_cell[0]:
		tmp["step"] = has_line_with_2_enemy_cell[1]
		ttc.d("step 2 def {0}".format(tmp["step"]))
		return tmp





	# иначе - раааандомааааайззззззз!

	random.seed()
	tmp["step"] = [random.randrange(3), random.randrange(3)]

	while True:
		tmp_json_str = json.dumps(tmp)
		ttc.d("server step: {0}".format(tmp_json_str))
		if not ttc.is_step_correct(tmp_json_str, game_field):
			tmp["step"] = [random.randrange(3), random.randrange(3)]
			continue
		else:
			break

	return tmp