Question: part 2 please consider part 1 please make the changes in my code and please do not provide different codes and make sure that they
part 2 please consider part 1








please make the changes in my code and please do not provide different codes and make sure that they pass the test cases and gives the expected output please refer to part 1
Hey can someone help me out by modifying my code based on the changes required and please ensure that all the test cases meet the expected output. Please make sure that the updated code would pass all the test cases giving the appropriate output. Please don't provide a sample code or something similar I have wasted most of my questions by getting them please modify my code to get the expected this is a code for a game of go in python. the exercise description and expected output of the test cases will be provided below the code. please modify the code and provide the modified version without errors as I have tried as much as i can but i keep on messing it up from collections import deque def load_board(filename): result = " " with open(filename) as f: print(f) for index, line in enumerate(f): if index == 0: result += ' '+' '.join([chr(alphabets + 65) for alphabets in range(len(line) - 1)]) + ' ' # the alphabetical column heading result += f"{19 - index:2d}" result += ' ' + ' '.join(line.strip()) + ' ' return result
def save_board(filename, board): with open(filename, "wt") as f: f.write(str(board)) from string import ascii_uppercase as letters class Board: #Dictionary created for the colours and the respected symbols points = {'E': '.', 'B': '@', 'W': 'O'}
#Constructor def __init__(self,board,size=19,from_strings=None): assert 2
def get_size(self): #Returns the size of the grid created by the constructor return self.size
def __str__(self): # creating the grid padding = ' ' # Creating a variable with a space assigned so that it acts as a padding to the rows that have a single digit heading = ' ' + ' '.join(letters[:self.size]) # Alphabetical heading is created lines = [heading] # adding the alphabetical heading into a list named lines to which the rows will be added later for r, row in enumerate(self.grid): if len(self.grid) 9: # for rows 1 to 9 the single digits are aligned according to the first digit from the right of the two digit rows if (self.from_strings): line = f'{self.size - r} ' + ' '.join(self.from_strings[r]) else: line = f'{self.size - r} ' + ' '.join(self.points[x] for x in row) line = padding + line # adding the space using the variable padding to the row created lines.append(line) # adding the row to the list of rows else: # for the rows 10 onwards - as there is no requirement to add a padding it is not added here if (self.from_strings): line = f'{self.size - r} ' + ' '.join(self.from_strings[r]) else: line = f'{self.size - r} ' + ' '.join(self.points[x] for x in row) # creation of the row lines.append(line) # adding the newly created row to the list of rows return ' '.join(lines)
def _to_row_and_column(self, coords): # destructure coordinates like "B2" to "B" and 2 alpha, num = coords colnum = ord(alpha) - ord('A') + 1 rownum = self.size - int(num) + 1 assert 1
def set_colour(self, coords, colour_name): rownum, colnum = self._to_row_and_column(coords) assert len(coords)==2 or len(coords)==3, "invalid coordinates" assert colour_name in self.points,"invalid colour name" self.grid[rownum - 1][colnum - 1] = colour_name
def get_colour(self, coords): rownum, colnum = self._to_row_and_column(coords) return self.grid[rownum - 1][colnum - 1]
def to_strings(self): #padding = ' ' lines = [] for r, row in enumerate(self.grid): if self.from_strings: lines.append(''.join(self.from_strings[r])) else: lines.append(''.join(self.points[x] for x in row)) return lines
def to_integer(self): digit_colour="" for line in self.to_strings(): for character in line: if character=='.': character=0 elif character=='O': character=1 elif character=='@': character=2 character=str(character) digit_colour+=character return int(digit_colour,3)
# return ''.join(self.to_int[x] for line in self.grid for x in line)
def set_from_integer(self, integer_encoding): n = int(integer_encoding) list1 = [] p=[] m=[] t=[] while n != 0: rem = n % self.size #3 list1.append(rem) n = n // self.size#3 list1.reverse() list1=["." if item ==0 else item for item in list1] list1=["O" if item ==1 else item for item in list1] list1=["@" if item ==2 else item for item in list1] for i in range(0,len(list1),self.size):#3 p.append(list1[i:i+self.size])#3 #print(p) for x in p: m=''.join(map(str,x)) t.append(m) #print(Board(self.size,t)) self.from_strings=t
def fill_reaching(self,colour_name,reach_name, visited, r, c): new_list = [] new_list2 = [] for x in self.from_strings: for y in x: if y == ".": y = "E" elif y == "@": y = "B" elif y == "O": y = "W" new_list.append(y) for i in range(0, len(new_list), self.size): new_list2.append(new_list[i:i + self.size]) self.grid = new_list2 if r = self.size or c = self.size: #Checking whether the number of rows are within the size of the grid return False if visited[r][c] or self.grid[r][c] != colour_name:#Checking whether the number of columns are within the size of the grid return False if self.grid[r][c] == reach_name: return True visited[r][c] = True if self.fill_reaching(colour_name, reach_name, visited, r + 1, c): return True if self.fill_reaching(colour_name, reach_name, visited, r - 1, c): return True if self.fill_reaching(colour_name, reach_name, visited, r, c + 1): return True if self.fill_reaching(colour_name, reach_name, visited, r, c - 1): return True return False
def reaching_empty_matrix(self): # Create a matrix of the same size as the board, filled with False values matrix = [[False for i in range(self.size)] for j in range(self.size)] #false for the empty grid # Iterate over the points on the board print(self.grid[1][0]) for i in range(self.size): for j in range(self.size): # If the current point is empty or an "O" point, perform a BFS from this point if self.grid[i][j] == "." or self.grid[i][j] == "O": queue = deque([(i, j)]) matrix[i][j] = True while queue: r, c = queue.popleft() for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): new_r = r + dr new_c = c + dc # If the new point is within the bounds of the board and has not been visited, add it to the queue and mark it as visited if 0
def is_legal(self): # Iterate over the points on the board for i in range(self.size): for j in range(self.size): # Skip empty points if self.board[i][j] == ".": continue # Check the surrounding points for any illegal positions for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): new_r = i + dr new_c = j + dc # If the new point is out of bounds or empty, or if it has a different color than the current point, the position is illegal if not (0




I have added part 1 into the question
hi there's an issue with updating the info I can't change the order for some reason so the newly added info goes to the bottom I guess
I have added that part earlier I just can't edit the entire question I can only add the new parts
and create a file 119b.txt which is identical to 119. txt. Task 3 Extend the constructor of class Board to accept an additional optional argument from_strings. If present, this argument must be a list of strings where each string represents a row of the board with the character encoding used in the _ _str__ ( ) method, but without the intervening spaces and the coordinate letters. For example, for a board of size 19 , from_strings must be a list of 19 strings, each having exactly 19 characters from the set ".@0". Check the validity of from_strings and raise AssertionError s with the following messages for invalid inputs (the letter x should indicate the row coordinate of the invalid row): "input is not a list" "length of input list does not match size" "row x is not a string" "length of row x does not match size" "invalid character in row x " Implement a method to_strings(self) that returns a representation of the board as a list of strings in the same format as that accepted by the init__() method. Outside the class, define a function load_board(filename) that takes as an argument the name of a text file, reads a Go position from that file and returns a Board object representing the position. The file must contain one line for each row of the board, using the characters ".", "@", and "0" as above to represent the colours. Define a function save_board(filename, board) that takes as arguments a filename and a Board object and saves the position to a text file in the same format as that accepted by load_board(). In class Board, define two new methods: - to_integer(self) returns an integer encoding of the position - set_from_integer(self, integer_encoding) sets the colours of all points of the board according to the given integer_encoding. This does not change the size of the board! The integer encoding of a board position is based on the ternary number system. The ternary system uses the digits 0,1 , and 2 to represent numbers as follows. If d,d,,d{0,1,2} are ternary digits, then d3+d3++d3 is the integer represented hy the sequence (d d ... d ) nof digits. Fo,r-example, (201) = 23+1=7 and (210)=29+13+0= 21nn103 3 If we replace the colours of the points of the Go board by digits (empty =0, white =1, black =2 ) and concatenate all rows of the board to a single row of digits, we get a ternary number that can then be converted to an integer. The method to_integer (self) is supposed to do exactly that. For example, the 33 board used in the example for Task 3 looked like this: For example, the 33 board used in the example for Task 3 looked like this: ABC 30.0 2.@ . 1@0. Reading this off as ternary digits gives us (101020210), which equals 7473 in decimal. Hint: To conzert an integer n to ternary representation, as required by set_from_integer ( ) , note that you get the last digit by computing nmod3. You get the next digit by computing Ln/3mod3 and so on. For example, here's how to get the last two digits of the ternary representation of 7473:7473mod3=0. 7473/3=2491.2491mod3=1. Task 6 In the Board class, define a method fill_reaching(self, colour_name, reach_name, visited, r, c) that receives the following parameters: - colour_name : the name of the colour ("E", "B", or "W" ) of the chain to be marked - reach_name : the name of a colour to be tested for reachability - visited : a matrix (list of lists) of Booleans of the same size as the board - r,c : the row and column number indexed from 0, i.e. 0,0 is the top left corner The method executes the flood fill algorithm, starting from the position given by r and c, to mark all points of colour colour_name that are connected to the starting position by a path of colour colour_name moving only vertically and horizontally. The method modifies the matrix visited: marking a point is defined as setting the corresponding element in visited to True. Some elements of visited may be True to begin with the corresponding grid points are treated as if they were of a colour different from colour_name. The method must not modify the Board object. You have implemented the flood fill algorithm in W10.3 Post-Class. This is a variation of that algorithm that uses a different matrix to mark visited points and also returns whether reach_name was touched at any time during filling. In addition to marking all visited points, the method returns True if the starting point reaches the colour specified in reach_name (see rule \#3 in the background information) and False otherwise. \#- \#Task 1 b = Board(9) print(b) b = Board() print(b) print(b.get_size()) \#Task 2 b = Board(5) b.set_colour("B1", "W") b.set_colour("C1", "B") b.set_colour("D1", "B") print(b) print(b.get_colour("C1")) b.set_colour("C1", "E") print(b) b.set_colour("C1", "G") \#Task 3 b = Board(3, ["O.O", ".@..", "@0."]) print(b) print(b.to_strings()) c = Board(b.get_size(), b.to_strings()) print(str(b) == str(c)) \#task 4 b = load_board("I19.txt") print(b) save_board("I19b.txt", b) \#Task 5 b = Board(3, ["O.O", ".@..", "@0."]) print(b.to_integer()) I19 = load_board("I19.txt") print(I19.to_integer()) c = Board(3) c.set_from_integer(14676) print(c) d = Board(5) d.set_from_integer(1) print(d) \#Task 6 b = Board(3, ["@0.", "OOO", ".O."]) print(b) visited = [[False] * 3 for i in range(3)] visited = [[False] * 3 for i in range(3)] print(e) The description Task 1 In the file go.py, implement a class Board representing a square Go board. The constructor should take an optional integer parameter size with a default value of 19 to indicate the size of the board. The size must be between 2 and 26 , inclusive. If this is not the case, raise an AssertionError with the error message "Illegal board size: must be between 2 and 26.". The constructor should create a square board of the given size with all points initialised as empty. Implement the method get_size(self) that returns the size of the board. Implement the method___str__(self) to convert a Board to a string that when printed gives an "ASCII art" representation of the board with coordinates marked with letters and numbers along the columns and rows. Click on the "Expand" button below for an example. Use the following characters to represent the points on the board: empty: "." black: "@" white: "0" Task 2 Implement a method set_colour(self, coords, colour_name) that changes the colour at the coordinates given by coords. coords must be a string consisting of an upper case letter specifying the column followed by an integer specifying the row. colour_name must be one of the strings "E" (for empty), "B" (for black), "W" (for white). If coords is not a string of length 2 or 3 , raise an AssertionError with the string "invalid coordinates". If column or row are out of range, raise an AssertionError with the message "column out of range" or "row out of range", respectively. If the colour name is invalid, raise an AssertionError with the message "invalid colour name". Implement a method get_colour(self, coords) that returns the colour of the point at the given coordinates. Coordinates and colour names are as described above. Check for valid coordinates as above. che rules of the game 1. Go is played on a 1919 square grid of points, by two players called Black and White. 2. Each point on the grid may be coloured black, white or empty. 3. A point P, not coloured C, is said to reach C, if there is a path of (vertically or horizontally) adjacent points of P 's colour from P to a point of colour C. 4. Clearing a colour is the process of emptying all points of that colour that don't reach empty. 5. Starting with an empty grid, the players alternate turns, starting with Black. 6. A turn is either a pass; or a move that doesn't repeat an earlier grid colouring. 7. A move consists of colouring an empty point one's own colour; then clearing the opponent colour, and then clearing one's own colour. 8. The game ends after two consecutive passes. 9. A player's score is the number of points of their colour, plus the number of empty points that reach only their colour. 10. The player with the higher score at the end of the game is the winner. Equal scores result in a tie
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
