6
\$\begingroup\$

My code is for a 10-faced dice-rolling game. There are 2 players who start off with 50 points, then they both roll a dice and get a random score between 1-10. The player with the highest roll gets the difference between the rolls deducted from their score (50 points), but the loser gets the difference between the rolls added to their score. To win the game you must reach the score 0, or below.

#Imported to help flow, and random to simulate dice rolls

print("Welcome to the dice rolling game.")
#Printed to make it more friendly to the user :)
time.sleep(1)

playernames=[]
#Add player's names to a list
playernames.append(input("\nWhat is player 1's name?"))#.append is used to add multiple names to list
playernames.append(input("\nWhat is player 2's name?"))
time.sleep(1)
#Prints players names from the list

print("\nPlayer 1:",playernames[0])
print("Player 2:",playernames[1])
input("\nPress enter to begin: ")


dicelist=[0,0]

dicelist[0]=random.randint(1,10)
dicelist[1]=random.randint(1,10)


for i in range(0,2):
    print(playernames[i],"rolls a",dicelist[i])
diceDifference=abs(dicelist[0]-dicelist[1])


score0=20
score1=20
while True:
    if dicelist[0]>dicelist[1]:
            print("\nPlayer 1 wins")
            time.sleep(1)
            print("\nPlayer 2 loses",diceDifference,"points")
            print("Player 2 gains",diceDifference,"points")

            print("player 1:",score0-diceDifference)
            print("player 2:",score1+diceDifference)
score0==0
exit

elif dicelist[1]>dicelist[2]:
print("\nPlayer 2 wins")
time.sleep(1)
print("\nPlayer 2 loses",diceDifference,"points")
print("\nPlayer 1 gains",diceDifference,"points")
print("player 1:",score0+diceDifference)
print("player 2:",score1-diceDifference)
score1==0
exit

else:
print("It's a draw")
time.sleep(1)
print("No change in score")

print("The score is: ","\nPlayer 1:",score0,"\nPlayer 2:",score1)
time.sleep(1)
\$\endgroup\$
10
\$\begingroup\$

You have quite a lot of duplication in your code - everything is written out twice, once for each player. This means that you have to change everything in two places if you want to alter the logic, and that adding more players is a huge pain.

Instead, I would suggest the use of lists to hold multiple items, allowing you to have an arbitrary number of players (you start this with the playernames and dicelist, then seem to give up!)

You should also factor out the "magic numbers" like the number of players, number of faces on the die and the starting score. For example:

import random

# Configuration
PLAYERS = 2  # could be another input at the start
FACES = 10
START_SCORE = 20  # or 50?

# Initialisation
names = [input("\nWhat is player {}'s name?".format(x+1)) 
         for x in range(PLAYERS)]
scores = [START_SCORE for _ in range(PLAYERS)]

# Main game loop
while all(score > 0 for score in scores):
    print()

    # Calculate rolls 
    rolls = [random.randint(1, FACES) for _ in range(PLAYERS)]
    for name, roll in zip(names, rolls):
        print("{} rolled {}".format(name, roll))

    # Determine winning roll
    winning_roll = max(rolls)
    diffs = [winning_roll - roll for roll in rolls]

    # Update scores
    for index, name in enumerate(names):
        scores[index] += diffs[index]
        if diffs[index] == 0:
            print("{} won!".format(name))
            scores[index] -= sum(diffs)

    # Report progress
    for name, score in zip(names, scores):
        print("{} now has {} points".format(name, score))

# Who won?
print()
winning_score = min(scores)
for name, score in zip(names, scores):
    if score == winning_score:
        print("{} is the winner!".format(name))

Note the use of zip, enumerate and list comprehensions to deal effectively with the various lists.

The rules have been adapted slightly to accommodate multiple players - those with the highest score get the sum of all differences subtracted from their score, whereas the others get only their difference added. This is the same for two players, but you could tweak this logic according to how the game should work.

One significant improvement over the current structure would be to implement as a set of short, self-contained functions rather than one long script.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.