Advertisement
AngelGeorgiev

Battleship game

May 12th, 2014
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.54 KB | None | 0 0
  1. from random import randint
  2. def battleship():
  3.     board = []
  4.     size = int(raw_input("Tell me the size of the field:"))
  5.     turns = int(raw_input("Tell me the turns you will use:"))
  6.     print
  7.    
  8.     for x in range(size):
  9.         board.append(["O"] * size)
  10.    
  11.     def print_board(board):
  12.         for row in board:
  13.             print " ".join(row)
  14.    
  15.     print "Let's play Battleship!"
  16.     print_board(board)
  17.     print
  18.    
  19.     def random_row(board):
  20.         return randint(0, len(board) - 1)
  21.    
  22.     def random_col(board):
  23.         return randint(0, len(board[0]) - 1)
  24.    
  25.     ship_row = random_row(board)
  26.     ship_col = random_col(board)
  27.    
  28.     for turn in range(turns):
  29.         guess_row = int(raw_input("Guess Row:"))-1
  30.         guess_col = int(raw_input("Guess Column:"))-1
  31.         print
  32.         if guess_row == ship_row and guess_col == ship_col:
  33.             print "Congratulations! You sunk my battleship!"
  34.             break
  35.         else:
  36.             if ( 0 > guess_row > len(board) - 1) or (0 > guess_col > len(board[0]) - 1):
  37.                 print "Oops, that's not even in the ocean."
  38.             elif (board[guess_row][guess_col] == "X"):
  39.                 print "You guessed that one already."
  40.             else:
  41.                 print "You missed my battleship!"
  42.                 board[guess_row][guess_col] = "X"
  43.             print "Turns taken: %i; Turns left: %i" % (turn + 1, turns - turn - 1)
  44.             print_board(board)
  45.             print
  46.         if turn == turns - 1:
  47.             print "Game Over"
  48.  
  49. battleship()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement