Advertisement
Guest User

Refactored place_twoship

a guest
Feb 26th, 2017
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.07 KB | None | 0 0
  1. import random
  2.  
  3. # Convert compass direction to row & column increments
  4. delta = {
  5.     'S': (1, 0),
  6.     'N': (-1, 0),
  7.     'E': (0, 1),
  8.     'W': (0, -1),
  9. }
  10.  
  11. num_rows = 4
  12. num_cols = 6
  13.  
  14. def make_board():
  15.     return [['0'] * num_cols for _ in range(num_rows)]
  16.  
  17. def print_board(board):
  18.     print('\n'.join([' '.join(row) for row in board]), end='\n\n')
  19.  
  20. def place_twoship(board):
  21.     ship_placed = False
  22.     x = random.randrange(num_rows)
  23.     y = random.randrange(num_cols)
  24.     while not ship_placed:
  25.         direction = random.choice("NSEW")
  26.         dx, dy = delta[direction]
  27.         nx, ny = x + dx, y + dy
  28.         print(x, y, direction, nx, ny)
  29.         if 0 <= nx < num_rows and 0 <= ny < num_cols:
  30.             board[x][y] = "2"
  31.             board[nx][ny] = "2"
  32.             twoshipcord.extend([(x, y), (nx, ny)])
  33.             flippedbattleshipstwo.extend([(y, x), (ny, nx)])
  34.             ship_placed = True
  35.  
  36. board = make_board()
  37. twoshipcord = []
  38. flippedbattleshipstwo = []
  39.  
  40. place_twoship(board)
  41. print_board(board)
  42. print(twoshipcord, flippedbattleshipstwo)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement