-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame
More file actions
538 lines (484 loc) · 20.9 KB
/
game
File metadata and controls
538 lines (484 loc) · 20.9 KB
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
import random
import re
from time import sleep
from nltk.corpus import wordnet
import nltk
values = {"A": 2, "B": 8, "C": 8, "D": 5, "E": 2, "F": 6, "G": 6, "H": 7, "I": 2, "J": 13, "K": 8, "L": 3, "M": 5,
"N": 5, "O": 2, "P": 6, "Q": 15, "R": 5, "S": 3, "T": 3, "U": 4, "V": 11, "W": 10, "X": 12, "Y": 4, "Z": 14,
"ER": 7, "CL": 10, "IN": 7, "TH": 9, "QU": 9}
frequencies = {"A": 10, "B": 2, "C": 2, "D": 4, "E": 12, "F": 2, "G": 4, "H": 2, "I": 8, "J": 2, "K": 2, "L": 4, "M": 2,
"N": 6, "O": 8, "P": 2, "Q": 2, "R": 6, "S": 4, "T": 6, "U": 6, "V": 2, "W": 2, "X": 2, "Y": 4, "Z": 2,
"ER": 2, "CL": 2, "IN": 2, "TH": 2, "QU": 2}
twoPlayerBonusOrder = ["longest word", "most words", "most words", "longest word", "most words", "most words",
"longest word", "most words"]
AInames = ["QuidTronic", "MechanicalQuid", "QuidBot3000", "TheQuidinator", "ArtificialQuintelligence"]
class Player:
def __init__(self, name):
self.name = name
self.game = "Unassigned"
self.score = 0
self.hand = []
def turn(self):
# Draw a Card, either from the deck or discard, prompted by player
print("\r")
print("It's your turn, " + self.name)
sleep(1.5)
print("Your hand contains:")
for letter in self.hand:
print(letter, end=" ")
print("\r")
sleep(2.5)
print("The top discard is: " + self.game.discard[0] + " (" + str(values[self.game.discard[0]]) + " points)")
sleep(1.5)
draw = input("Would you like to draw the top discard [D] or a mystery card from the deck [M]...\n")
while draw != "D" and draw != "M":
draw = input("Please select D or M...\n")
if draw == "D":
newCard = self.game.discard.pop(0);
elif draw == "M":
newCard = self.game.deck.pop(0);
self.hand.insert(0, newCard)
print("You have picked up a " + newCard + " (" + str(values[newCard]) + " points)")
sleep(1.5)
print("Your hand is now:\r")
for letter in self.hand:
print(letter, end=" ")
print("\r")
sleep(3)
# Discard a card, prompted by player
disc = input("Select a Card to Discard...\n")
while not self.hand.count(disc) > 0:
disc = input("Please select a card in your hand...\n")
self.game.discard.insert(0, disc)
self.hand.remove(disc)
sleep(0.75)
print("Your hand is now:\r")
for letter in self.hand:
print(letter, end=" ")
print("\r")
sleep(2.5)
# Forces player to go out if someone else already has
# Or, asks them if they want to out if they are the first
# Also manages errors in input
if self.game.goneOut:
words = input("You must go out! Seporating each letter (or double-letter)\nwith a space, and each word "
"with a comma,\ntype your words here, with unused letters as their own words...\n")
words = re.sub(r'\s*,\s*', ",", words)
handScore = self.checkWords(words)
while not isinstance(handScore, int):
if handScore == "Bad Input":
words = input("Format incorrect. Please format again L I K E,TH I S...\n")
elif handScore == "Used Letters not in Hand, or Letters in Hand unused":
words = input("You used a letter not in you hand or did not use a letter in your hand.\nTry again...\n")
else:
words = input(handScore + ".\nTry Again...\n")
words = re.sub(r'\s*,\s*', ",", words)
handScore = self.checkWords(words)
self.game.handMostWords[self.name] = self.mostWords(words)
self.game.handLongestWords[self.name] = self.longestWord(words)
self.game.handScores[self.name] = handScore
sleep(0.5)
print(self.name + " has gone out with " + re.sub(r',', ", ", words) + " for " + str(handScore) + " points")
sleep(2.5)
else:
out = input("Would you like to go out? [Y] or [N]...\n")
while out != "Y" and out != "N":
out = input("Please enter Y or N\n")
if out == "Y":
sleep(1)
words = input("Reveal your Words! Separate each letter (or double-letter)\nwith a space and each "
"word with a comma, or type C to cancel and not go out...\n")
validWords = False
words = re.sub(r'\s*,\s*', ",", words)
while not validWords:
if words == "C":
return
handScore = self.checkWords(words)
if handScore == "Bad Input":
words = input("Format incorrect. Please format again L I K E,TH I S or type C to cancel and not go out...\n")
handScore = self.checkWords(words)
elif handScore == "Used Letters not in Hand, or Letters in Hand unused":
words = input("You used a letter not in you hand or did not use a letter in your hand.\nType C to cancel and not go out or try again...\n")
handScore = self.checkWords(words)
elif handScore == "Unused Letters when first to go out":
words = input("You can't be the first to go out if you have unused letters.\nType C to cancel and not go out or try again...\n")
elif not isinstance(handScore, int):
words = input(handScore + ". \nType C to cancel and not go out or try again...\n")
else:
validWords = True
words = re.sub(r'\s*,\s*', ",", words)
self.game.handMostWords[self.name] = self.mostWords(words)
self.game.handLongestWords[self.name] = self.longestWord(words)
self.game.handScores[self.name] = handScore
self.game.goneOut = True
sleep(0.5)
print(self.name + " has gone out with " + re.sub(r',', ", ", words) + " for " + str(handScore) + " points")
sleep(2.5)
else:
sleep(2)
# return the number of words in WORDS
def mostWords(self, words):
toReturn = len([i for i in re.split(",", words.upper()) if len(i) > 1])
for d in list(values.keys())[26:31]:
for word in words:
if d == word and d in self.hand:
if not (d[0] in self.hand and d[1] in self.hand):
toReturn -= 1
return toReturn
# return the length of the longest word in WORDS
def longestWord(self, words):
wordList = re.split(",", words)
maxlen = 0
for word in wordList:
word = re.sub(r'\s', "", word)
if len(word) > maxlen:
maxlen = len(word)
return maxlen
# Takes a hand of words and returns an error or the value of that hand
# MUST IMPLEMENT DICTIONARY CHECK
def checkWords(self, words):
# parse hand
words = words.upper()
wordList = re.split(",", words)
handScore = 0
usedLetters = []
unusedLetters = []
for word in wordList:
if len(word) == 1:
unusedLetters.append(word)
else:
letters = re.split(" ", word)
for letter in letters:
if len(letter) == 2 and len(word) == 2:
unusedLetters.append(word)
else:
usedLetters.append(letter)
if not self.game.goneOut:
if len(unusedLetters) > 0:
return "Unused Letters when first to go out"
# Make sure words are in the dictionary
wordListCopy = list(wordList)
for word in wordListCopy:
word = re.sub(r'\s', "", word)
try:
syns = wordnet.synsets(word)
syns[0].definition()
except IndexError as e:
return word + " is not in the dictionary"
# Total up score and ensure only existant letters are used
for letter in unusedLetters:
try:
handScore -= values[letter]
except KeyError as e:
return "Bad Input"
for letter in usedLetters:
try:
handScore += values[letter]
except KeyError as e:
return "Bad Input"
# Check all cards from hand are used once
usage = {}
for letter in usedLetters + unusedLetters:
if letter in list(usage.keys()):
usage[letter] += 1
else:
usage[letter] = 1
try:
for letter in list(usage.keys()):
if not usage[letter] == self.hand.count(letter):
return "Used Letters not in Hand, or Letters in Hand unused"
for letter in self.hand:
if not usage[letter] == self.hand.count(letter):
return "Used Letters not in Hand, or Letters in Hand unused"
except KeyError as e:
return "Used Letters not in Hand, or Letters in Hand unused"
# return score from the hand
if (handScore > 0):
return handScore
else:
return 0
class AI(Player):
def turn(self):
print("It's " + self.name + "'s turn")
def scoreHand(words, hand):
used = []
for word in words:
for l in word:
used.append(l)
score = 0
for l in hand:
if l in used:
score += values[l]
used.remove(l)
else:
score -= values[l]
if score > 0:
return score
else:
return 0
draw = random.choice(["D", "M"])
if draw == "D":
sleep(2.5)
print(self.name + " has drawn a " + self.game.discard[0] + " from the discard")
self.hand.insert(0, self.game.discard.pop(0))
else:
sleep(2.5)
print(self.name + " has drawn from the deck")
self.hand.insert(0, self.game.deck.pop(0))
disc = random.choice(self.hand)
self.game.discard.insert(0, disc)
self.hand.remove(disc)
sleep(2.5)
print(self.name + " has discarded a " + disc)
current = self.makeWords()
currentString = str(current)[1:-1]
currentString = re.sub(r'\'', "", currentString)
if not self.game.goneOut:
if sum([len(w) for w in current]) == len(self.hand):
self.game.goneOut = True
self.game.handMostWords[self.name] = self.mostWords(currentString)
self.game.handLongestWords[self.name] = self.longestWord(currentString)
self.game.handScores[self.name] = scoreHand(current, self.hand)
sleep(2.5)
print(self.name + " has gone out with " + currentString + " for " + str(scoreHand(current, self.hand)) + " points")
sleep(1.5)
else:
self.game.handMostWords[self.name] = self.mostWords(currentString)
self.game.handLongestWords[self.name] = self.longestWord(currentString)
self.game.handScores[self.name] = scoreHand(current, self.hand)
used = []
for word in current:
for letter in word:
used.append(letter)
unused = [l for l in self.hand if l not in used]
sleep(2.5)
for letter in unused:
currentString += (", " + letter)
print(self.name + " has gone out with " + currentString + " for " + str(scoreHand(current, self.hand)) + " points")
sleep(1.5)
sleep(2)
def makeWords(self):
vocab = {}
for i in list(nltk.corpus.wordnet.words()):
vocab[i] = i
words = []
def allWords(start, inputList, outputList):
for l in inputList:
new = start + l
try:
var = vocab[new.lower()]
outputList.append(new)
except KeyError as e:
pass
if len(inputList) > 1:
copy = list(inputList)
copy.remove(l)
allWords(new, copy, outputList)
for letter in self.hand:
handcopy = list(self.hand)
allWords(letter, handcopy, words)
def allCombos(startList, remainingLetters, inputList, outputList):
for w in inputList:
temp = list(remainingLetters)
try:
for l in w:
temp.remove(l)
outputList.append(startList + [w])
allCombos(startList + [w], temp, inputList, outputList)
except ValueError as e:
pass
combos = []
allCombos([], self.hand, words, combos)
for combo in list(combos):
for word in combo:
if not ("A" in word or "E" in word or "I" in word or "O" in word or "U" in word or "Y" in word):
combos.remove(combo)
break
def scoreWordList(wordList):
used = []
for word in wordList:
for l in word:
used.append(l)
score = 0
for l in self.hand:
if l in used:
score += values[l]
used.remove(l)
else:
score -= values[l]
if score > 0:
return score
else:
return 0
points = {}
for wordList in combos:
points[tuple(wordList)] = scoreWordList(wordList)
if len(list(points.values())) > 0:
maxPoints = max(list(points.values()))
for lst in list(points.keys()):
if points[lst] == maxPoints:
return list(lst)
else:
return []
class Game:
def shuffleSeed(self):
return 0
def endRoundChecker(self):
for score in list(self.handScores.values()):
if score == -1:
return False
return True
def __init__ (self, players):
self.cards = 3
self.goneOut = False
self.discard = []
self.players = players
self.deck = []
self.handScores = {n: -1 for n in [player.name for player in players]}
self.handLongestWords = {}
self.handMostWords = {}
for player in players:
player.game = self
# Play a full 8 round game of Quiddler and determine a winner
def playgame(self):
print("Welcome to Quiddler!")
sleep(1)
print("The initial turn order will be:")
for player in self.players:
sleep(1)
print(player.name)
sleep(1)
print("\r")
while self.cards <= 10:
self.startround()
self.playround()
self.cards += 1
print("\r")
sleep(1)
print("The game is over.")
sleep(2)
print(".")
sleep(2)
print(".")
sleep(2)
print(".")
sleep(2)
finalScores = sorted([player.score for player in self.players], reverse=True)
playerOrder = []
for score in finalScores:
for player in self.players:
if player.score == score:
playerOrder.append(player)
if len(finalScores) >= 2 and finalScores[0] == finalScores[1]:
print("The game ends as a tie between", end=" ")
tied = []
for i in range(len(finalScores)):
if finalScores[0] == finalScores[i]:
tied.append(playerOrder[i].name)
for i in range(len(tied) - 1):
print(tied[i], end=", ")
print("and " + tied[len(tied) - 1])
else:
print("The winner was " + playerOrder[0].name + "! Congratulations!")
sleep(2)
print("The final scores are:")
for i in range(0, len(finalScores)):
sleep(2)
print(playerOrder[i].name + ": " + str(finalScores[i]))
sleep(2)
print("\r")
print("Thanks for playing!")
# Start a new hand with CARDNUMBER cards each
# Shuffle a clean deck and then deal
def startround(self):
self.goneOut = False
self.deck = []
self.discard = []
self.handScores = {n: -1 for n in [player.name for player in self.players]}
self.handLongestWords = {}
self.handMostWords = {}
for player in self.players:
player.hand = []
for letter in frequencies.keys():
for i in range(0, frequencies[letter] - 1):
self.deck.append(letter)
random.shuffle(self.deck)
print("Dealing the " + str(self.cards) + " card round")
sleep(1.5)
if len(self.players) == 2:
print("The bonus for this round will be " + twoPlayerBonusOrder[self.cards - 3])
sleep(1.5)
for i in range(0, self.cards):
for player in self.players:
player.hand.append(self.deck.pop(0))
self.discard.append(self.deck.pop(0))
# Play a full round and score bonuses at the end
def playround(self):
# Play round
currentPlayer = self.players[(self.cards - 3) % len(self.players)]
while not self.endRoundChecker():
currentPlayer.turn()
currentPlayer = self.players[(self.players.index(currentPlayer) + 1) % len(self.players)]
print("The round is over!")
sleep(1.5)
# count bonuses
if (not len(self.players) == 2) or twoPlayerBonusOrder[self.cards - 3] == "most words":
mostWords = 0
mostWordsName = ""
mostWordsFinal = ""
for name in list(self.handMostWords.keys()):
if self.handMostWords[name] > mostWords:
mostWords = self.handMostWords[name]
mostWordsName = name
if list(self.handMostWords.values()).count(mostWords) == 1:
print(mostWordsName + " receives the 10 point most words bonus for " + str(mostWords) + " words and a total round score of " + str(self.handScores[mostWordsName] + 10))
self.handScores[mostWordsName] += 10
mostWordsFinal = mostWordsName
else:
print("Nobody has received the most words bonus")
sleep(2)
if (not len(self.players) == 2) or twoPlayerBonusOrder[self.cards - 2] == "longest word":
longestWord = 0
longestWordName = ""
for name in list(self.handLongestWords.keys()):
if self.handLongestWords[name] > longestWord:
longestWord = self.handLongestWords[name]
longestWordName = name
if list(self.handLongestWords.values()).count(longestWord) == 1:
if longestWordName != mostWordsFinal:
print(longestWordName + " receives the 10 point longest words bonus for " + str(longestWord) + " letters and a total round score of " + str(self.handScores[longestWordName] + 10))
else:
print(longestWordName + " receives the 10 point longest words bonus for " + str(longestWord) + " letters and a total round score of " + str(self.handScores[longestWordName] + 20))
self.handScores[longestWordName] += 10
else:
print("Nobody has received the longest words bonus")
sleep(2)
# Announce scores
print("The final scores for the hand are: ")
for player in list(self.handScores.keys()):
print(player + ": " + str(self.handScores[player]))
for p in self.players:
if p.name == player:
p.score += self.handScores[player]
if self.cards == 10:
return
sleep(4)
print("At the end of the " + str(self.cards) + " card hand, the overall scores are: ")
for player in self.players:
print(player.name + ": " + str(player.score))
print("\r")
sleep(4)
# SCRIPT:
# Initialize a game of Quiddler and then play it out as all players
username = input("Enter your name...\n")
numplayers = input("Including yourself, how many players would you like in this game...\n")
while numplayers not in ["2", "3", "4", "5", "6"]:
numplayers = input("You can only play a game with 2 to 6 players. Enter a new number...\n")
numplayers = int(numplayers)
user = Player(username)
random.shuffle(AInames)
opponents = AInames[0:numplayers - 1]
allPlayers = [user] + [AI(opp) for opp in opponents]
random.shuffle(allPlayers)
myGame = Game(allPlayers)
myGame.playgame()