Test Run


#1


The console keeps saying list out of range when I put in five for either guess coordinates

it should put an X when the guess is within the rows and coulums


from random import randint

board = []

for x in range(0, 5):
    board.append(["O"] * 5)

def print_board(board):
    for row in board:
        print " ".join(row)

print_board(board)

def random_row(board):
    return randint(0, len(board))

def random_col(board):
    return randint(0, len(board))

ship_row = random_row(board)
ship_col = random_col(board)
gr = int(raw_input("Guess Row:"))
gc = int(raw_input("Guess Col:"))

print ship_row
print ship_col

# Write your code below!
if gr == ship_row and gc == ship_col:
    print "Congratulations! You sank my battleship!"
else: 
    if gr == range(5) or gc == range(5):
        print "Oops, that's not even in the ocean."
    elif board[gr][gc] == 'X':
        print "You guessed that one already."
    else:
        print "You missed my battleship!"
        board[gr][gc] = "X"
        print_board(board)


#2

this:

if gr == range(5) or gc == range(5):

won't work, how can a single number equal a list?

use the in keyword to check if gr and gc are in range


#3

Thank you, that helped but it keeps saying list index error. It has something to do with the elif function


#4

can i see an updated version of your code?


#5

from random import randint

board = []

for x in range(0, 5):
    board.append(["O"] * 5)

def print_board(board):
    for row in board:
        print " ".join(row)

print_board(board)

def random_row(board):
    return randint(0, len(board))

def random_col(board):
    return randint(0, len(board))

ship_row = random_row(board)
ship_col = random_col(board)
gr = int(raw_input("Guess Row:"))
gc = int(raw_input("Guess Col:"))

print ship_row
print ship_col

# Write your code below!
if gr == ship_row and gc == ship_col:
    print "Congratulations! You sank my battleship!"
else: 
    if gr in range(5) or gc in range(5):
        print "Oops, that's not even in the ocean."
    elif board[gr][gc] == 'X':
        print "You guessed that one already."
    else:
        print "You missed my battleship!"
        board[gr][gc] = 'X'
        print_board(board)

#6

you enter 5 as coordinate? that won't work, lists are zero index based so possible values are: 0, 1, 2, 3, 4


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.