#importing "random integer" from "random" functions from random import randint #making a "board" list board = [] #creating the original board for x in range(0, 5): board.append(["O"] * 5) #printing board w/o qoutes def print_board(board): for row in board: #this allows to print list elements using anything - here printing with spaces b/w elements print " ".join(row) #printing original board print_board(board) #random row where the ship will be def random_row(board): return randint(0, len(board) - 1) #random column where the ship will be def random_col(board): return randint(0, len(board[0]) - 1) #puting the ship in that random row & colum ship_row = random_row(board) ship_col = random_col(board) #<<Printing ship's row & col for debugging>> print ship_row print ship_col #<<Printing ship's row & col for debugging>> #asking user to guess the row guess_row = int(raw_input("Guess Row:")) #asking user to guess the col guess_col = int(raw_input("Guess Col:")) #if guess is same as ship, user wins if guess_row == ship_row and guess_col == ship_col: #display win message print "Congratulations! You sank my battleship!" #if guess is not same as ship else: #if row/column is outside board if guess_row != range(5) and guess_col != range(5): #based on T or F = T & T and F = F logic #outside baord message print "Oops, that's not even in the ocean." #already marked w/"X" elif board[guess_col][guess_row]=="X": print "You guessed that one already." else: #marking the guess with an "X" board[guess_col][guess_row]="X" #display lose message print "You missed my battleship!" #printing board with "X" 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