Пример #1
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 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 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
Пример #4
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)
Пример #5
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
Пример #6
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)