Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Programming Assignment 2
- # Dylan Hagen
- # 10/24/2019
- alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
- 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
- def board(level):
- # --- construct initial board
- period_str = '.'
- asterisk_str = '*'
- game_board = []
- board_size = 10 + (level - 1) * 2 # 8 + level * 2
- # creating a two-dimentional list
- for n in range(1, board_size + 1):
- # creating a row in the table
- row = []
- for k in range(1, board_size + 1):
- if n < board_size // 2 + 1:
- row.append(period_str)
- else:
- row.append(asterisk_str)
- # appending each row to the game_borad
- game_board.append(row)
- return (game_board)
- def displayBoard(game_board):
- # ---- display a board
- board_size = len(game_board)
- print('\nGame Board ...\n')
- print(format(' ', '<3'), end='')
- # printing the letters for the columns' header
- for inc in range(0, board_size):
- print(format(chr(ord('A') + inc), '^3'), end='')
- print('\n')
- # printing the actual board using a nested loops
- for row in range(0, board_size):
- print(format(row + 1, '<3'), end='')
- for col in range(0, board_size):
- print(format(game_board[row][col], '^3'), end='')
- # label each side of game board
- if row == 2:
- print(format(' ', '<6'), "PLAYER'S SHIPS", end='')
- elif row == board_size // 2 + 2:
- print(format(' ', '<6'), "COMPUTER'S SHIPS", end='')
- # display blank line between player's and computer's sides of board
- if row == board_size // 2 - 1:
- print('\n')
- else:
- print()
- print()
- def colHeading(gameboard):
- boardSize = len(gameboard)
- colHeading = []
- for i in range(boardSize):
- colHeading.append(chr(65 + i))
- return colHeading
- def verticalPlace(game_board, row1, col1, row2, col2, ship):
- '''
- Purpose:
- Function takes the board and all the user inputs and places them on the board
- Returns: Nothing
- '''
- for i in range(int(row1), int(row2) + 1):
- game_board[i - 1][ord(col1) - 65] = ship
- def horizontalPlace(game_board, row1, col1, row2, col2, ship):
- '''
- Purpose:
- Function takes the board and all the user inputs and places them on the board
- Returns: Nothing
- '''
- newCol1 = ord(col1) - 65
- newCol2 = ord(col2) - 65
- for i in range(newCol1, newCol2 + 1):
- game_board[int(row1) - 1][i] = ship
- def verticalCollision(game_board, row1, col1, row2, col2):
- '''
- Purpose:
- Function takes the board and all the user inputs and checks if that cell is taken
- Returns: Boolean value
- '''
- for i in range (int(row1), int(row2)+1):
- if game_board[i-1][ord(col1) - 65] != '.':
- return False
- return True
- def horizontalCollision(game_board, row1, col1, row2, col2):
- '''
- Purpose:
- Function takes the board and all the user inputs and checks if that cell is taken
- Returns: Boolean value
- '''
- newCol1 = ord(col1) - 65
- newCol2 = ord(col2) - 65
- for i in range(newCol1, newCol2 + 1):
- if game_board[int(row1) - 1][i] != '.':
- return False
- return True
- def formatVerification(game_board, userStartRow, userStartCol, userEndRow, userEndCol, ship):
- '''
- Purpose:
- Function takes the board and all the user inputs and checks if the input is wrong in any way
- Returns: errorCode
- '''
- errorCode = 0 # Used to print which condition the user broke.
- while userStartCol not in alphabet or userEndCol not in alphabet:
- errorCode = 1
- return errorCode
- while not str(userStartRow).isdigit() or not str(userEndRow).isdigit():
- errorCode = 2
- return errorCode
- if userStartCol not in colHeading(game_board) or userEndCol not in colHeading(game_board):
- errorCode = 8 # Order is incorrect because I just discovered this bug
- return errorCode
- while not verticalCollision(game_board, int(userStartRow), userStartCol, int(userEndRow), userEndCol):
- errorCode = 3
- return errorCode
- while not horizontalCollision(game_board, int(userStartRow), userStartCol, int(userEndRow), userEndCol):
- errorCode = 4
- return errorCode
- while userStartCol != userEndCol and userStartRow != userEndRow:
- errorCode = 5
- return errorCode
- while ord(userStartCol) > ord(userEndCol) or userStartRow > userEndRow:
- errorCode = 6
- return errorCode
- if (int(userEndRow) + 1 + ord(userEndCol) - 64) - (int(userStartRow) + ord(userStartCol) - 64) != ship:
- errorCode = 7
- return errorCode
- return errorCode
- # you only need to complete the following function (playerShipPosition)
- def playerShipPosition(game_board):
- print('Enter location of each of specified size (e.g. A1:A5)')
- ship_lengths = [5, 4, 3, 3, 2]
- ship_names = ['aircraft carrier', 'battleship', 'cruiser', 'submarine', 'destroyer']
- ship_codings = ['a', 'b', 'c', 's', 'd']
- # get an input
- for i in range(len(ship_lengths)):
- mesg = ship_names[i] + '(' + str(ship_lengths[i]) + '): '
- userInput = input(mesg)
- while ':' not in str(userInput): # If colon isn't in input, start,end breaks program.
- userInput = input('Input is in the incorrect format. Enter with correct format: ')
- while userInput.count(':') > 1: # If colon appears more than once, start,end gets unpack error.
- userInput = input('Input is in the incorrect format. Enter with correct format: ')
- start, end = userInput.split(':')
- userStartCol = start[0].upper()
- userStartRow = (start[1:])
- userEndCol = end[0].upper()
- userEndRow = (end[1:])
- # user variables take index of input for value extraction
- errorCode = formatVerification(game_board, userStartRow,
- userStartCol, userEndRow, userEndCol, ship_lengths[i])
- while errorCode != 0:
- errorList = ['', 'Input is in the incorrect format. ', 'Input is in the incorrect format',
- 'That space is already taken.', 'That space is already taken',
- 'You cannot place ships diagonally', 'You cannot place ships backwards',
- 'Ship is the incorrect length', 'Position does not exist']
- # List is used to print index of error code
- print(errorList[errorCode])
- userInput = input(mesg)
- while ':' not in str(userInput):
- userInput = input('Input is in the incorrect format. Enter with correct format: ')
- while userInput.count(':') > 1:
- userInput = input('Input is in the incorrect format. Enter with correct format: ')
- start, end = userInput.split(':')
- userStartCol = start[0].upper()
- userStartRow = (start[1:])
- userEndCol = end[0].upper()
- userEndRow = (end[1:])
- errorCode = formatVerification(game_board, userStartRow,
- userStartCol, userEndRow, userEndCol, ship_lengths[i])
- if userStartCol == userEndCol:
- verticalPlace(game_board, userStartRow, userStartCol, userEndRow, userEndCol, ship_codings[i])
- if userStartCol != userEndCol:
- horizontalPlace(game_board, userStartRow, userStartCol, userEndRow, userEndCol, ship_codings[i])
- displayBoard(game_board)
- start, end = userInput.split(':')
- print(start, end)
- # You may have separate functions for the followings and call them here:
- # Figure out if the ship is vertical or horizontal
- # and in what cells it is going to be located.
- # validate userInput: (e.g., number of characters, valid area, ...)
- # make sure there is no collision
- # place it on the board
- def computerShipPosition(game_board):
- import random
- # --- randomly position computer's ships
- ship_names = ['aircraft carrier', 'battleship', 'cruiser', 'submarine', 'destroyer']
- ship_lengths = [5, 4, 3, 3, 2]
- ship_codings = ['a', 'b', 'c', 's', 'd']
- for current_ship in range(len(ship_names)):
- # get length of current ship
- length = ship_lengths[current_ship]
- # place horizontially or vertically based on even/odd random number
- if random.randint(1, 10) % 2 == 0:
- # position horizontally
- placed_without_collision = False
- while not placed_without_collision:
- # generate random ship location,(row, col),within bottom half
- # of board for horizontal placement, accounting for its length
- loc = (random.randint(len(game_board) // 2, len(game_board) - 1),
- random.randint(0, len(game_board) - length))
- # check for collisions
- collision_found = False
- col_incr = 0
- while col_incr < ship_lengths[current_ship] and \
- not collision_found:
- if game_board[loc[0]][loc[1] + col_incr] != '*':
- collision_found = True
- else:
- col_incr = col_incr + 1
- if not collision_found:
- placed_without_collision = True
- # place ship on board
- for col_incr in range(ship_lengths[current_ship]):
- game_board[loc[0]][loc[1] + col_incr] = ship_codings[current_ship]
- else:
- # position vertically
- placed_without_collision = False
- while not placed_without_collision:
- # generate random location, (row, col), within bottom half
- # of board for vertical placement, accounting for its length
- loc = (random.randint(len(game_board) // 2,
- len(game_board) - length),
- random.randint(0, len(game_board) - 1))
- # check for collisions
- collision_found = False
- for row_incr in range(ship_lengths[current_ship]):
- if game_board[loc[0] + row_incr][loc[1]] != '*':
- collision_found = True
- if not collision_found:
- placed_without_collision = True
- # place ship on board
- for row_incr in range(ship_lengths[current_ship]):
- game_board[loc[0] + row_incr][loc[1]] = ship_codings[current_ship]
- def main():
- # step1: get the level from user and error handling
- level = input('Please enter the level of play (1-9): ')
- while (not level.isdigit()) or int(level) > 9 or int(level) < 1:
- level = input('Please enter the level of play (1-9): ')
- level = int(level)
- game_board = board(level)
- # displayBorad(game_board)
- computerShipPosition(game_board)
- displayBoard(game_board)
- playerShipPosition(game_board)
- print('\nGAME STARTED...\n')
- displayBoard(game_board)
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement