Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This must be in Python and can\'t use print(). It must be return. Connect Four!

ID: 3593544 • Letter: T

Question

This must be in Python and can't use print(). It must be return.

Connect Four!

Connect Four is a game where players win by placing four of their pieces in a row, either horizontally, vertically, or diagonally. The board is a vertical plane with a limited number of columns; playing a piece in a column will drop to the lowest available space. Players take turns dropping pieces into columns, trying to get four in a row before their opponent does.

Representations

We will represent the board as a list of lists of values; the overall list is really a list of rows, and each row is a list of the items in the row. We represent each space with a single-character string. Look at the example below for both the picture and the corresponding grid representation.

• empty spaces are represented by a period "."

• player pieces are represented by upper-case letters.

• a board is of any finite rectangular size. Always indicate the number of rows before number of columns.

o in this spec, we use board as convenient shorthand for a list of lists of length-one strings.

o only non-negative indexes are allowed (Python doesn't enforce it but our program should).

o only length-one strings are allowed in the inner lists.

o a board is "valid" when it is rectangular, has at most two colors in it, no floating pieces, and no more that one extra move for some player. Otherwise it's a least a list of lists of length-1 strings.

• a coord is a pair of row- and col- indexes, e.g. (0,0), (2,3), (5,1). Only non-negative indexes allowed.

• a color is a single upper-case letter.

• a run is our terminology for four pieces of the same color in a line. We don't care which direction it goes. Indexing into the Board When we have a grid, we have two dimensions. The first dimension indicates the row (top row to bottom row), and the second dimension indicates the column (left column to right column). Thus with N rows and M columns, we have a grid with indexes as shown to the right. Here we define some sample boards, which are used (by name) in examples through the definitions below. The direct board definitions are given, as well as the print(show_board(ex)) outputs to the right (which is easier to understand).

What can I use? You may only use the following things. You may ask about adding things to a list, but we are unlikely to add anything. If you use something disallowed, it's not an honor code violation, you just won't get points.

Restrictions

• no modules may be imported.

Allowed

• basic statements, variables, operators, del, indexing, slicing, in, are all allowed

• any form of control flow we've covered is allowed (if/else, loops, etc)

• only these built-in functions: range(), len(), int(), str(), list(), abs()

• only these built-in methods: s.split(), s.join(), s.pop(), xs.append(), xs.extend(), xs.insert(), s.format()

• calling other functions of the project (and your own helper functions). Please do this! J Hint In our solution, we only used range, len, in, abs, .append(), .join(), .split(), and list().

Extra Credit

This last function is more challenging, but still only uses the same skills as before.

def winning_move(board,color): Find a column that will win the game for color in a single move, and return that column index. When multiple columns offer a win, report the leftmost column. If no one-move win exists, return None.

• Assume: board is a board.

• winning_move(ex6,"X") 5

• winning_move(ex6,"O") 1 # leftmost column that wins for 'O'

• winning_move(ex1,"O") None # game is already over!

Explanation / Answer

def init_board(num_rows, num_cols):
board = []
for i in range(num_rows):
row = ['.']*num_cols
board.append(row)
return board
# print(init_board(2, 3))

def show_board(board):
boardstr = ''
for row in board:
boardstr += ''.join(row) + ' '
return boardstr
# print(show_board([['.', '.', '.'], ['A', 'B', 'A']]))

def read_board(s):
if not s:
return None
lines = []
  
tempLines = s.split(' ')
  
for line in tempLines:
if line:
lines.append(line)
  
col = len(lines[0])
row = 0
for i in range(len(lines)):
if len(lines[i]) != col:
return None
if lines[i] == ' ':
continue
row += 1
for c in lines[i]:
if not (c == '.' or c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
return None
  
  
board = init_board(row, col)
  
for i in range(row):
for j in range(col):
board[i][j] = lines[i][j]
return board
# print(read_board(".... NOO "))

def get_size(board):
if not board:
return None
row = len(board)
if row == 0:
return None
col = len(board[0])
return (row, col)
# print(get_size([['.', '.', '.'], ['A', 'B', 'A']]))

def is_valid_coord(board, r, c):
if r < 0 or c < 0:
return False
(row, col) = get_size(board)
if r >= row or c >= col:
return False
  
return True
# print(is_valid_coord([["B", ".", "R"], ["R", "R", "B"]], 0, 0))
# print(is_valid_coord([["B", ".", "R"], ["R", "R", "B"]], 2, 3))
# print(is_valid_coord([["B", ".", "R"], ["R", "R", "B"]], -1, -1))

def get_coords_by_color(board, color):
color_coord = []
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == color:
color_coord.append((i, j))
return color_coord
# print(get_coords_by_color([['G', '.'], ['Y', 'Y']], 'Y'))
# print(get_coords_by_color([['G', '.'], ['Y', 'Y']], 'G'))
# print(get_coords_by_color([['.', 'X'], ['Y', 'X']], 'X'))

def get_colors(board):
colors = []
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] != '.' and (not board[i][j] in colors):
colors.append(board[i][j])
return colors
# print(get_colors([['.', 'Y'], ['Y', 'X']]))

def count_pieces_by_color(board, color):
count = 0
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == color:
count += 1
return count
# print(count_pieces_by_color([['.', 'Y'], ['Y', 'X']], 'Y'))

def any_floating(board):
(row, col) = get_size(board)
for j in range(col):
color_found = False
for i in range(row):
if board[i][j] != '.':
color_found = True
elif board[i][j] == '.' and color_found:
return True
return False

def is_column_full(board, c):
(row, col) = get_size(board)
if c < 0 or c >= col:
return False
for i in range(row):
if board[i][c] == '.':
return False
return True

# print(is_column_full([['.', 'Y'], ['Y', 'X'], ['Y', 'X']], 0))
# print(is_column_full([['.', 'Y'], ['Y', 'X'], ['Y', 'X']], 99))
# print(is_column_full([['.', 'Y'], ['Y', 'X'], ['Y', 'X']], 1))

def place_one(board, c, color):
(row, col) = get_size(board)
if c < 0 or c >= col or is_column_full(board, c):
return False
  
for i in range(row-1, -1, -1):
if board[i][c] == '.':
board[i][c] = color
return True
return False

def pop_out(board, c, color):
(row, col) = get_size(board)
if c < 0 or c >= col or board[row-1][c] != color:
return False
for i in range(row-1, 0, -1):
board[i][c] = board[i-1][c]
board[0][c] = '.';
return True
# b = [['A', 'B'], ['B', 'A']]
# print(pop_out(b, 0, 'B'))
# print(b)

def check_horizontal(board, r, c):
(row, col) = get_size(board)
if not is_valid_coord(board, r, c):
return False
color = board[r][c]
if color == '.':
return False
count = 1
for j in range(c+1, col):
if count == 4:
break
if board[r][j] == color:
count += 1
else:
return False
return count == 4
# print(check_horizontal([['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B']], 0, 4))

def check_vertical(board, r, c):
(row, col) = get_size(board)
if not is_valid_coord(board, r, c):
return False
color = board[r][c]
if color == '.':
return False
count = 1
for i in range(r+1, row):
if count == 4:
break
if board[i][c] == color:
count += 1
else:
return False
return count == 4
# print(check_vertical([['A'], ['A'], ['A'], ['A'], ['A']], -1, -1))

def check_major_diagonal(board, r, c):
(row, col) = get_size(board)
if not is_valid_coord(board, r, c):
return False
color = board[r][c]
if color == '.':
return False
count = 1
j = c
for i in range(r+1, row):
j = j + 1
if j >= col:
break
if count == 4:
break
if board[i][j] == color:
count += 1
else:
return False
return count == 4

def check_minor_diagonal(board, r, c):
(row, col) = get_size(board)
if not is_valid_coord(board, r, c):
return False
color = board[r][c]
if color == '.':
return False
count = 1
j = c
for i in range(r-1, -1, -1):
j = j + 1
if j >= col:
break
if count == 4:
break
if board[i][j] == color:
count += 1
else:
return False
return count == 4

def is_board_full(board):
(row, col) = get_size(board)
for i in range(row):
for j in range(col):
if board[i][j] == '.':
return False
return True

def board21(): # one move for 'G', four in a diagonal
return [['.','.','.','.','.','.','.'],
['.','.','.','.','B','B','.'],
['.','.','B','G','G','G','.'],
['.','.','G','G','G','B','.'],
['.','G','B','B','G','B','.'],
['G','B','B','G','B','G','B']]
print(check_minor_diagonal(board21(),5,0))

def check_winner(board):
(row, col) = get_size(board)

winner_color = ''
won = False
for i in range(row):
for j in range(col):
if check_horizontal(board, i, j) or check_vertical(board, i, j) or check_major_diagonal(board, i, j) or check_minor_diagonal(board, i, j):
won = True
if winner_color and winner_color != board[i][j]:
return "tie!"
else:
winner_color = board[i][j]
if won:
return winner_color
elif is_board_full(board):
return "draw"
else:
return "pending"
  

# completed

def get_copy_of_board(board):
board_copy = []
for row in board:
newRow = []
for col in row:
newRow.append(col)
board_copy.append(newRow)
return board_copy

def winning_move(board,color):
if check_winner(board) != "pending":
return None
  
(row, col) = get_size(board)
  
for j in range(col):
board_copy = get_copy_of_board(board)
if place_one(board_copy, j, color):
if check_winner(board_copy) == color:
return j
return None

# code link: https://paste.ee/p/hQRu3

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote