Skip to content

Commit 4adc695

Browse files
committed
Update scrabble.py as per guidelines
1 parent 6c36b21 commit 4adc695

File tree

1 file changed

+85
-36
lines changed

1 file changed

+85
-36
lines changed

Scrabble/scrabble.py

Lines changed: 85 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,77 +1,126 @@
11
from PyDictionary import PyDictionary
22

3+
34
def main():
4-
print("\n" + '*'*10 + "Welcome to the Scrabble game" + '*'*10 + "\n" + "Let's start playing!!\n")
5+
"""
6+
Main entry point of the Scrabble game.
7+
"""
8+
print('*' * 10 + "Welcome to the Scrabble game" + '*' * 10)
9+
print("Let's start playing!!\n")
510
score_board = {}
611
for i in range(player_count()):
712
player = input(f"Player {i+1}: ")
813
score_board[player] = 0
9-
print('*'*40 + "\n")
10-
print(winner(get_input(score_board)).center(40, " ") +"\n")
11-
print('*'*40 + "\n"+"Thank you for your time. Have a Nice day!")
14+
print('*' * 40)
15+
print(winner(get_input(score_board)).center(40, " "))
16+
print('*' * 40)
17+
print("Thank you for your time. Have a Nice day!")
1218

19+
1320
def valid(word):
14-
if PyDictionary().meaning(word, True) == None :
15-
return False
16-
else:
17-
return True
21+
"""
22+
Checks if a word is valid by checking its meaning using PyDictionary.
23+
Args:
24+
word (str): The word to be validated.
25+
Returns:
26+
bool: True if the word is valid, False otherwise.
27+
"""
28+
dictionary = PyDictionary()
29+
return dictionary.meaning(word) is not None
1830

31+
1932
def compute_score(word):
20-
score_list = {'a':1, 'b':3, 'c':3, 'd':2, 'e':1, 'f':4, 'g':2, 'h':4, 'i':1, 'j':8, 'k':5, 'l':1, 'm':3,
21-
'n':1, 'o':1, 'p':3, 'q':10, 'r':1, 's':1, 't':1, 'u':1, 'v':4, 'w':4, 'x':8, 'y':4, 'z':10}
33+
"""
34+
Computes the score for a given word based on a score list.
35+
Args:
36+
word (str): The word for which the score needs to be computed.
37+
Returns:
38+
int: The computed score for the word.
39+
Raises:
40+
ValueError: If the word is invalid or contains non-alphabetic characters.
41+
"""
42+
score_list = {
43+
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2,
44+
'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1,
45+
'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1,
46+
'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10}
2247
score = 0
2348
if word.isalpha():
2449
if valid(word):
25-
for i in word:
26-
score += score_list[i.lower()]
50+
for char in word:
51+
score += score_list[char.lower()]
2752
return score
2853
else:
29-
raise NameError
54+
raise ValueError("Invalid word")
3055
else:
31-
raise ValueError
56+
raise ValueError("Word should only contain alphabetic characters")
3257

58+
3359
def player_count():
60+
"""
61+
Prompts the user to input the number of players for the game.
62+
Returns:
63+
int: The number of players.
64+
Raises:
65+
ValueError: If the user inputs a non-positive number.
66+
"""
3467
while True:
3568
try:
3669
count = int(input("How many players? "))
37-
except ValueError:
38-
print("Please type a number in integer format.")
39-
continue
40-
else:
70+
if count < 1:
71+
raise ValueError("Please enter a positive number")
4172
return count
42-
break
73+
except ValueError as e:
74+
print(str(e))
4375

76+
4477
def get_input(score_board):
78+
"""
79+
Retrieves the word input from each player and updates their scores.
80+
Args:
81+
score_board (dict): The dictionary storing the scores of each player.
82+
Returns:
83+
dict: The updated score board.
84+
"""
4585
while True:
4686
for player in score_board:
4787
while True:
4888
try:
4989
word = input(f"{player} | Type a word: ")
5090
score_board[player] += compute_score(word)
51-
except BaseException:
52-
print("Please type a valid word.")
53-
continue
91+
except ValueError as e:
92+
print(str(e))
5493
else:
5594
break
5695

57-
if input("If exit, type Y: ") == "Y":
58-
print('*'*40 + "\n")
96+
if input("If exit, type Y: ").lower() == "y":
97+
print('*' * 40)
5998
break
60-
else:
61-
continue
99+
continue
62100
return score_board
63101

102+
64103
def winner(score_board):
65-
sorted_scores = sorted(score_board.items(), key=lambda x: x[1], reverse= True)
66-
max = sorted_scores[0][1]
67-
winners = [sorted_scores[0][0]]
68-
for i in sorted_scores[1:]:
69-
if i[1] == max:
70-
winners.append(i[0])
71-
if len(winners) > 1:
72-
return f"It's a tie. The winners are {', '.join(winners)}!!"
73-
else:
104+
"""
105+
Determines the winner(s) based on the highest scores.
106+
Args:
107+
score_board (dict): The dictionary storing the scores of each player.
108+
Returns:
109+
str: The winner(s) message.
110+
Raises:
111+
IndexError: If there are no players in the score board.
112+
"""
113+
sorted_scores = sorted(score_board.items(), key=lambda x: x[1], reverse=True)
114+
if len(sorted_scores) > 0:
115+
max_score = sorted_scores[0][1]
116+
winners = [player for player, score in sorted_scores if score == max_score]
117+
if len(winners) > 1:
118+
return f"It's a tie. The winners are {', '.join(winners)}!!"
74119
return f"The winner is {winners[0]}!"
120+
else:
121+
return "No players found. Game over!"
122+
75123

76124
if __name__ == "__main__":
77-
main()
125+
main()
126+

0 commit comments

Comments
 (0)