Skip to content

Instantly share code, notes, and snippets.

@DZuz14
Created June 30, 2017 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DZuz14/a59c0c94840b6a228ec8b03a4c8f9f14 to your computer and use it in GitHub Desktop.
Save DZuz14/a59c0c94840b6a228ec8b03a4c8f9f14 to your computer and use it in GitHub Desktop.
Python Battleship
from random import randint
board = []
# create the 5 x 5 board
for x in range(0, 5):
board.append(["O"] * 5)
board_index = len(board) - 1
# displays an easier to read board
def print_board(board):
for row in board:
print " ".join(row)
print_board(board)
# helpers for selecting random coordinates
def random_row(board):
return randint(0, board_index)
def random_col(board):
return randint(0, board_index)
# Set the coordinates of the battleship
ship_row = random_row(board)
ship_col = random_col(board)
# Used to print turn number to user
turn = 0
for i in range(board_index):
turn += 1
print 'Turn %d' % turn
# Takes coordinate guess input from the user
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
# Handle win or wrong guesses
if guess_row == ship_row and guess_col == ship_col:
print 'Congratulations! You sank my battleship!'
break
elif guess_row <= board_index and guess_col <= board_index:
if board[guess_row][guess_col] == 'X':
print "You guessed that one already."
else:
print 'You missed my battleship!'
board[guess_row][guess_col] = 'X'
print_board(board)
else:
if guess_row > board_index or guess_col > board_index:
print "Oops, that's not even in the ocean."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment