0

Estoy haciendo una variante de juego 4 en línea adaptando código del juego TIC TAC TOE realizado por James Shah en esta pagina web: https://dev.to/jamesshah/the-classic-tictactoe-game-in-python-cpi

En el juego se declara victorioso a aquel jugador que ponga cuatro fichas en línea tanto vertical como horizontal como diagonal.

He analizado que existen 69 formas de poner las fichas de forma ganadora, pero para no escribir las condiciones literales en unos if de todos los casos, ideé una forma de iterar para obtener los valores horizontales, verticales y diagonales (no está en este código) para ahorrarme unas cuantas líneas de código.

El caso es que dichas condiciones no están siendo captadas en el programa y no sé por qué.

Tengo la impresión de que es un error sencillo pero profundo.

Aquí les va el código:

# -*- coding: utf-8 -*-

# adaptacion de Tic Tac Toe por James Shah https://dev.to/jamesshah/the-classic-tictactoe-game-in-python-cpi
# Implementacion de humano vs humano del juego 4 en linea

theBoard = {
    '36': ' ', '37': ' ', '38': ' ', '39': ' ', '40': ' ', '41': ' ', '42': ' ',
    '29': ' ', '30': ' ', '31': ' ', '32': ' ', '33': ' ', '34': ' ', '35': ' ',
    '22': ' ', '23': ' ', '24': ' ', '25': ' ', '26': ' ', '27': ' ', '28': ' ',
    '15': ' ', '16': ' ', '17': ' ', '18': ' ', '19': ' ', '20': ' ', '21': ' ',
    '8': ' ', '9': ' ', '10': ' ', '11': ' ', '12': ' ', '13': ' ', '14': ' ',
    '1': ' ', '2': ' ', '3': ' ', '4': ' ', '5': ' ', '6': ' ', '7': ' '
}

board_keys = []

for key in theBoard:
    board_keys.append(key)

def printBoard(board):

    print(board['36'] + '|' + board['37'] + '|' + board['38'] + '|' +
          board['39'] + '|' + board['40'] + '|' + board['41'] + '|' + board['42'])
    print('-+-+-+-+-+-+-')
    print(board['29'] + '|' + board['30'] + '|' + board['31'] + '|' +
          board['32'] + '|' + board['33'] + '|' + board['34'] + '|' + board['35'])
    print('-+-+-+-+-+-+-')
    print(board['22'] + '|' + board['23'] + '|' + board['24'] + '|' +
          board['25'] + '|' + board['26'] + '|' + board['27'] + '|' + board['28'])
    print('-+-+-+-+-+-+-')
    print(board['15'] + '|' + board['16'] + '|' + board['17'] + '|' +
          board['18'] + '|' + board['19'] + '|' + board['20'] + '|' + board['21'])
    print('-+-+-+-+-+-+-')
    print(board['8'] + '|' + board['9'] + '|' + board['10'] + '|' + board['11'] +
          '|' + board['12'] + '|' + board['13'] + '|' + board['14'])
    print('-+-+-+-+-+-+-')
    print(board['1'] + '|' + board['2'] + '|' + board['3'] + '|' +
          board['4'] + '|' + board['5'] + '|' + board['6'] + '|' + board['7'])

