Advertisement
Guest User

Untitled

a guest
Nov 15th, 2019
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.27 KB | None | 0 0
  1. # Programming Assignment 2
  2. # Dylan Hagen
  3. # 10/24/2019
  4. alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
  5. 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  6.  
  7.  
  8. def board(level):
  9. # --- construct initial board
  10. period_str = '.'
  11. asterisk_str = '*'
  12. game_board = []
  13. board_size = 10 + (level - 1) * 2 # 8 + level * 2
  14.  
  15. # creating a two-dimentional list
  16. for n in range(1, board_size + 1):
  17. # creating a row in the table
  18. row = []
  19. for k in range(1, board_size + 1):
  20. if n < board_size // 2 + 1:
  21. row.append(period_str)
  22. else:
  23. row.append(asterisk_str)
  24. # appending each row to the game_borad
  25. game_board.append(row)
  26.  
  27. return (game_board)
  28.  
  29.  
  30. def displayBoard(game_board):
  31. # ---- display a board
  32. board_size = len(game_board)
  33.  
  34. print('\nGame Board ...\n')
  35. print(format(' ', '<3'), end='')
  36.  
  37. # printing the letters for the columns' header
  38. for inc in range(0, board_size):
  39. print(format(chr(ord('A') + inc), '^3'), end='')
  40. print('\n')
  41.  
  42. # printing the actual board using a nested loops
  43. for row in range(0, board_size):
  44. print(format(row + 1, '<3'), end='')
  45.  
  46. for col in range(0, board_size):
  47. print(format(game_board[row][col], '^3'), end='')
  48.  
  49. # label each side of game board
  50. if row == 2:
  51. print(format(' ', '<6'), "PLAYER'S SHIPS", end='')
  52. elif row == board_size // 2 + 2:
  53. print(format(' ', '<6'), "COMPUTER'S SHIPS", end='')
  54.  
  55. # display blank line between player's and computer's sides of board
  56. if row == board_size // 2 - 1:
  57. print('\n')
  58. else:
  59. print()
  60. print()
  61.  
  62.  
  63. def colHeading(gameboard):
  64. boardSize = len(gameboard)
  65. colHeading = []
  66. for i in range(boardSize):
  67. colHeading.append(chr(65 + i))
  68. return colHeading
  69.  
  70. def verticalPlace(game_board, row1, col1, row2, col2, ship):
  71. '''
  72. Purpose:
  73. Function takes the board and all the user inputs and places them on the board
  74. Returns: Nothing
  75. '''
  76. for i in range(int(row1), int(row2) + 1):
  77. game_board[i - 1][ord(col1) - 65] = ship
  78.  
  79.  
  80. def horizontalPlace(game_board, row1, col1, row2, col2, ship):
  81. '''
  82. Purpose:
  83. Function takes the board and all the user inputs and places them on the board
  84. Returns: Nothing
  85. '''
  86. newCol1 = ord(col1) - 65
  87. newCol2 = ord(col2) - 65
  88. for i in range(newCol1, newCol2 + 1):
  89. game_board[int(row1) - 1][i] = ship
  90.  
  91. def verticalCollision(game_board, row1, col1, row2, col2):
  92. '''
  93. Purpose:
  94. Function takes the board and all the user inputs and checks if that cell is taken
  95. Returns: Boolean value
  96. '''
  97. for i in range (int(row1), int(row2)+1):
  98. if game_board[i-1][ord(col1) - 65] != '.':
  99. return False
  100. return True
  101.  
  102. def horizontalCollision(game_board, row1, col1, row2, col2):
  103. '''
  104. Purpose:
  105. Function takes the board and all the user inputs and checks if that cell is taken
  106. Returns: Boolean value
  107. '''
  108. newCol1 = ord(col1) - 65
  109. newCol2 = ord(col2) - 65
  110. for i in range(newCol1, newCol2 + 1):
  111. if game_board[int(row1) - 1][i] != '.':
  112. return False
  113. return True
  114.  
  115. def formatVerification(game_board, userStartRow, userStartCol, userEndRow, userEndCol, ship):
  116. '''
  117. Purpose:
  118. Function takes the board and all the user inputs and checks if the input is wrong in any way
  119. Returns: errorCode
  120. '''
  121. errorCode = 0 # Used to print which condition the user broke.
  122. while userStartCol not in alphabet or userEndCol not in alphabet:
  123. errorCode = 1
  124. return errorCode
  125. while not str(userStartRow).isdigit() or not str(userEndRow).isdigit():
  126. errorCode = 2
  127. return errorCode
  128. if userStartCol not in colHeading(game_board) or userEndCol not in colHeading(game_board):
  129. errorCode = 8 # Order is incorrect because I just discovered this bug
  130. return errorCode
  131. while not verticalCollision(game_board, int(userStartRow), userStartCol, int(userEndRow), userEndCol):
  132. errorCode = 3
  133. return errorCode
  134. while not horizontalCollision(game_board, int(userStartRow), userStartCol, int(userEndRow), userEndCol):
  135. errorCode = 4
  136. return errorCode
  137. while userStartCol != userEndCol and userStartRow != userEndRow:
  138. errorCode = 5
  139. return errorCode
  140. while ord(userStartCol) > ord(userEndCol) or userStartRow > userEndRow:
  141. errorCode = 6
  142. return errorCode
  143. if (int(userEndRow) + 1 + ord(userEndCol) - 64) - (int(userStartRow) + ord(userStartCol) - 64) != ship:
  144. errorCode = 7
  145. return errorCode
  146.  
  147. return errorCode
  148.  
  149.  
  150.  
  151. # you only need to complete the following function (playerShipPosition)
  152. def playerShipPosition(game_board):
  153. print('Enter location of each of specified size (e.g. A1:A5)')
  154. ship_lengths = [5, 4, 3, 3, 2]
  155. ship_names = ['aircraft carrier', 'battleship', 'cruiser', 'submarine', 'destroyer']
  156. ship_codings = ['a', 'b', 'c', 's', 'd']
  157.  
  158. # get an input
  159. for i in range(len(ship_lengths)):
  160.  
  161. mesg = ship_names[i] + '(' + str(ship_lengths[i]) + '): '
  162. userInput = input(mesg)
  163. while ':' not in str(userInput): # If colon isn't in input, start,end breaks program.
  164. userInput = input('Input is in the incorrect format. Enter with correct format: ')
  165. while userInput.count(':') > 1: # If colon appears more than once, start,end gets unpack error.
  166. userInput = input('Input is in the incorrect format. Enter with correct format: ')
  167. start, end = userInput.split(':')
  168. userStartCol = start[0].upper()
  169. userStartRow = (start[1:])
  170. userEndCol = end[0].upper()
  171. userEndRow = (end[1:])
  172. # user variables take index of input for value extraction
  173. errorCode = formatVerification(game_board, userStartRow,
  174. userStartCol, userEndRow, userEndCol, ship_lengths[i])
  175. while errorCode != 0:
  176. errorList = ['', 'Input is in the incorrect format. ', 'Input is in the incorrect format',
  177. 'That space is already taken.', 'That space is already taken',
  178. 'You cannot place ships diagonally', 'You cannot place ships backwards',
  179. 'Ship is the incorrect length', 'Position does not exist']
  180. # List is used to print index of error code
  181. print(errorList[errorCode])
  182. userInput = input(mesg)
  183. while ':' not in str(userInput):
  184. userInput = input('Input is in the incorrect format. Enter with correct format: ')
  185. while userInput.count(':') > 1:
  186. userInput = input('Input is in the incorrect format. Enter with correct format: ')
  187. start, end = userInput.split(':')
  188. userStartCol = start[0].upper()
  189. userStartRow = (start[1:])
  190. userEndCol = end[0].upper()
  191. userEndRow = (end[1:])
  192. errorCode = formatVerification(game_board, userStartRow,
  193. userStartCol, userEndRow, userEndCol, ship_lengths[i])
  194.  
  195. if userStartCol == userEndCol:
  196. verticalPlace(game_board, userStartRow, userStartCol, userEndRow, userEndCol, ship_codings[i])
  197. if userStartCol != userEndCol:
  198. horizontalPlace(game_board, userStartRow, userStartCol, userEndRow, userEndCol, ship_codings[i])
  199. displayBoard(game_board)
  200. start, end = userInput.split(':')
  201. print(start, end)
  202.  
  203. # You may have separate functions for the followings and call them here:
  204. # Figure out if the ship is vertical or horizontal
  205. # and in what cells it is going to be located.
  206. # validate userInput: (e.g., number of characters, valid area, ...)
  207. # make sure there is no collision
  208. # place it on the board
  209.  
  210.  
  211. def computerShipPosition(game_board):
  212. import random
  213. # --- randomly position computer's ships
  214. ship_names = ['aircraft carrier', 'battleship', 'cruiser', 'submarine', 'destroyer']
  215. ship_lengths = [5, 4, 3, 3, 2]
  216. ship_codings = ['a', 'b', 'c', 's', 'd']
  217. for current_ship in range(len(ship_names)):
  218. # get length of current ship
  219. length = ship_lengths[current_ship]
  220.  
  221. # place horizontially or vertically based on even/odd random number
  222. if random.randint(1, 10) % 2 == 0:
  223.  
  224. # position horizontally
  225. placed_without_collision = False
  226.  
  227. while not placed_without_collision:
  228. # generate random ship location,(row, col),within bottom half
  229. # of board for horizontal placement, accounting for its length
  230. loc = (random.randint(len(game_board) // 2, len(game_board) - 1),
  231. random.randint(0, len(game_board) - length))
  232. # check for collisions
  233. collision_found = False
  234. col_incr = 0
  235. while col_incr < ship_lengths[current_ship] and \
  236. not collision_found:
  237. if game_board[loc[0]][loc[1] + col_incr] != '*':
  238. collision_found = True
  239. else:
  240. col_incr = col_incr + 1
  241.  
  242. if not collision_found:
  243. placed_without_collision = True
  244.  
  245. # place ship on board
  246. for col_incr in range(ship_lengths[current_ship]):
  247. game_board[loc[0]][loc[1] + col_incr] = ship_codings[current_ship]
  248. else:
  249.  
  250. # position vertically
  251. placed_without_collision = False
  252.  
  253. while not placed_without_collision:
  254.  
  255. # generate random location, (row, col), within bottom half
  256. # of board for vertical placement, accounting for its length
  257. loc = (random.randint(len(game_board) // 2,
  258. len(game_board) - length),
  259. random.randint(0, len(game_board) - 1))
  260.  
  261. # check for collisions
  262. collision_found = False
  263. for row_incr in range(ship_lengths[current_ship]):
  264. if game_board[loc[0] + row_incr][loc[1]] != '*':
  265. collision_found = True
  266.  
  267. if not collision_found:
  268. placed_without_collision = True
  269.  
  270. # place ship on board
  271. for row_incr in range(ship_lengths[current_ship]):
  272. game_board[loc[0] + row_incr][loc[1]] = ship_codings[current_ship]
  273.  
  274.  
  275. def main():
  276. # step1: get the level from user and error handling
  277. level = input('Please enter the level of play (1-9): ')
  278. while (not level.isdigit()) or int(level) > 9 or int(level) < 1:
  279. level = input('Please enter the level of play (1-9): ')
  280.  
  281. level = int(level)
  282. game_board = board(level)
  283. # displayBorad(game_board)
  284. computerShipPosition(game_board)
  285. displayBoard(game_board)
  286.  
  287. playerShipPosition(game_board)
  288.  
  289. print('\nGAME STARTED...\n')
  290. displayBoard(game_board)
  291.  
  292.  
  293. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement