patternpythonMinor
Simple Rock-Paper-Scissors to get more comfortable with OOP
Viewed 0 times
scissorspapersimplewithcomfortablemoregetrockoop
Problem
I'm trying to get a little more comfortable with using classes as they're meant to be used, instead of using them to decorate my code to make it look more legitimate. Can you see anything glaringly wrong/could be improved/possibly different implementations?
import random
class Player(object):
def __init__(self,player):
self.name = player
self.score = 0
self.choice = []
class Game(object):
player_one,player_two = Player('player_one'),Player('player_two')
def gameplay(self):
choices = ['rock','paper','scissors']
self.player_one.choice,self.player_two.choice = random.choice(choices),random.choice(choices)
if self.player_one.choice == self.player_two.choice:
print 'Tie!'
elif self.player_one.choice == 'rock' and self.player_two.choice == 'paper':
print '{0} is the winner with {1}!'.format(self.player_one.name,self.player_one.choice)
self.player_one.score += 1
elif self.player_one.choice == 'paper' and self.player_two.choice == 'rock':
print '{0} is the winner with {1}!'.format(self.player_two.name,self.player_two.choice)
self.player_two.score += 1
elif self.player_one.choice == 'scissors' and self.player_two.choice == 'rock':
self.player_two.score += 1
elif self.player_one.choice == 'scissors' and self.player_two.choice == 'paper':
self.player_one.score += 1
elif self.player_one.choice == 'paper' and self.player_two.choice == 'scissors':
self.player_two.score += 1
elif self.player_one.choice == 'rock' and self.player_two.choice == 'scissors':
self.player_one.score += 1
print '{0}\'s score is {1}, and {2}\'s score is {3}'.format(self.player_one.name,self.player_one.score,self.player_two.name,self.player_two.score)
g = Game()
for i in range(0,10000):
g.gameplay()Solution
I think that one another class Choice will be useful. You have two functionality to move to this class:
Then your gameplay function could be like
- make random choice. You can simple write
def make_random(self):
- compare two choices. You can define standard operators
def __lt__(self, oth):anddef __gt__(self, oth):. If you want handle ties than__eq__operator will be useful also.
Then your gameplay function could be like
def gameplay(self):
self.player_one.choice.make_random()
self.player_two.choice.make_random()
if self.player_one.choice > self.player_two.choice:
self.player_one.score += 1
elif self.player_one.choice < self.player_two.choice:
self.player_two.score += 1Code Snippets
def gameplay(self):
self.player_one.choice.make_random()
self.player_two.choice.make_random()
if self.player_one.choice > self.player_two.choice:
self.player_one.score += 1
elif self.player_one.choice < self.player_two.choice:
self.player_two.score += 1Context
StackExchange Code Review Q#123612, answer score: 4
Revisions (0)
No revisions yet.