11.Danger, Will Robinson!


#1

Hi guys! This is not an error report just a fix for a better "player" experience of the game! If we use the code that is expected:

guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))

print ship_row
print ship_col

if ship_row == guess_row and ship_col == guess_col:
    print "Congratulations! You sank my battleship!"

when the player types 2 for row and 3 for col he actually guess 3/4 because python counts the indexes from 0 to 4 in the row and col lists. Which even prints out the wrong board afterwards when you get the X mark on the players' wrong guesses. So my solution is this:

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

def random_col(board):
    return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)
guess_row = int(raw_input("Guess Row:")) - 1
guess_col = int(raw_input("Guess Col:")) - 1

print ship_row
print ship_col

if ship_row == (guess_row +1)and ship_col == (guess_col+1):
    print "Congratulations! You sank my battleship!"
else:
    print "You missed my battleship!"
        
    board[guess_row][guess_col]="X"
    print_board(board)

Basically I tried to compensate for the fact our "player" will not choose from 0 to 4 but 1 to 5 since hes not a programmer. And in the win condition I added one to both guess_row and col variables so that the first correction does not mess up the rest of the program. I am just wondering if that is ok or does it mess up the rest of the program ?:slight_smile:


#2

@lordvetinari: That's okay.
You can also inform the user which positions he can choose from a given range, i.e. 0 to 4.

I think this is the beginning of the game so just a reminder: don't forget to check if the chosen position is greater than 4.