1
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()

Output:

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

Though the code is not yet complete,my problem is, the numbers in the grid doesn't change when it should be changed according to the user input..What am i doing wrong!? :(

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • 1
    The output of the `input()` method is a string, so you should compare your `j` to `int(player1)`. – toti08 Nov 07 '18 at 15:21
  • Is it how your code is currently indented? – Cid Nov 07 '18 at 15:22
  • There's also a problem when you iterate over the `i` elements, your `j` will not assume all the numeric values in your string, but just the whole string, for example `| 1 | 2 | 3 |`, so it will never be a number. You better modify your grid to only contain numbers and modify the function to print it. – toti08 Nov 07 '18 at 15:33

2 Answers2

0

On a second thought I saw you were anyway comparing string with strings, so the problem here is that your j variable was never assuming all the numeric values in your grid (i.e. 1, 2, 3, etc...). A better approach would be to define your grid in a different way and change the way you print it.

You first define the pattern you want to print at the beginning and at the end of your grid. Then you iterate over the rows of your grid and create the string to print:

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()

Output is:

 --- --- ---
| 1 | 2 | 3 |
| 4 | X | 6 |
| 7 | 8 | 9 |
 --- --- ---
toti08
  • 2,448
  • 5
  • 24
  • 36
  • The only other change would be to add to `x` (example: `x += 1`) and `y` (`y += 1`) since currently it will only output what you have above instead of changing with the user input. You will also want to reset `y` after each iteration through `j`. – Cory Shay Nov 07 '18 at 16:04
  • Yes, I've seen, but that was not clear from the question, the OP is always setting the element `[1][1]` in grid to `'X'`, so I just left the rest of the code as it was. – toti08 Nov 07 '18 at 16:06
0

There are several bugs to your code - see inline comments:

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.

You should split your code into smaller and easier to understand parts:

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

Main game:

# 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

Output:

 --- --- ---
| 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.
Community
  • 1
  • 1
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69