def game():

    turn = 'X'
    count = 0

    for i in range(43):
        printBoard(theBoard)
        print("It's your turn," + turn + '.Move to which place?')

        move = input()

        if theBoard[move] == ' ':
            theBoard[move] = turn
            count += 1
        else:
            print('That place is already filled.\nMove to which place?')
            continue

        # Despues de 7 jugadas ya existe posibilidad de que el primer jugador gane
        if count >= 7:

            # horizontales
            cabezasH = [1, 8, 15, 22, 29, 36]

            lista = [i for i in range(1, 43)]

            for numeroH in cabezasH:

                for i in range(0, 4):

                    listaH = lista[numeroH+i-1:numeroH+i+3]

                    if theBoard[str(listaH[0])] == theBoard[str(listaH[1])] == theBoard[str(listaH[2])] == theBoard[str(listaH[3])] != ' ':
                        printBoard(theBoard)
                        print('\nGame Over.\n')
                        print(' **** ' + turn + ' won. ****')
                        break

            # verticales
            intervalos = [i for i in range(1, 22)]

            for numeroV in intervalos:

                listaV = [numeroV, numeroV+7, numeroV+14, numeroV+21]

                if theBoard[str(listaV[0])] == theBoard[str(listaV[1])] == theBoard[str(listaV[2])] == theBoard[str(listaV[3])] != ' ':
                    printBoard(theBoard)
                    print('\nGame Over.\n')
                    print(' **** ' + turn + ' won. ****')
                    break

        # Si no hay ganador en lo anterior en la jugada 42 se declara empate
        if count == 42:
            print('\nGame Over.\n')
            print("It's a Tie!!")

            # Se desea jugar de nuevo o no
            restart = input('Do want to play Again?(y/n)')
            if restart == 'y' or restart == 'Y':
                for key in board_keys:
                    theBoard[key] = ' '
                printBoard(theBoard)
                game()
            else:
                print('gg well played')
                break

        if turn == 'O':
            turn = 'X'
        else:
            turn = 'O'

game()

Gracias por su tiempo.

Cuando pruebo las iteraciones de forma aislada me da el resultado que deseo, no sé por qué no lo hace así en el código completo.

print('los elementos horizontales')
cabezasH = [1, 8, 15, 22, 29, 36]
lista = [i for i in range(1, 43)]

for numeroH in cabezasH:
    for i in range(0, 4):
        listaH = lista[numeroH+i-1:numeroH+i+3]
        print(listaH)

y los verticales

print('los elementos verticales')
intervalos = [i for i in range(1, 22)]

for numeroV in intervalos:
    listaV = [numeroV, numeroV+7, numeroV+14, numeroV+21]
    print(listaV)

1 respuesta 1

1

finalmente el codigo quedo de esta manera

saludos

# -*- coding: utf-8 -*-

# adaptacion de Tic Tac Toe por James Shah https://dev.to/jamesshah/the-classic-tictactoe-game-in-python-cpi
# Implementacion de humano vs humano del juego 4 en linea


theBoard = {'36': ' ', '37': ' ', '38': ' ', '39': ' ', '40': ' ', '41': ' ', '42': ' ',
            '29': ' ', '30': ' ', '31': ' ', '32': ' ', '33': ' ', '34': ' ', '35': ' ',
            '22': ' ', '23': ' ', '24': ' ', '25': ' ', '26': ' ', '27': ' ', '28': ' ',
            '15': ' ', '16': ' ', '17': ' ', '18': ' ', '19': ' ', '20': ' ', '21': ' ',
            '8': ' ', '9': ' ', '10': ' ', '11': ' ', '12': ' ', '13': ' ', '14': ' ',
            '1': ' ', '2': ' ', '3': ' ', '4': ' ', '5': ' ', '6': ' ', '7': ' '
            }

board_keys = []

for key in theBoard:
    board_keys.append(key)


def printBoard(board):

    print(board['36'] + '|' + board['37'] + '|' + board['38'] + '|' +
          board['39'] + '|' + board['40'] + '|' + board['41'] + '|' + board['42'])
    print('-+-+-+-+-+-+-')
    print(board['29'] + '|' + board['30'] + '|' + board['31'] + '|' +
          board['32'] + '|' + board['33'] + '|' + board['34'] + '|' + board['35'])
    print('-+-+-+-+-+-+-')
    print(board['22'] + '|' + board['23'] + '|' + board['24'] + '|' +
          board['25'] + '|' + board['26'] + '|' + board['27'] + '|' + board['28'])
    print('-+-+-+-+-+-+-')
    print(board['15'] + '|' + board['16'] + '|' + board['17'] + '|' +
          board['18'] + '|' + board['19'] + '|' + board['20'] + '|' + board['21'])
    print('-+-+-+-+-+-+-')
    print(board['8'] + '|' + board['9'] + '|' + board['10'] + '|' + board['11'] +
          '|' + board['12'] + '|' + board['13'] + '|' + board['14'])
    print('-+-+-+-+-+-+-')
    print(board['1'] + '|' + board['2'] + '|' + board['3'] + '|' +
          board['4'] + '|' + board['5'] + '|' + board['6'] + '|' + board['7'])


