MCPcopy Create free account
hub / github.com/asweigart/PythonStdioGames / runQuiz

Function runQuiz

src/gamesbyexample/countingquiz.py:39–85  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

37
38
39def runQuiz():
40 correct = 0
41 startTime = time.time()
42 while time.time() < startTime + 60:
43 print('\n' * 60) # Clear the screen by printing newlines.
44
45 # Generate the problem and the star field to display:
46 width = random.randint(1, 10)
47 height = random.randint(1, 10)
48 starField = {} # Keys are (x, y) tuples, values are '*' or ' '.
49
50 # First, populate the entire field with stars:
51 for x in range(width):
52 for y in range(height):
53 starField[(x, y)] = '*'
54
55 # Next, remove some stars from the field:
56 numMissing = random.randint(0, math.sqrt(width * height) // 2)
57 for i in range(numMissing):
58 while True:
59 x = random.randint(0, width - 1)
60 y = random.randint(0, height - 1)
61
62 # Make sure we don't remove a star that has already
63 # been removed:
64 if starField[(x, y)] == '*':
65 break
66 starField[(x, y)] = ' ' # Set this star to an empty space.
67 answer = width * height - numMissing
68
69 # Display the star field:
70 for y in range(height):
71 for x in range(width):
72 print(starField[(x, y)] + ' ', end='')
73 print() # Print a newline.
74
75 # Let the player answer and determine if they're right or wrong.
76 response = input('Enter the number of stars. > ')
77 if response.isdecimal() and int(response) == answer:
78 correct += 1
79 else:
80 print('No, answer is ', answer)
81 time.sleep(1)
82
83 print('Time\'s up!&#x27;)
84 print('You were able to count', correct, 'star fields correctly.')
85 print()
86
87
88# If the program is run (instead of imported), run the game:

Callers 1

mainFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected