Mar-09-2020, 12:29 AM
(This post was last modified: Mar-09-2020, 12:29 AM by deanhystad.)
There's a few problems here. Let's start with Dice(). What do you think this is doing? What is it's purpose?
I think you mean for Dice to be a structure that holds information for your dice game. Look what happens when I run this program:
For a simple program like this I would forget about any kind of data structure until I got all the parts working. Something like this
I think you mean for Dice to be a structure that holds information for your dice game. Look what happens when I run this program:
def Dice(): player_1=0 Points1=0 player_2=0 Points2=0 player_12=0 player_22=0 Points12=0 Points22=0 totalpoints1=Points1 + Points12 totalpoints2=Points2 + Points22 print('Dice is a', type(Dice)) print('Dice knows about', Dice.__dict__) print(totalpoints1)
Output:Dice is a <class 'function'>
Dice knows about {}
Traceback (most recent call last):
File "C:/Users/djhys/Documents/Python/schema/dsp/regex.py", line 17, in <module>
print(totalpoints1)
NameError: name 'totalpoints1' is not defined
Surprise! Dice is a function. The code above creates a function that assigns a bunch of local variables and returns None. And those local variables are only visible from inside the function while it is running. When I tried to print "totalpoints1" I got an error because there is no such thing outside the Dice function.For a simple program like this I would forget about any kind of data structure until I got all the parts working. Something like this
import random def dice_roll(): return random.randint(1,6) player1_points = 0 player2_points = 0 for rnd in range(1, 5): player1_roll = dice_roll() + dice_roll() player2_roll = dice_roll() + dice_roll() print('Round', rnd) if player1_roll == player2_roll: print("It's a tie!") elif player1_roll > player2_roll: print("Player 1 wins the roll!") player1_points += 1 else: print("Player 2 wins the roll!") player2_points += 1 print('Game over') if player1_points == player2_points: print("It's a tie!") elif player1_points > player2_points: print("player 1 wins the game!") else: print("Player 2 Wins the game!")
Output:Round 1
Player 1 wins the roll!
Round 2
Player 1 wins the roll!
Round 3
Player 1 wins the roll!
Round 4
It's a tie!
Game over
player 1 wins the game!
I think the game is a little sterile. To give it some flash I change the dice rolling to report which die were cast. To do this I modified the dice_roll function.def dice_roll(player_name): die1 = random.randint(1,6) die2 = random.randint(1,6) print(player_name, 'rolls', die1, 'and', die2) return die1 + die2See how this adds drama.
Output:Round 1
Player 1 rolls 2 and 4
Player 2 rolls 6 and 6
Player 2 wins!
Round 2
Player 1 rolls 4 and 6
Player 2 rolls 6 and 3
Player 1 wins!
Round 3
Player 1 rolls 6 and 5
Player 2 rolls 5 and 3
Player 1 wins!
Round 4
Player 1 rolls 4 and 6
Player 2 rolls 4 and 6
It's a tie!
Game over
player 1 wins the game, 2 to 1