Skip to content

Instantly share code, notes, and snippets.

@the-frey
Created April 12, 2013 09:38
Show Gist options
  • Save the-frey/5370853 to your computer and use it in GitHub Desktop.
Save the-frey/5370853 to your computer and use it in GitHub Desktop.
Adaptation of the single-square Battleship game from the Codecademy Python course to use the setup/game loop pattern favoured by Al Sweigart in his Python games book. Variable board size introduced too.
from random import randint
board = []
print '''
Welcome to Battleship! First, let's set up the board...
'''
board_size = raw_input("What board size do you want to play?")
board_size = int(board_size)
for x in range(0, board_size):
board.append(["O"] * board_size)
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)
print '''
Please note: column 1 and row one are represented by 0.
Good luck, commander!
'''
game_over = False
while game_over == False:
def print_board(board):
for row in board:
print " ".join(row)
print_board(board)
guess_row = raw_input("Guess Row:")
guess_col = raw_input("Guess Col:")
if guess_row == '':
print "Invalid Row."
guess_row = raw_input("Guess Row:")
elif guess_col == '':
print "Invalid Col."
guess_col = raw_input("Guess Col:")
guess_row = int(guess_row)
guess_col = int(guess_col)
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sank my battleship!"
game_over = True
else:
if guess_row > len(board)-1 or guess_col > len(board)-1:
print "Oops, that's not even in the ocean."
elif board[guess_row][guess_col] == "X":
print "You guessed that one already."
else:
board[guess_row][guess_col] = "X"
print "You missed my battleship!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment