import math
import random
def main():
board_size = 8
iterations = 10000
Test(board_size, iterations)
# returns a new position after moving in the given direction for the given number of steps
def Move(pos, direction, steps):
if direction == "U":
return (pos[0], pos[1] + steps)
elif direction == "D":
return (pos[0], pos[1] - steps)
elif direction == "L":
return (pos[0] - steps, pos[1])
elif direction == "R":
return (pos[0] + steps, pos[1])
# returns a new position after moving in a random direction for a random number of steps
def RandomMove(pos, board_size):
direction = random.choice(GetPossibleDirections(pos, board_size))
steps = GetSteps(direction, pos, board_size)
return Move(pos, direction, steps)
# returns a list of possible directions to move in
def GetPossibleDirections(pos, board_size):
result = ["U", "D", "L", "R"]
if pos[0] == 0:
result.remove("L")
elif pos[0] == board_size - 1:
result.remove("R")
if pos[1] == 0:
result.remove("D")
elif pos[1] == board_size - 1:
result.remove("U")
return result
# returns the number of steps to move in the given direction
def GetSteps(direction, pos, board_size):
if direction == "U":
return math.floor(random.random() * (board_size - pos[1] - 1) + 1)
elif direction == "D":
return math.floor(random.random() * (pos[1]) + 1)
elif direction == "L":
return math.floor(random.random() * (pos[0]) + 1)
elif direction == "R":
return math.floor(random.random() * (board_size - pos[0] - 1) + 1)
# returns the number of steps it takes to reach the top-right cell from the bottom-left cell
def Simulate(pos, board_size):
steps = 0
while pos != (board_size - 1, board_size - 1):
pos = RandomMove(pos, board_size)
steps += 1
return steps
# runs a simulation of the given number of games on a board of the given size
def Test(board_size, iterations):
print("Simulating", iterations, "games on a", board_size, "x", board_size, "board...")
total_steps = 0
for i in range(iterations):
total_steps += Simulate((0, 0), board_size)
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()