Python Board Game grid[Array and list problem]











up vote
0
down vote

favorite












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!? :(










share|improve this question




















  • 1




    The output of the input() method is a string, so you should compare your j to int(player1).
    – toti08
    Nov 7 at 15:21










  • Is it how your code is currently indented?
    – Cid
    Nov 7 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 7 at 15:33















up vote
0
down vote

favorite












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!? :(










share|improve this question




















  • 1




    The output of the input() method is a string, so you should compare your j to int(player1).
    – toti08
    Nov 7 at 15:21










  • Is it how your code is currently indented?
    – Cid
    Nov 7 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 7 at 15:33













up vote
0
down vote

favorite









up vote
0
down vote

favorite











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!? :(










share|improve this question















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!? :(







python python-3.x list printing






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 7 at 16:12









Patrick Artner

18.3k51940




18.3k51940










asked Nov 7 at 15:19









AbyssWalker

31




31








  • 1




    The output of the input() method is a string, so you should compare your j to int(player1).
    – toti08
    Nov 7 at 15:21










  • Is it how your code is currently indented?
    – Cid
    Nov 7 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 7 at 15:33














  • 1




    The output of the input() method is a string, so you should compare your j to int(player1).
    – toti08
    Nov 7 at 15:21










  • Is it how your code is currently indented?
    – Cid
    Nov 7 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 7 at 15:33








1




1




The output of the input() method is a string, so you should compare your j to int(player1).
– toti08
Nov 7 at 15:21




The output of the input() method is a string, so you should compare your j to int(player1).
– toti08
Nov 7 at 15:21












Is it how your code is currently indented?
– Cid
Nov 7 at 15:22




Is it how your code is currently indented?
– Cid
Nov 7 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 7 at 15:33




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 7 at 15:33












2 Answers
2






active

oldest

votes

















up vote
0
down vote



accepted










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





share|improve this answer























  • 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 7 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 7 at 16:06




















up vote
0
down vote













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.





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53192417%2fpython-board-game-gridarray-and-list-problem%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










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





    share|improve this answer























    • 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 7 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 7 at 16:06

















    up vote
    0
    down vote



    accepted










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





    share|improve this answer























    • 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 7 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 7 at 16:06















    up vote
    0
    down vote



    accepted







    up vote
    0
    down vote



    accepted






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





    share|improve this answer














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






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 7 at 15:48

























    answered Nov 7 at 15:43









    toti08

    1,59611523




    1,59611523












    • 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 7 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 7 at 16:06




















    • 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 7 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 7 at 16:06


















    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 7 at 16:04




    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 7 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 7 at 16:06






    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 7 at 16:06














    up vote
    0
    down vote













    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.





    share|improve this answer



























      up vote
      0
      down vote













      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.





      share|improve this answer

























        up vote
        0
        down vote










        up vote
        0
        down vote









        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.





        share|improve this answer














        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.






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 7 at 16:15

























        answered Nov 7 at 16:06









        Patrick Artner

        18.3k51940




        18.3k51940






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53192417%2fpython-board-game-gridarray-and-list-problem%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Xamarin.form Move up view when keyboard appear

            Post-Redirect-Get with Spring WebFlux and Thymeleaf

            Anylogic : not able to use stopDelay()