Search code examples
pythonarraysdictionaryturn

Why i cant print the board at the end? (tic tac toe python)


I have to make a Tictactoe for a project, and while i do know that the code is not good, i can´t see what the error is, the value is assigned to the dict, if i print the key for the last play its correctly show me if is an X or a O, but the value is not represented in the last print of the board.

def tateti():
juego_terminado = False
first_player = 'X'
second_player = 'O'
turn = 0
tablero = {'ArribaIzquierda' : ' ','ArribaCentro' : ' ', 'ArribaDerecha' : ' ', 
'CentroIzquierda' : ' ', 'CentroCentro' : ' ', 'CentroDerecha' : ' ',
'AbajoIzquierda' : ' ', 'AbajoCentro' : ' ','AbajoDerecha' : ' '}

#Loop principal
    #Instrucciones
print('Para jugar, usa el numepad como si fuera el tablero de tateti\no elegi una posicion en el tablero con las primeras dos iniciales de la fila\ny la primer letra de la posicion dentro de la fila.\nPor ejemplo para ponerla arriba al centro es: arc (AR-riba C-entro). \n\n')
print('TA TE TI')
while juego_terminado == False:
    abd = tablero['AbajoDerecha']
    arc = tablero['ArribaCentro']
    ard = tablero['ArribaDerecha']
    cei = tablero['CentroIzquierda']
    cec = tablero['CentroCentro']
    ced = tablero['CentroDerecha']
    ari = tablero['ArribaIzquierda']
    abi = tablero['AbajoIzquierda']
    abc = tablero['AbajoCentro']
    #Separando los turnos
    if turn % 2 == 0:
        player = first_player
    else:
        player = second_player
    
    print('|{}|{}|{}|\n- - - -\n|{}|{}|{}|\n- - - -\n|{}|{}|{}|'.format(ari, arc, ard, cei, cec, ced, abi, abc, abd))
    #Pedirle al jugador donde quiero poner su figura
    jugada = str(input('¿Donde queres poner la {}?: '.format(player)))

    #Asignando cruz o cicedulo al dicecionario
    if jugada == 'ari' or jugada == '7':
        if tablero['ArribaIzquierda'] == ' ': 
            tablero['ArribaIzquierda'] = player
        else:
            print('Este posición ya fue ocupada, por favor elegi otra')
            continue
    elif jugada == 'arc' or jugada == '8':
        if  tablero['ArribaCentro'] == ' ':   
            tablero['ArribaCentro'] = player
        else:
            print('Este posición ya fue ocupada, por favor elegi otra')
            continue
    elif jugada == 'ard' or jugada == '9':
        if tablero['ArribaDerecha'] == ' ':
            tablero['ArribaDerecha'] = player
        else:
            print('Este posición ya fue ocupada, por favor elegi otra')
            continue
    elif jugada == 'cei' or jugada == '4':
        if tablero['CentroIzquierda'] == ' ':
            tablero['CentroIzquierda'] = player
        else:
            print('Este posición ya fue ocupada, por favor elegi otra')
            continue
    elif jugada == 'cec' or jugada == '5':
        if tablero['CentroCentro'] == ' ':
            tablero['CentroCentro'] = player
        else:
            print('Este posición ya fue ocupada, por favor elegi otra')
            continue
    elif jugada == 'ced' or jugada == '6':
        if tablero['CentroDerecha'] == ' ':
            tablero['CentroDerecha'] = player
        else:
            print('Este posición ya fue ocupada, por favor elegi otra')
            continue
    elif jugada == 'abi' or jugada == '1':
        if tablero['AbajoIzquierda'] == ' ':
            tablero['AbajoIzquierda'] = player
        else:
            print('Este posición ya fue ocupada, por favor elegi otra')
            continue
    elif jugada == 'abc' or jugada == '2':
        if tablero['AbajoCentro'] == ' ':
            tablero['AbajoCentro'] = player
        else:
            print('Este posición ya fue ocupada, por favor elegi otra')
            continue
    elif jugada == 'abd' or jugada == '3' :
        if tablero['AbajoDerecha'] == ' ':
            tablero['AbajoDerecha'] = player
        else:
            print('Este posición ya fue ocupada, por favor elegi otra')
            continue
    else:
        print('Jugada invalida, por favor realice una jugada valida') 
        continue

    #Condiciones para ganar
    if tablero['AbajoDerecha'] == tablero['AbajoCentro'] and tablero['AbajoCentro'] == tablero['AbajoIzquierda'] and tablero['AbajoDerecha'] != ' ' :
        juego_terminado = True
    elif tablero['CentroDerecha'] == tablero['CentroCentro'] and tablero['CentroCentro'] == tablero['CentroIzquierda'] and tablero['CentroDerecha'] != ' ' :
        juego_terminado = True
    elif tablero['ArribaDerecha'] == tablero['ArribaCentro'] and tablero['ArribaCentro'] == tablero['ArribaIzquierda'] and tablero['ArribaDerecha'] != ' ':
        juego_terminado = True
    elif tablero['ArribaDerecha'] == tablero['CentroCentro'] and tablero['CentroCentro'] == tablero['AbajoIzquierda'] and tablero['ArribaDerecha'] != ' ':
        juego_terminado = True
    elif tablero['ArribaIzquierda'] == tablero['CentroCentro'] and tablero['CentroCentro'] == tablero['AbajoDerecha'] and tablero['ArribaIzquierda'] != ' ':
        juego_terminado = True
    elif tablero['ArribaDerecha'] == tablero['CentroDerecha'] and tablero['CentroDerecha'] == tablero['AbajoDerecha'] and tablero['ArribaDerecha'] != ' ':
        juego_terminado = True
    elif tablero['ArribaIzquierda'] == tablero['CentroIzquierda'] and tablero['CentroIzquierda'] == tablero['AbajoIzquierda'] and tablero['ArribaIzquierda'] != ' ':
        juego_terminado = True
    elif tablero['ArribaCentro'] == tablero['CentroCentro'] and tablero['CentroCentro'] == tablero['AbajoCentro'] and tablero['ArribaCentro'] != ' ':
        juego_terminado = True
    
    #Si el tablero esta lleno    
    if turn == 8 and juego_terminado == False:
        print('Empate')
        print('|{}|{}|{}|\n- - - -\n|{}|{}|{}|\n- - - -\n|{}|{}|{}|'.format(ari, arc, ard, cei, cec, ced, abi, abc, abd))
        break
    elif juego_terminado == True:
        print('{} gano'.format(player))
        print('|{}|{}|{}|\n- - - -\n|{}|{}|{}|\n- - - -\n|{}|{}|{}|'.format(ari, arc, ard, cei, cec, ced, abi, abc, abd))
        
        
              
    turn += 1

    
    
  tateti()

