from random import randint print "BATTLESHIP" print "The rows and columns are numbered 0-4 so don't guess five or higher" print # Lines 7 - 16 create the board 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) # Lines 19 - 26 randomly determine where the ship is. 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) # Lines 29 - 50 count your turns, determine if you win, determine if you miss, and determine if the game is over. for turn in range(5): # Line 28 is the turn counter print "Turn", turn + 1 #Lines 33 - 34 create the imputs for the guesses guess_row = int(raw_input("Guess Row: ")) guess_col = int(raw_input("Guess Col: ")) # These lines determine the outcome of a shot print guess_row + guess_col if guess_row == ship_row and guess_col == ship_col: print "Congratulations! You sank my battleship!" break else: if guess_row not in range(5) or \ guess_col not in range(5): print "Oops, that's not even in the ocean." elif board[guess_row][guess_col] == "X": print "You guessed that one already." else: print "You missed my battleship!" board[guess_row][guess_col] = "X" if (turn == 4): print "GAME OVER" print_board(board)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question