def game():

    global turn  # si no hay error en la funcion victoria

    turn = 'X'

    while True:
        printBoard(theBoard)
        print("It's your turn," + turn + ".Move to which place?")

        move = input()

        try:  # evitando que el programa se rompa si move tomaun valor distinto de numeros 1 a 42

            lista_move = ['1', '2', '3', '4', '5', '6', '7']

            if move in lista_move:

                if theBoard[move] == ' ':
                    theBoard[move] = turn

                else:

                    print("..you can't do that.\nMove to which place?")

                    continue  # sino cuando turn tomaria no seria la misma ficha de juego

            elif move not in lista_move:

                if theBoard[move] == ' ' and theBoard[str(int(move)-7)] != ' ':
                    theBoard[move] = turn

                else:
                    print("...you can't do that :).\nMove to which place?")

                    continue  # sino cuando turn tomaria no seria la misma ficha de juego
        except KeyError:  # capturando el error cuando move es distinto de numeros 1 a 42

            print("..you can't do that either.\nMove to which place?")

            continue  # sino cuando turn tomaria no seria la misma ficha de juego

    # Despues de 7 jugadas ya existe posibilidad de que el primer jugador gane

        # horizontales
        cabezasH = [1, 8, 15, 22, 29, 36]

        lista = [i for i in range(1, 43)]

        for numeroH in cabezasH:

            for i in range(0, 4):

                listaH = lista[numeroH + i - 1:numeroH + i + 3]

                if theBoard[str(listaH[0])] == theBoard[str(listaH[1])] == theBoard[str(listaH[2])] == theBoard[str(listaH[3])] != ' ':
                    victory()
                    play_again()

        # verticales
        intervalos = [i for i in range(1, 22)]

        for numeroV in intervalos:

            listaV = [numeroV, numeroV + 7, numeroV + 14, numeroV + 21]

            if theBoard[str(listaV[0])] == theBoard[str(listaV[1])] == theBoard[str(listaV[2])] == theBoard[str(listaV[3])] != ' ':
                victory()
                play_again()

        # diagonales

        lista_diagonal1 = [1, 2, 3, 4, 8, 9, 10, 11, 15, 16, 17, 18]
        lista_diagonal2 = [4, 5, 6, 7, 11, 12, 13, 18, 19, 20, 14, 21]

        for i, j in zip(lista_diagonal1, lista_diagonal2):

            listaD1 = [i, i+8, i+16, i+24]
            listaD2 = [j, j+6, j+12, j+18]

            if theBoard[str(listaD1[0])] == theBoard[str(listaD1[1])] == theBoard[str(listaD1[2])] == theBoard[str(listaD1[3])] != ' ' or theBoard[str(listaD2[0])] == theBoard[str(listaD2[1])] == theBoard[str(listaD2[2])] == theBoard[str(listaD2[3])] != ' ':
                victory()
                play_again()

        # el empate
        lista_empate = []

        for j in board_keys:

            for i in theBoard[j]:

                if i != ' ':

                    lista_empate.append(i)

            if len(lista_empate) == 42:

                tie()
                play_again()

# el cambio de la ficha que le toca en turno!!!
        if turn == 'O':
            turn = 'X'
        else:
            turn = 'O'

# si hay victoria


def victory():

    printBoard(theBoard)
    print("\nGame Over.\n")
    print(" **** " + turn + " won. ****")

# si hay empate


def tie():

    printBoard(theBoard)
    print("\nGame Over.\n")
    print("It's a Tie!!")

# si desea jugar de nuevo o no


def play_again():

    # Now we will ask if player wants to restart the game or not.
    restart = input("Do want to play Again?(y/n)")
    if restart == "y" or restart == "Y":
        for key in board_keys:
            theBoard[key] = " "

    elif restart == "n" or restart == "N":
        print('gg well played')
        quit()

    else:

        play_again()


game()

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.