forked from olugbengs12/Wheel-of-fortune
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wheel_of_fortune2.py
281 lines (227 loc) · 9.84 KB
/
wheel_of_fortune2.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
# PASTE YOUR WOFPlayer CLASS (from part A) HERE
class WOFPlayer:
def __init__(self,name):
self.name = name
self.prizeMoney = 0
self.prizes = []
def addMoney(self, amt):
self.prizeMoney = 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)
# PASTE YOUR WOFHumanPlayer CLASS (from part B) HERE
class WOFHumanPlayer(WOFPlayer):
def __init__(self,name):
WOFPlayer.__init__(self,name)
def getmove(self, category, obscuredPhrase, guessed):
user_inp = input("{} has ${}\nCategory: {}\nPhrase: {}\nGuessed: {}\n\n\nGuess a letter, phrase, or type 'exit' or 'pass':".format(self.name,self.prizeMoney,self.category,self.obscuredPhrase,self.guessed))
print(user_inp)
# PASTE YOUR WOFComputerPlayer CLASS (from part C) HERE
class WOFComputerPlayer(WOFPlayer):
SORTED_FREQUENCIES = 'ZQXJKVBPYGFWMUCLDRHSNIOATE'
def __init__(self, name, difficulty):
self.name = name
self.difficulty = difficulty
self.prizes = []
self.prizeMoney = 0
def smartCoinFlip(self):
rnd_num = random.randint(1, 10)
if rnd_num > self.difficulty:
return True
else:
return False
def guessedPossibleLetters(self, guessed):
possible_letters = []
for char in LETTERS:
if char in VOWELS and self.prizeMoney < VOWEL_COST:
continue
possible_letters.append(char)
return possible_letters
def getMove(self, category,obscurePhrases,guessed):
gl = self.guessedPossibleLetters
if gl ==[] or gl =='pass':
return 'pass'
scf = self.smartCoinFlip
if scf == True:
return SORTED_FREQUENCIES[-1]
elif scf ==False:
return random.choice(SORTED_FREQUENCIES)
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
# 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))