In: Computer Science
Write a python script to calculate the average length of the game, Shortest game, longest game and overall length of the game
we need a python script that calculates the average length of a snake and ladder game. ie the number of moves it takes a single player to win the game. Then you run the game several times and will compare the results to come up with the required data(length of the game and number of moves )
Please find the solution below.
Please give a thumbs up. I have taken a lot of time to solve this.
SOURCE CODE:
*Please follow the comments to better understand the code.
**Please look at the Screenshot below and use this code to copy-paste.
***The code in the below screenshot is neatly indented for better understanding.
import random
snakes_dict = {17: 7, 54: 34, 62: 19, 64: 60, 87: 36, 93: 73, 95: 75, 98: 79}
ladder_dict = {1: 38, 4: 14, 9: 31, 21: 42, 28: 84, 51: 67, 72: 91, 88: 99}
# Play the game
def play():
place = 0
count = 0
while place != 100:
dice = random.randint(1, 6)
if place + dice <= 100:
place += dice
if place in snakes_dict.keys():
place = snakes_dict.get(place)
elif place in ladder_dict.keys():
place = ladder_dict.get(place)
count += 1
# return the output of number of times it took
return count
def simulate():
"""
This will play the game for 1000 times and keep track of min and max of the counts.
:return: The values of (shortest, longest, avg)
"""
games = []
for i in range(1000):
# Play 1000 times
games.append(play())
# Get the min and max counts here
shortest = min(games)
longest = max(games)
avg = sum(games) / 1000.0
return shortest, longest, avg
def main():
"""
This will simulate the game for 10 times and prints the results.
:return: None
"""
print('Run Number\tAverage Length\tShortest Game\t Longest Game')
sum = 0
for i in range(10):
shortest, longest, avg = simulate()
sum += avg
print("{:10d}\t{:.1f}\t\t{:10d}\t\t{:10d}".format(i + 1, avg, shortest, longest))
print('Overall Average Length: {:.1f}'.format(sum / 10))
# Let's PLAY...!!!!
main()
=================
SAMPLE OUTPUTS: