简体   繁体   English

为什么我不能在最后打印板? (井字游戏蟒蛇)

[英]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.我必须为一个项目制作一个 Tictactoe,虽然我知道代码不好,但我看不到错误是什么,值被分配给 dict,如果我打印最后一次播放的键正确地告诉我是 X 还是 O,但该值未在板的最后一次打印中显示。

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!提前致谢!

You are assigning the new X or O to tablero['algo'] .您正在将新的XO分配给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.如果游戏没有在这里结束,您将tablero的内容分配给ariarc等,但仅限于下一个循环的开始。

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.因此,如果游戏确实在该移动之后结束,则打印尚未更新以反映最新移动的旧ariarc等。

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. tablero = [" "] * 9创建一个包含 9 个空格字符的列表。 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.请注意,列表的第一个元素由0索引,因此我们需要考虑到这一点。

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:现在处理输入要容易得多,因为您可以重用相同的代码而不是大量的if/elif语句:

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:现在我们在casilla有一个数字,让我们看看它是否在范围内,如果可以,让我们填充板子,如果可以的话:

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.我还没有实际测试过这个,所以如果你遇到问题,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM