Advertisement
Guest User

Battleship python code

a guest
Jul 27th, 2017
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. from random import randint
  2.  
  3. board = []
  4.  
  5. for x in range(5):
  6.     board.append(["O"] * 5)
  7.  
  8. def print_board(board):
  9.     for row in board:
  10.         print " ".join(row)
  11.  
  12. print "Let's play Battleship!"
  13. print
  14. print "Choose a row and a column which are numbers from 1 to 5. '1, 1' is the top left and '5, 5' is the bottom right. An 'X' will appear in the coordinates you have already chosen. You have five chances"
  15. print
  16. print_board(board)
  17. print
  18. print "Scroll up for information"
  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. print
  28.  
  29. for turn in range(4):
  30.     print "Turn", turn + 1
  31.  
  32.     guess_row = int(raw_input("Guess Row:")) -1
  33.     guess_col = int(raw_input("Guess Col:")) -1
  34.  
  35.     if guess_row == ship_row and guess_col == ship_col:
  36.         print "Congratulations! You sunk my battleship!"
  37.         break
  38.     else:
  39.         if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
  40.             print "Oops, that's not even in the ocean."
  41.         elif(board[guess_row][guess_col] == "X"):
  42.             print "You guessed that one already."
  43.         else:
  44.             print "You missed my battleship!"
  45.             board[guess_row][guess_col] = "X"
  46.  
  47.         print_board(board)
  48.  
  49.     if turn == 3:
  50.         print "Game Over"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement