import math
import random
def main():
boardSize = int(input("Enter board size: "))
iterations = int(input("Enter number of iterations: "))
startPos = (0,0)
endPos = (boardSize - 1, boardSize - 1)
Test(boardSize, iterations, startPos, endPos)
# returns a new position after moving in a random direction for a random number of steps
def RandomMove(pos, boardSize):
possible_cells = [] # For 3x3 board, if at (0,0) , then it is [(0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1)]
for i in range(0, boardSize):
if (i, pos[1]) != pos:
possible_cells.append((i, pos[1]))
if (pos[0], i) != pos:
possible_cells.append((pos[0], i))
newPos = random.choice(possible_cells)
return newPos
# returns the number of steps it takes to reach the top-right cell from the bottom-left cell
def Simulate(boardSize, startPos, endPos):
pos = startPos
steps = 0
while pos != endPos:
pos = RandomMove(pos, boardSize)
steps += 1
return steps
# runs a simulation of the given number of games on a board of the given size
def Test(boardSize, iterations, startPos, endPos):
print("Simulating", iterations, "games on a", boardSize, "x", boardSize, "board...")
total_steps = 0
for i in range(iterations):
total_steps += Simulate(boardSize, startPos, endPos)
progress_bar(i + 1, iterations)
print("Average number of moves:", total_steps / iterations)
def progress_bar(current, total, bar_length=20):
fraction = current / total
arrow = int(fraction * bar_length - 1) * '-' + '>'
padding = int(bar_length - len(arrow)) * ' '
ending = '\n' if current == total else '\r'
print(f'Progress: [{arrow}{padding}] {int(fraction*100)}%', end=ending)
if __name__ == "__main__":
main()