user14663834
user14663834

Reputation:

My function isn't working and I don't know why. Python

So I have a board that has 9 positions and 6 pieces, 3 [X] and 3 [ ] (you can also consider "[ ]" a piece but it represents an empty position). A player can choose to move a piece anywhere he wants to a position near him. In the board below, "X" (that's how we represent the pieces, just like the ones on the board but without the []) has to move but he has no place to go. I want a function that sees if a player has no legal movements and if so it returns True. These are the helping functions:

#pc stands for piece, brd for board and pos for position

board = ["[X]","[X]","[X]",
         "[O]","[O]","[O]",
         "[ ]","[ ]","[ ]"]

def near_pos(pos):    #positions are represented 1-9 and this functions gives the near positions of a position
    if pos== 1:
        return (2,4,5)
    elif pos== 2:
        return (1,3,4,5,6)
    elif pos== 3:
        return (2,5,6)
    elif pos== 4:
        return (1,2,5,7,8)
    elif pos== 5:
        return (1,2,3,4,6,7,8,9)
    elif pos== 6:
        return (2,3,5,8,9)
    elif pos== 7:
        return (4,5,8)
    elif pos== 8:
        return (4,5,6,7,9)
    elif pos== 9:
        return (5,6,8)

def free_pos(brd,pos):   #you give it a board and a position and it returns True if it is free
    pos -= 1
    if brd[pos] == "[ ]":
        return True
    else:
        return False

def player_pos(brd,pc):      #It works now
    l = []
    for i in range(0,9):
        if pc == "X":
            if brd[i] == "[X]":
                l.append(i + 1)
        elif pc == "O":
            if brd[i] == "[O]":
                l.append(i + 1)
    return (* l,)

#The last function (the one that I'll write next, sorry if I caused any misunderstanding) was supposed to see if from the positions I got from player_pos, if any had a close position available. The way I thought I could do that was by seeing for each position the positions near that one, using near_pos function, and determine if there was any clear one, using free_pos.

What I wrote was this but it is wrong and I don't know how to fix it

def No_Free_Positions(brd,pc):
    if pc == "X":
        a = "O"
    if pc =="O":
        a = "X"
    for player_pos(brd,pc) in near_pos(pc):
        if Free_Pos(brd,near_pos(pc)) is False:
            return "No"
        else:
            return "Yes"

What's the problem?

Upvotes: 0

Views: 79

Answers (1)

DapperDuck
DapperDuck

Reputation: 2859

The free_pos function will always return false because of this condition: if brd[pos] == " ". This checks if the given square is empty, however an empty square in your program is "[ ]", so it will never return true. Here is the corrected code:

if brd[pos] == "[ ]":

Upvotes: 1

Related Questions