Python棋盘游戏网格[数组和列表问题]

时间:2018-11-07 15:19:55

标签: python python-3.x list printing

grid = [[' --- --- --- '], ['| 1 | 2 | 3 |'],
        [' --- --- --- '], ['| 4 | 5 | 6 |'],
        [' --- --- --- '], ['| 7 | 8 | 9 |'],
        [' --- --- --- ']] 

def board():
    for i in grid:
        print(''.join(i) 

def player():
    x = 0
    y = 0
    player1 = input("Enter Player1 move : ")
    for i in grid:
        for j in i:
            if j == player1:
                grid[1][1] = 'X'
    board()

player()

输出:

 --- --- --- 
| 1 | 2 | 3 |
 --- --- --- 
| 4 | 5 | 6 |
 --- --- --- 
| 7 | 8 | 9 |
 --- --- --- 

尽管代码尚未完成,但我的问题是,应根据用户输入进行更改时,网格中的数字不会更改。我在做什么错!! :(

2 个答案:

答案 0 :(得分:0)

第二个想法是,我看到您无论如何都将字符串与字符串进行比较,所以这里的问题是您的j变量从不假设网格中的所有数字值(即1、2、3等)。 ..)。 更好的方法是用其他方式定义网格并更改打印方式。

您首先定义要在网格的开头和结尾处打印的图案。然后,遍历网格的各行并创建要打印的字符串:

startEnd = ' --- --- --- '
grid2 = [['1', '2', '3'],['4', '5', '6'],['7', '8', '9']]

def board():
    print (startEnd)
    for row in grid2:
        s = '| {0} | {1} | {2} |'.format(row[0], row[1], row[2])
        print(s)        
    print (startEnd)

def player():
    x = 0
    y = 0
    player1 = raw_input("Enter Player1 move : ")
    for i in grid2:
        for j in i:
            if j == player1:
                grid2[1][1] = 'X'
    board()

player()

输出为:

 --- --- ---
| 1 | 2 | 3 |
| 4 | X | 6 |
| 7 | 8 | 9 |
 --- --- ---

答案 1 :(得分:0)

您的代码存在多个错误-请参见内联注释:

grid = [[' --- --- --- '], ['| 1 | 2 | 3 |'],
        [' --- --- --- '], ['| 4 | 5 | 6 |'],
        [' --- --- --- '], ['| 7 | 8 | 9 |'],
        [' --- --- --- ']] 

def player():
    x = 0                          # not used
    y = 0                          # not used
    player1 = input("Enter Player1 move : ")
    for i in grid:                 # each i is a list containing 1 string
        for j in i:                # each j is one string
            if j == player1:       # only ever true if playerinput is ' --- --- --- '
                                   # or '| 1 | 2 | 3 |' or '| 4 | 5 | & |' or ....
                grid[1][1] = 'X'   # never hit.

您应该将代码分成更小且更易于理解的部分:

def freeSpace(l,pos):
    """Returns True if l[pos] is inside the list and currently of type int - else False."""
    return (0 <= pos < len(l))  and isinstance(l[pos],int)

def setPlayer(l,player,pos):
    """Checks if l[pos] is valid to be set to a players 'X' or 'O' string. 
    If, set it and return True, else return False."""
    if freeSpace(l,pos):
        l[pos] = player
        return True

    return False

def printList(l):
    """Pretty prints a list of 9 items in a grid with some decor around it."""
    print("\n --- --- --- ")
    for row in (l[i:i + 3] for i in range(0,9,3)):
        print("|",end="")
        for e in row:
            print("{:^3}|".format(e),end="")
        print("\n --- --- --- ")

def no_win(l):
    # TODO - check for win, return False and a win message mayhap
    return True

主游戏:

# prepare field with integers - its easier to hold your 9 fields in a 1dim list
# and do the "comlicated" stuff in printList
tic_tac_toe = list(range(1,10))

# no players turn
player = ""
ok = True

# until all fields
while any(i in range(1,10) for i in tic_tac_toe) and no_win(tic_tac_toe):
    printList(tic_tac_toe)

    # last turn was ok, switch players (X starts if player = "")
    if ok:
        player = "X" if player != "X" else "O"
        print("Your turn: ", player)
    else: 
        # how hard can it be ...
        print("Wrong move - try again: ", player)

    # you could move this also in a method .. see 
    # https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until
    try:
        k = input("Which position? ")
        k = int(k)-1
        ok = setPlayer(tic_tac_toe, player, k)
    except ValueError:
        ok = False

输出:

 --- --- ---
| 1 | 2 | 3 |
 --- --- ---
| 4 | 5 | 6 |
 --- --- ---
| 7 | 8 | 9 |
 --- --- ---
Your turn:  X
Which position? Applepie

 --- --- ---
| 1 | 2 | 3 |
 --- --- ---
| 4 | 5 | 6 |
 --- --- ---
| 7 | 8 | 9 |
 --- --- ---
Wrong move - try again:  X
Which position? 99

 --- --- ---
| 1 | 2 | 3 |
 --- --- ---
| 4 | 5 | 6 |
 --- --- ---
| 7 | 8 | 9 |
 --- --- ---
Wrong move - try again:  X
Which position? 1

 --- --- ---
| X | 2 | 3 |
 --- --- ---
| 4 | 5 | 6 |
 --- --- ---
| 7 | 8 | 9 |
 --- --- ---
Your turn:  O
Which position? 1

 --- --- ---
| X | 2 | 3 |
 --- --- ---
| 4 | 5 | 6 |
 --- --- ---
| 7 | 8 | 9 |
 --- --- ---
Wrong move - try again:  O
Which position? 5

 --- --- ---
| X | 2 | 3 |
 --- --- ---
| 4 | O | 6 |
 --- --- ---
| 7 | 8 | 9 |
 --- --- ---
Your turn:  X
Which position?  # etc.