Amazing-Python-Scripts

Форк
0
121 строка · 3.6 Кб
1
from PyDictionary import PyDictionary
2

3

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

17

18
def valid(word):
19
    """
20
    Checks if a word is valid by checking its meaning using PyDictionary.
21
    Args:
22
        word (str): The word to be validated.
23
    Returns:
24
        bool: True if the word is valid, False otherwise.
25
    """
26
    dictionary = PyDictionary()
27
    return bool(dictionary.meaning(word))
28

29

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

54

55
def player_count():
56
    """
57
    Prompts the user to input the number of players for the game.
58
    Returns:
59
        int: The number of players.
60
    Raises:
61
        ValueError: If the user inputs a non-positive number.
62
    """
63
    while True:
64
        try:
65
            count = int(input("How many players? "))
66
            if count < 1:
67
                raise ValueError("Please enter a positive number")
68
            return count
69
        except ValueError as e:
70
            print(str(e))
71

72

73
def get_input(score_board):
74
    """
75
    Retrieves the word input from each player and updates their scores.
76
    Args:
77
        score_board (dict): The dictionary storing the scores of each player.
78
    Returns:
79
        dict: The updated score board.
80
    """
81
    while True:
82
        for player in score_board:
83
            while True:
84
                try:
85
                    word = input(f"{player} | Type a word: ")
86
                    score_board[player] += compute_score(word)
87
                except ValueError as e:
88
                    print(str(e))
89
                else:
90
                    break
91

92
        if input("If exit, type Y: ").lower() == "y":
93
            print('*' * 40)
94
            break
95
        continue
96
    return score_board
97

98

99
def winner(score_board):
100
    """
101
    Args:
102
        score_board (dict): The dictionary storing the scores of each player.
103
    Returns:
104
        str: The winner(s) message.
105
    Raises:
106
        IndexError: If there are no players in the score board.
107
    """
108
    sorted_scores = sorted(score_board.items(),
109
                           key=lambda x: x[1], reverse=True)
110
    if len(sorted_scores) > 0:
111
        max_score = sorted_scores[0][1]
112
        winners = [player for player,
113
                   score in sorted_scores if score == max_score]
114
        if len(winners) > 1:
115
            return f"It's a tie. The winners are {', '.join(winners)}!!"
116
        return f"The winner is {winners[0]}!"
117
    return "No players found. Game over!"
118

119

120
if __name__ == "__main__":
121
    main()
122

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.