Thanks in advance!


Solution

  • You are assigning the new X or O to tablero['algo']. If the game doesn't end here, you assign the contents of tablero to ari, arc, etc., but only at the start of the next loop.

    So if the game does end after that move, you print the old ari, arc, etc. which have not yet been updated to reflect the latest move.

    Of course, there are many other things you should fix (lots of repetition that can be avoided), but the game does work correctly.

    Some suggestions:

    I would use a simple list to handle the board. tablero = [" "] * 9 creates a list of nine space characters. This allows for a lot of simplications down the line. For example, to print the board, you can simply do

    print('|{6}|{7}|{8}|\n- - - -\n|{3}|{4}|{5}|\n- - - -\n|{0}|{1}|{2}|'.format(*tablero))
    

    Note that the first element of a list is indexed by 0, so we need to take that into account.

    Once you've done that, you can create another list to handle the shortcuts:

    casillas = ["abi", "abc", "abd", "cei", "cec", "ced", "ari", "arc", "ard"]
    

    Now handling the input is a lot easier because you can reuse the same code instead of lots of if/elif statements:

    jugada = input('¿Donde queres poner la {}?: '.format(player)) # input() already returns a str
    
    try: # let's see if player entered a whole number
        casilla = int(jugada) - 1 # remember, field 1 is numbered internally as 0
    except ValueError: # apparently not
        try: # let's see if player entered a valid shortcut
            casilla = casillas.index(jugada)
        except ValueError: # apparently not
            casilla = 9 # let's choose an invalid value, we'll detect that later
    

    Now that we have a number in casilla, let's see if it's in range, and if so, let's fill the board, if we can:

    if 0 <= casilla <= 8:
        if tablero[casilla] == ' ': 
            tablero[casilla] = player
        else:
            print('Este posición ya fue ocupada, por favor elegi otra')
            continue
    else:
        print('Jugada invalida, por favor realice una jugada valida') 
        continue
    

    The winning conditions can also be simplified:

    if tablero[0] == tablero[1] == tablero[2] != " " or \
       tablero[3] == tablero[4] == tablero[4] != " " or \
       tablero[6] == tablero[7] == tablero[8] != " " or \
       ... etc. ...:
       juego_terminado = True
    

    With a comprehension, this can be shortened even more:

    if any(tablero[i] == tablero[j] == tablero[k] != " " 
       for i,j,k in ((0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6))):
        juego_terminado = True
    

    I haven't actually tested this, so if you run into problems, let me know.