Reputation: 19
I'm trying to do a practice assignment to help learn python yet am stuck on this. It says to create a simple Die game which asks for user input to keep playing, along with displaying results. I also need to use classes. I have been able to create it without the classes yet become stuck when transferring it to classes.
import random
def RollDice():
die = random.randint(1,6)
die2 = random.randint(1,6)
faceValue = die + die2
if die == 1:
RollOne()
elif die == 2:
RollTwo()
elif die == 3:
RollThree()
elif die == 4:
RollFour()
elif die == 5:
RollFive()
elif die == 6:
RollSix()
if die2 == 1:
RollOne()
elif die2 == 2:
RollTwo()
elif die2 == 3:
RollThree()
elif die2 == 4:
RollFour()
elif die2 == 5:
RollFive()
elif die2 == 6:
RollSix()
return faceValue
def RollOne():
print(''' ------
| |
| o |
| |
------ ''')
return
def RollTwo():
print(''' ------
| o |
| |
| o |
------ ''')
return
def RollThree():
print(''' ------
| o |
| o |
| o |
------ ''')
return
def RollFour():
print(''' ------
| o o |
| |
| o o |
------ ''')
return
def RollFive():
print(''' ------
| o o |
| o |
| o o |
------ ''')
return
def RollSix():
print(''' ------
| o o |
| o o |
| o o |
------ ''')
return
x = 1
OverallRoll = RollDice()
print("Face value:", OverallRoll)
while x == 1:
play_again = input("Would you like to play again? Respond with 'Yes' to continue and anything else to quit.")
if play_again == 'Yes':
OverallRoll = RollDice()
print("Face value:", OverallRoll)
else:
quit()
Any tips on how to make it into classes with methods? Thank you!
Upvotes: 0
Views: 54
Reputation: 161
import random
class Game:
DIE_ASCII_ART = {1: ''' ------
| |
| o |
| |
------ ''', 2: ''' ------
| o |
| |
| o |
------ '''} # Do this for all values from 1-6
@staticmethod
def _roll_dice() -> int:
die = random.randint(1, 6)
die2 = random.randint(1, 6)
print(Game.DIE_ASCII_ART[die])
print(Game.DIE_ASCII_ART[die2])
return die + die2
@staticmethod
def run() -> None:
running = True
while running:
play_again = input("Would you like to play again? Respond with 'Yes' to continue and anything else to quit.")
if play_again == 'Yes':
overall_roll = Game._roll_dice()
print("Face value:", overall_roll)
else:
running = False
if __name__ == '__main__':
Game.run()
A few other notes about your code: You use PascalCase in your code while the convention for Python is snake_case. You defined alot of functions and wrote alot of if statements when a simple dictonary was enough to solve the problem.
A few notes about my code:
The methods in the Game
class are static because there isn't a need for instance variables in the code.
I added typing annotations for improved code quality.
I changed the game loop for using a number to a boolean because that is more readble in my opinion.
Refrences:
Upvotes: 1