-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathWheel_of_Fortune.py
295 lines (238 loc) · 10.2 KB
/
Wheel_of_Fortune.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import sys
sys.setExecutionLimit(600000) # let this take up to 10 minutes
import json
import random
import time
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
VOWELS = 'AEIOU'
VOWEL_COST = 250
class WOFPlayer:
def __init__(self , name):
self.name = name
self.prizeMoney = 0
self.prizes = []
def addMoney( self, amt):
self.prizeMoney += amt
def goBankrupt(self):
self.prizeMoney = 0
def addPrize(self,prize):
self.prizes.append(prize)
def __str__(self):
return "{} (${})".format(self.name,self.prizeMoney)
class WOFHumanPlayer(WOFPlayer):
def __init(self,name):
WOFPlayer.__ini__(self,name)
def getMove(self,category, obscuredPhrase, guessed):
print("{} has (${})".format(self.name,self.prizeMoney))
print("Category:",category)
print("Phrase:",obscuredPhrase)
print("Guessed:",guessed)
theChoose = str(input("Guess a letter, phrase, or type 'exit' or 'pass': "))
return theChoose
class WOFComputerPlayer(WOFPlayer):
SORTED_FREQUENCIES = 'ZQXJKVBPYGFWMUCLDRHSNIOATE'
def __init__(self, name, difficulty):
WOFPlayer.__init__(self,name)
self.difficulty = difficulty
self.prizes = []
self.prizeMoney = 0
def smartCoinFlip(self):
rand_number = random.randint(1, 10)
if rand_number > self.difficulty:
return True
else:
return False
def getPossibleLetters(self,guessed):
CanBeGuessed = []
for letter in LETTERS:
if letter not in guessed and letter not in VOWELS :
CanBeGuessed.append(letter)
elif letter not in guessed and letter in VOWELS:
if self.prizeMoney > VOWEL_COST:
CanBeGuessed.append(letter)
return CanBeGuessed
def getMove(self, category, obscuredPhrase, guessed):
CanBeGuessed = self.getPossibleLetters(guessed)
if CanBeGuessed == []:
return 'pass'
else:
the_value = self.smartCoinFlip()
if the_value == True:
i = len(self.SORTED_FREQUENCIES)-1
while(0 <= i <= len(self.SORTED_FREQUENCIES)-1):
if self.SORTED_FREQUENCIES[i] in CanBeGuessed:
return self.SORTED_FREQUENCIES[i]
else:
i-=1
continue
else:
rand_letter = random.choice(CanBeGuessed)
return rand_letter
# Repeatedly asks the user for a number between min & max (inclusive)
def getNumberBetween(prompt, min, max):
userinp = input(prompt) # ask the first time
while True:
try:
n = int(userinp) # try casting to an integer
if n < min:
errmessage = 'Must be at least {}'.format(min)
elif n > max:
errmessage = 'Must be at most {}'.format(max)
else:
return n
except ValueError: # The user didn't enter a number
errmessage = '{} is not a number.'.format(userinp)
# If we haven't gotten a number yet, add the error message
# and ask again
userinp = input('{}\n{}'.format(errmessage, prompt))
# Spins the wheel of fortune wheel to give a random prize
# Examples:
# { "type": "cash", "text": "$950", "value": 950, "prize": "A trip to Ann Arbor!" },
# { "type": "bankrupt", "text": "Bankrupt", "prize": false },
# { "type": "loseturn", "text": "Lose a turn", "prize": false }
def spinWheel():
with open("wheel.json", 'r') as f:
wheel = json.loads(f.read())
return random.choice(wheel)
# Returns a category & phrase (as a tuple) to guess
# Example:
# ("Artist & Song", "Whitney Houston's I Will Always Love You")
def getRandomCategoryAndPhrase():
with open("phrases.json", 'r') as f:
phrases = json.loads(f.read())
category = random.choice(list(phrases.keys()))
phrase = random.choice(phrases[category])
return (category, phrase.upper())
# Given a phrase and a list of guessed letters, returns an obscured version
# Example:
# guessed: ['L', 'B', 'E', 'R', 'N', 'P', 'K', 'X', 'Z']
# phrase: "GLACIER NATIONAL PARK"
# returns> "_L___ER N____N_L P_RK"
def obscurePhrase(phrase, guessed):
rv = ''
for s in phrase:
if (s in LETTERS) and (s not in guessed):
rv = rv+'_'
else:
rv = rv+s
return rv
# Returns a string representing the current state of the game
def showBoard(category, obscuredPhrase, guessed):
return """
Category: {}
Phrase: {}
Guessed: {}""".format(category, obscuredPhrase, ', '.join(sorted(guessed)))
# GAME LOGIC CODE
print('='*15)
print('WHEEL OF PYTHON')
print('='*15)
print('')
num_human = getNumberBetween('How many human players?', 0, 10)
# Create the human player instances
human_players = [WOFHumanPlayer(input('Enter the name for human player #{}'.format(i+1))) for i in range(num_human)]
num_computer = getNumberBetween('How many computer players?', 0, 10)
# If there are computer players, ask how difficult they should be
if num_computer >= 1:
difficulty = getNumberBetween('What difficulty for the computers? (1-10)', 1, 10)
# Create the computer player instances
computer_players = [WOFComputerPlayer('Computer {}'.format(i+1), difficulty) for i in range(num_computer)]
players = human_players + computer_players
# No players, no game :(
if len(players) == 0:
print('We need players to play!')
raise Exception('Not enough players')
# category and phrase are strings.
category, phrase = getRandomCategoryAndPhrase()
# guessed is a list of the letters that have been guessed
guessed = []
# playerIndex keeps track of the index (0 to len(players)-1) of the player whose turn it is
playerIndex = 0
# will be set to the player instance when/if someone wins
winner = False
def requestPlayerMove(player, category, guessed):
while True: # we're going to keep asking the player for a move until they give a valid one
time.sleep(0.1) # added so that any feedback is printed out before the next prompt
move = player.getMove(category, obscurePhrase(phrase, guessed), guessed)
move = move.upper() # convert whatever the player entered to UPPERCASE
if move == 'EXIT' or move == 'PASS':
return move
elif len(move) == 1: # they guessed a character
if move not in LETTERS: # the user entered an invalid letter (such as @, #, or $)
print('Guesses should be letters. Try again.')
continue
elif move in guessed: # this letter has already been guessed
print('{} has already been guessed. Try again.'.format(move))
continue
elif move in VOWELS and player.prizeMoney < VOWEL_COST: # if it's a vowel, we need to be sure the player has enough
print('Need ${} to guess a vowel. Try again.'.format(VOWEL_COST))
continue
else:
return move
else: # they guessed the phrase
return move
while True:
player = players[playerIndex]
wheelPrize = spinWheel()
print('')
print('-'*15)
print(showBoard(category, obscurePhrase(phrase, guessed), guessed))
print('')
print('{} spins...'.format(player.name))
time.sleep(2) # pause for dramatic effect!
print('{}!'.format(wheelPrize['text']))
time.sleep(1) # pause again for more dramatic effect!
if wheelPrize['type'] == 'bankrupt':
player.goBankrupt()
elif wheelPrize['type'] == 'loseturn':
pass # do nothing; just move on to the next player
elif wheelPrize['type'] == 'cash':
move = requestPlayerMove(player, category, guessed)
if move == 'EXIT': # leave the game
print('Until next time!')
break
elif move == 'PASS': # will just move on to next player
print('{} passes'.format(player.name))
elif len(move) == 1: # they guessed a letter
guessed.append(move)
print('{} guesses "{}"'.format(player.name, move))
if move in VOWELS:
player.prizeMoney -= VOWEL_COST
count = phrase.count(move) # returns an integer with how many times this letter appears
if count > 0:
if count == 1:
print("There is one {}".format(move))
else:
print("There are {} {}'s".format(count, move))
# Give them the money and the prizes
player.addMoney(count * wheelPrize['value'])
if wheelPrize['prize']:
player.addPrize(wheelPrize['prize'])
# all of the letters have been guessed
if obscurePhrase(phrase, guessed) == phrase:
winner = player
break
continue # this player gets to go again
elif count == 0:
print("There is no {}".format(move))
else: # they guessed the whole phrase
if move == phrase: # they guessed the full phrase correctly
winner = player
# Give them the money and the prizes
player.addMoney(wheelPrize['value'])
if wheelPrize['prize']:
player.addPrize(wheelPrize['prize'])
break
else:
print('{} was not the phrase'.format(move))
# Move on to the next player (or go back to player[0] if we reached the end)
playerIndex = (playerIndex + 1) % len(players)
if winner:
# In your head, you should hear this as being announced by a game show host
print('{} wins! The phrase was {}'.format(winner.name, phrase))
print('{} won ${}'.format(winner.name, winner.prizeMoney))
if len(winner.prizes) > 0:
print('{} also won:'.format(winner.name))
for prize in winner.prizes:
print(' - {}'.format(prize))
else:
print('Nobody won. The phrase was {}'.format(phrase))