Feb-11-2021, 05:15 AM
(This post was last modified: Feb-11-2021, 05:15 AM by deanhystad.)
You should not have a variable named player_1 or Player2Points. If you have a game with 2 players you should have a variable named players, and it should be a list of length 2. You will realize significant reduction in code if you stop thinking of the game as having 2 players and instead think of it as a single player game with two players taking turns.
Players have 2 attributes, a name and a score. There are multiple things in Python that can store more than one value; lists, dictionaries, classes. In the example below a dictionary is used to store the player's name and score.
A list holds the two player dictionaries.
Players have 2 attributes, a name and a score. There are multiple things in Python that can store more than one value; lists, dictionaries, classes. In the example below a dictionary is used to store the player's name and score.
A list holds the two player dictionaries.
"""Plays a dice game""" import random from time import sleep def get_players(): """Get players names and initialize scores""" players = [] for i in range(2): players.append({'name':input('Enter Player {i+1} Name: '), 'score':0}) return players def roll_dice(players): """Give each player a turn. Players roll two dice. Players are awarded the total of the two dice. If the total is even, the player is awarded a 10 point bonus. If the total is odd, the player is penalized 5 points. If the player rolls doubles they roll an additional die and are awarded a bonus equal to the value of the die. """ def play_game(players): """Play the dice game. Players get 4 rolls and the player with the highest score wins. If players are tied after 4 rolls they continue to roll until the tie is broken. """ for _ in range(4): roll_dice(players) while players[0]['score'] == players[1]['score']: print('The score is tied! Tiebreaker roll!') roll_dice(players) if players[0]['score'] > players[1]['score']: winner, loser = players else: loser, winner = players print(f'\n{winner["name"]} wins with {winner["score"]} points!') print(f'{loser["name"]} finishes with {loser["score"]} points\n\n') players = get_players() play_game(players)Notice how little code is devoted to there being two players. Instead of doing something for player 1 and hen doing almost exactly the same thing for player 2, I use a for loop and iterate through he players. It would be simple to change this game to allow 3, 4, 500 players.