Best Python code snippet using Kiwi_python
Qwixx.py
Source:Qwixx.py  
1from Die import *2from ScoreSheet import *3class Qwixx:4    """5    A class to represent a Qwixx game.6    Attributes7    ----------8    n_players : int9        the number of players in the game.10    *player_names : list11        the names of the players in the game.12    Methods13    -------14    play()15        Play the game.16    turn(player_number : int)17        Play a turn for the player with the given number.18    is_game_over()19        Check if the game is over.20    play_action(choice : int, player_number : int, white_color : str = None, white_number : str = None, colored_color : str = None, colored_number: str = None)21        Play an action for the player with the given number.22    roll_dice()23        Roll the dice of the enabled colors.24    allowed_combinations(roll : dict, player_number : int)25        Return all possible dice combinations for a roll.26    print_roll(roll : dict)27        Print the roll.28    """29    def __init__(self, n_players:int, *player_names):30        """31        Constructor for the Qwixx class.32        Parameters33        ----------34        n_players : int35            the number of players in the game.36        *player_names : list37            the names of the players in the game.38        """39        if len(player_names) > 0 and len(player_names) is not n_players:40            raise ValueError(41                "Number of players must match the number of names provided."42            )43        # Initialize the game components44        self.n_players = n_players45        # Create a new empty score sheet for each player46        self.players = (47            [ScoreSheet(name) for name in player_names]48            if player_names49            else [ScoreSheet(f"Player {i}") for i in range(1, n_players + 1)]50        )51        # Create a new empty die for each color and two white dice52        self.dice = {53            "Red": Die("Red"),54            "Yellow": Die("Yellow"),55            "Green": Die("Green"),56            "Blue": Die("Blue"),57            "White1": Die("White"),58            "White2": Die("White"),59        }60        # Keep track of which colors are enabled61        self.enabled_colors = {"Red": True, "Yellow": True, "Green": True, "Blue": True}62    def play(self):63        """64        Play the game.65        Returns66        -------67        None68        """69        # Random start player70        current_player = random.randint(0, self.n_players - 1)71        while not self.is_game_over():72            self.turn(current_player)73            current_player = (current_player + 1) % self.n_players74        print()75        print("==========================")76        print("Game over!\n")77        print("Final score sheets:")78        # Print the final score sheet79        for player in self.players:80            print(player)81            print()82        # Calculate the scores for each player and store them in a dictionary83        scores = {}84        for player in self.players:85            scores[player.name] = player.calculate_score()86        # Sort the scores in descending order87        sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)88        print()89        # Print the scores90        print(f"Scores:")91        for name, score in sorted_scores:92            print(f"{name}: {score}")93        print()94        # Print the winner95        print(f"Winner: {sorted_scores[0][0]}!")96    def turn(self, player_number: int):97        """98        Play a turn for the player with the given number.99        Parameters100        ----------101        player_number : int102            the number of the current player.103        Returns104        -------105        None106        """107        # A turn:108        # 1. Roll the dice109        # 2. Choose which dice to keep if any110        # 3. Update the score sheet111        # 4. Let the other players mark the score sheet using the white dice112        # Roll the dice113        roll = self.roll_dice()114        # Let the current player go first115        white_combos, colored_combos = self.allowed_combinations(roll, player_number)116        # Print the allowed white combinations117        print(118            f"{self.players[player_number].name} can mark the following using the white dice: "119        )120        self.print_roll(white_combos)121        # Print the allowed combinations122        print(123            f"{self.players[player_number].name} can mark the following using other combinations: "124        )125        self.print_roll(colored_combos)126        # Show the player their score sheet127        print(self.players[player_number])128        closed_rows = []129        # Ask the player to choose a combination130        while True:131            white_color = None132            white_number = None133            colored_color = None134            colored_number = None135            print(f"{self.players[player_number].name}, choose an action: ")136            try:137                action = int(138                    input(139                        "1. Mark the score sheet using the white dice\n2. Mark the score sheet using the colored dice\n3. Mark the score sheet with the white dice followed by the colored dice\n4. Add a failed attempt\n"140                    )141                )142            except ValueError:143                print("Invalid input.")144                continue145            if action not in [1, 2, 3, 4]:146                print("Invalid choice. Try again.\n")147                continue148            print()149            if action == 1 or action == 3:150                # Mark the score sheet using the white dice151                white_combo = input("Choose a combination that uses the white dice:\n")152                split_number = white_combo.split(" ")153                if (154                    split_number[0] not in white_combos.keys()155                    or int(split_number[1]) not in white_combos[split_number[0]]156                ):157                    print("Invalid choice. Try again.\n")158                    continue159                white_color = split_number[0]160                white_number = int(split_number[1])161            if action == 2 or action == 3:162                # Mark the score sheet using the colored dice163                colored_combo = input(164                    "Choose a combination that uses the colored dice:\n"165                )166                split_number = colored_combo.split(" ")167                if (168                    split_number[0] not in colored_combos.keys()169                    or int(split_number[1]) not in colored_combos[split_number[0]]170                ):171                    print("Invalid choice. Try again.\n")172                    continue173                colored_color = split_number[0]174                colored_number = int(split_number[1])175            if action == 3:176                if white_color == colored_color and ((colored_number <= white_number and (colored_color == "Red" or colored_color == "Yellow")) or (colored_number >= white_number and (colored_color == "Green" or colored_color == "Blue"))):177                    print(178                        "This is not possible since the white number goes first and the colored number comes after the white number.\n"179                    )180                    continue181            closed_rows = self.play_action(182                int(action),183                player_number,184                white_color,185                white_number,186                colored_color,187                colored_number,188            )189            break190        print()191        if self.is_game_over():192            return193        # Ask the other players to mark the score sheet using the white dice194        for i in range(self.n_players):195            print("------------------------------------------------------")196            if i is not player_number:197                # List the possible white combinations198                white_combos, _ = self.allowed_combinations(roll, i)199                if len(white_combos) == 0:200                    print(201                        f"{self.players[i].name} cannot mark the score sheet using the white dice."202                    )203                    continue204                print(205                    f"{self.players[i].name}, you can mark the score sheet using the white dice\n"206                )207                print(self.players[i])208                print()209                print(f"Your possible choices: ")210                self.print_roll(white_combos)211                # Ask the player to choose a combination212                while True:213                    want_to = input(214                        f"Would you like to mark the score sheet using the white dice? (y/n)\n"215                    )216                    if want_to.lower() == "y":217                        white_combo = input(218                            "Choose a combination that uses the white dice:\n"219                        )220                        split_number = white_combo.split(" ")221                        if (222                            split_number[0] not in white_combos.keys()223                            or int(split_number[1]) not in white_combos[split_number[0]]224                        ):225                            print("Invalid choice. Try again.\n")226                            continue227                        self.play_action(228                            1, i, split_number[0], int(split_number[1]), None, None229                        )230                        break231                    elif want_to.lower() == "n":232                        break233                    else:234                        print("Invalid choice. Try again.\n")235                        continue236                # If the first player "closed" a row, close it for the other players237                if closed_rows:238                    for row in closed_rows:239                        self.players[i].rows[row].closed = True240    def is_game_over(self):241        """242        Check if the game is over.243        Returns244        -------245        bool246            True if the game is over, False otherwise.247        """248        # Check if the game is over249        # Game is over if one player has 4 failed attempts or if two colors are disabled250        for player in self.players:251            if player.failed_attempts >= 4:252                return True253        # Count the number of enabled colors254        enabled_colors = 0255        for color in self.enabled_colors:256            if self.enabled_colors[color]:257                enabled_colors += 1258        if enabled_colors <= 2:259            return True260        return False261    def play_action(262        self,263        choice: int,264        player_number: int,265        white_color: str=None,266        white_number: int=None,267        colored_color: str=None,268        colored_number: int=None,269    ):270        """271        Play an action.272        Parameters273        ----------274        choice : int275            The action to be played.276        player_number : int277            The player number.278        white_color : str279            The chosen color for the white dice.280        white_number : int281            The number of the white dice.282        colored_color : str283            The chosen color for the colored dice.284        colored_number : int285            The number of the colored dice.286        Returns287        -------288        list289            The list of closed rows (if there are any).290        """291        # Option 1: Mark the score sheet using the white dice292        if choice == 1:293            if white_number is None or white_color is None:294                raise ValueError("No white dice combination was provided.")295            self.players[player_number].mark_row(white_color, white_number)296            print(297                f"{self.players[player_number].name} marked the score sheet using the white dice {white_color} {white_number}."298            )299            # Print if the row is closed300            if self.players[player_number].rows[white_color].closed:301                print(f"The {white_color.lower()} row is now closed!")302                return [white_color]303        # Option 2: Mark the score sheet using the colored dice304        elif choice == 2:305            if colored_color is None or colored_number is None:306                raise ValueError("Color and number must be provided.")307            self.players[player_number].mark_row(colored_color, colored_number)308            print(309                f"{self.players[player_number].name} marked the score sheet using the colored dice {colored_color} {colored_number}."310            )311            # Print if the row is closed312            if self.players[player_number].rows[colored_color].closed:313                print(f"The {colored_color.lower()} row is now closed!")314                return [colored_color]315        # Option 3: Mark the score sheet with the white dice followed by the colored dice316        elif choice == 3:317            if colored_color is None or colored_number is None:318                raise ValueError("Color and number must be provided.")319            if white_number is None or white_color is None:320                raise ValueError("No white dice combination was provided.")321            self.players[player_number].mark_row(white_color, white_number)322            self.players[player_number].mark_row(colored_color, colored_number)323            print(324                f"{self.players[player_number].name} marked the score sheet using the white dice {white_color} {white_number} and the colored dice {colored_color} {colored_number}."325            )326            closed_colors = []327            # Print if the row is closed328            if self.players[player_number].rows[white_color].closed:329                print(f"The {white_color.lower()} row is now closed!")330                closed_colors.append(white_color)331            if self.players[player_number].rows[colored_color].closed:332                print(f"The {colored_color.lower()} row is now closed!")333                closed_colors.append(colored_color)334            return closed_colors335        # Option 4: Adding a failed attempt336        elif choice == 4:337            self.players[player_number].add_failed_attempt()338            print(f"{self.players[player_number].name} added a failed attempt.")339    def roll_dice(self):340        """341        Roll the dice.342        Returns343        -------344        list345            The list of the rolled dice.346        """347        # Roll the dice of the enabled colors348        roll = {349            color: self.dice[color].roll_die()350            for color in self.enabled_colors351            if self.enabled_colors[color]352        }353        # Roll the white dice354        white1 = self.dice["White1"].roll_die()355        white2 = self.dice["White2"].roll_die()356        # Save all possible dice combinations357        combinations = {"White": [white1 + white2]}358        for color in roll:359            combinations[f"{color}"] = sorted(360                (roll[color] + white1, roll[color] + white2)361            )362        return combinations363    def allowed_combinations(self, roll: dict, player_number: int):364        """365        Filter the possible combinations of the dice to only the ones that are allowed.366        Parameters367        ----------368        roll : dict369            The dictionary of the rolled dice.370        player_number : int371            The player number.372        Returns373        -------374        list, list375            The list of the allowed combinations for the white dice and the list of the allowed combinations for the colored dice.376        """377        # Filter out the combinations that are not allowed for player_number378        allowed_colored_combinations = {}379        allowed_white_combinations = {}380        for key, value in roll.items():381            if key == "White":382                for row in self.players[player_number].rows.values():383                    if row.is_allowed(value[0]):384                        allowed_white_combinations[row.color] = [value[0]]385            else:386                for i in range(len(value)):387                    if self.players[player_number].rows[key].is_allowed(value[i]):388                        allowed_colored_combinations[key] = (389                            [value[i]]390                            if not key in allowed_colored_combinations391                            else (392                                allowed_colored_combinations[key] + [value[i]]393                                if not value[i] in allowed_colored_combinations[key]394                                else allowed_colored_combinations[key]395                            )396                        )397        return allowed_white_combinations, allowed_colored_combinations398    def print_roll(self, roll: dict):399        """400        Print the roll in a nice way.401        Parameters402        ----------403        roll : dict404            The dictionary of the rolled dice.405        406        Returns407        -------408        None409        """410        print(f"Color     | Roll(s)")411        print(f"----------+----------")412        for key, value in roll.items():413            r = key414            r += " " * (10 - len(key)) + "| "415            for v in value:416                r += str(v) + " "417            print(r)...admin.py
Source:admin.py  
...31        <a href="https://kiwitcms.readthedocs.io/en/latest/admin.html#test-execution-statuses">32        the documentation</a>!"""),33        }),34    ]35    def colored_color(self, test_execution):36        return format_html(37            '''38            <span style="background-color: {}; height: 20px; display: block;39                         color: black; font-weight: bold">40                {}41            </span>42            ''',43            test_execution.color, test_execution.color)44    colored_color.short_description = 'color'45    def visual_icon(self, test_execution):46        return format_html(47            '''48            <span class="{}" style="font-size: 18px; color: {};"></span>49            ''',...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
