Extra credit- A bit less quirky? Opinions


#1



Hi fellow programmers. I found it a bit quirky that top left square is designated row=0, column=0.... think about it,who will input a 0 , 0 unless they know that it has been programmed in Python and therefore first col and row are internally designated 0... so i did an attempt to swap it to:
square top_left r=>row=1,col=1
square bottom_right =>row=5, col=5

Here comes my code, please let me know your thoughts!!!!! (i am new to this)


# Import random int command
from random import randint
# Generates 5x5 board and stores it in empty list board
board = []
for x in range(5):
    board.append(["O"] * 5)
# Def function to print board w/o "" on O's.
def print_board(board):
    for row in board:
        print " ".join(row)
        
print "Let's play Battleship!"
print_board(board)
# Def functions to store random ship square:
# Added +1 to randomly generate sauqre (ship)
def random_row(board):
    return randint(1, len(board) - 1)

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

ship_row = random_row(board)
ship_col = random_col(board)
# Print funtions below to check rand sqaures (debugger)
#print ship_row
#print ship_col

# For loop for gameover attempts
for turn in range(4):
# Def functions for user square input:
    guess_row = int(raw_input("Guess Row:"))
    guess_col = int(raw_input("Guess Col:"))
# If statement for sinking condition:
    if guess_row == ship_row and guess_col == ship_col:
        print "Congratulations! You sunk my battleship!"
        break
# How to handle user erroneous input:
# Widen +1 range, increased lower margin from 0 to 1 and top from 4 to 5
    else:
        if (guess_row < 1 or guess_row > 5) or (guess_col < 1 or guess_col > 5):
            print "Oops, that's not even in the ocean."
#how to handle a "water" shot....and keep track of it if repeated.
        elif(board[guess_row-1][guess_col-1] == "X"):
            print "You guessed that one already."
        else:
            print "You missed my battleship!"
            board[guess_row-1][guess_col-1] = "X"
            print print_board(board)
            if turn == 3:
                print ("Game Over")
# Print (turn + 1) here!
    print (turn+1)

Replace this line with your code.


#2

That is a lot of fudging just to compensate. Note that ALL languages use zero-indexed arrays (lists) although some do have a command similar to,

option_base = 0
option_base = 1

All you really need to do is first tell the user the input range

int(raw_input("Guess Row (1..5): ")) - 1
int(raw_input("Guess Col (1..5): ")) - 1

Now all the rest of the code can remain as originally written.

Check for a win off the top, then test the range next.

if guess_row not in range(5) or guess_col not in range(5):

#3

Thanks! far more elegant solution....


#4

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