0

I know ultimately this has to be a formatting issue, but can't get quite figure it out. Here is an example of what my list looks like:

[['a1', 'a2', 'a3', 'a4', 'a5'], ['b1', 'b2', 'b3', 'b4'], ['c1', 'c2', 'c3'], ['d1', 'd2', 'd3'], ['e1', 'e2']]

My code with IF statement looks like this:

guesses = 0
    while guesses < 5:
        guess = input("Guess a spot on the grid (example A10:")
        guesses + 1
        if guess in grid1.board:
            print("Sweet nice hit!")
        else:
            print("sorry try again")

Every entry that seemingly should be correct is giving me a "sorry try again" error. Any idea what my issue might be?

EDIT ADDED MORE CODE HERE---this is where i run the game (battleship)

if __name__ == '__main__':
    grid = [['O']*BOARD_SIZE for _ in range(BOARD_SIZE)]
    player1 = Player()
    player2 = Player()
    grid1 = Board(grid)
    grid2 = Board(grid)
    grid1.print_board()
    chris =[]

    for ship_name, ship_size in SHIP_INFO:
        ship1 = Ship(player1,ship_name,ship_size,grid1) #create ship instance
        # ask_coords = ship1.ask_ship_coords(ship_name) #ask user for starting coordinate for ship in form "A1"
        x,y = ship1.split_coordinates(ship_name) #split coordinate from above into x, y variables and check if valid
        direction = ship1.ask_ship_location() # ask for ship's postion --horizontal or vertical
        created_coords = ship1.create_ship_coordinates(x, y, ship_size, direction,grid) # create all coordinates for ship based on size of ship and locatio
        #add coordinates to player's grid
        grid1.board.append(created_coords)

        grid1.print_ship_coordinates(created_coords, direction,grid) #loop through coords for ship to print out on displayed grid

and top of my Board class:

BOARD_SIZE = 10

class Board:
    board = []

    def __init__(self, grid):
        self.grid = [['O']*BOARD_SIZE for _ in range(BOARD_SIZE)]
10
  • Can you show your grid1.board? Commented Mar 10, 2017 at 0:38
  • 1
    Python doesn't check the sublists for an item when it searches the list. Since guess will never be one of the sublists (it is always a string), the if will never be evaluated as True. Commented Mar 10, 2017 at 0:42
  • 1
    See this: stackoverflow.com/q/1156087/5827958 Commented Mar 10, 2017 at 0:45
  • 1
    [['O']*BOARD_SIZE for _ in range(BOARD_SIZE)] this will probably cause problems because each of the elements in those lists all point to the same thing. Try e.g. L = [ [6, 7] ]*5; L[0].append(8); L Commented Mar 10, 2017 at 0:45
  • 1
    Also, see this: stackoverflow.com/q/26167566/5827958 Commented Mar 10, 2017 at 0:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.