简体   繁体   中英

Logical error in my Python program?

I am attempting to write a simple program that will simulate a number of rock paper scissors games, and return the number of wins each item has, based on a number of games the user puts in to simulate. However, it only prints out the number of draws that have occurred, and 0 for the rock, paper, and scissors categories. I have a feeling it is something to do with my logic, but haven't been able to figure it out in the last 20 mins. Also, if you find any formatting issues or things that I could do better with this, please feel free to let me know. Also this isn't homework, just a small practice program. Thanks Guys!

#Simulates games of rock paper scissors and tracks them
from random import randint


class tracker:
    def __init__(self, games):  
        self.wins = {'rock': 0, 'paper': 0, 'scissors': 0, 'draw':0 }
        self.games = games  

    def runSim(self):
        def __init__(self):
            pass

        for game in range(0, self.games):
            keys = ['rock', 'paper', 'scissors'] 
            opp1 = keys[randint(0, 2)]
            opp2 = keys[randint(0, 2)]


            if (opp1 == opp2):
                self.wins['draw'] = self.wins['draw'] + 1
            elif ((opp1 or opp2) == 'rock') and ((opp1 or opp2) == 'scissors'):
                self.wins['rock'] = self.wins['rock'] + 1
            elif ((opp1 or opp2) == 'paper' and (opp1 or opp2) == 'scissors'):
                self.wins['scissors'] = self.wins['scissors'] + 1
            elif ((opp1 or opp2) == 'paper' and (opp1 or opp2) == 'rock'):
                self.wins['paper'] = self.wins['paper'] + 1

        print 'draws: ', self.wins['draw']
        print 'rocks: ', self.wins['rock']
        print 'papers: ', self.wins['paper']
        print 'scissors: ', self.wins['scissors']
        print keys


while True:
    print 'enter number of games: '
    games = raw_input()
    games = int(games)  
    tracker = tracker(games)
    tracker.runSim()

The following does not do what you think it does:

(opp1 or opp2) == 'rock'

You'll want to write the following instead:

(opp1 == 'rock' or opp2 == 'rock')

What (opp1 or opp2) == 'rock' does is:

  • evaluate (opp1 or opp2) and compare that to 'rock' .

Given that opp1 and opp2 are both non-empty strings the expression (opp1 or opp2) will evaluate to True . So you're basically comparing True == 'rock' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM