python - Simulate several rounds of rock, paper and scissors -
i trying implement function takes integer n , simulates n rounds of rock, paper, scissors between players player 1 , player 2. player wins rounds wins n-round game, ties possible. function should print result of game shown.
>>> simul(1) player 1 >>> simul(1) tie >>>simul(100) player 2
i think need approach in modular fashion. in other words, need combine @ least 2 functions, problem can't seem figure out how that. how can activate result embedded function when calling simul()
function?
so have created function simulates game rock, paper, scissors execution function rps(p1, p2)
. code following:
def rps(p1,p2): #tie if (p1==p2): return 0 # player 1 wins elif p1+p2 in ['pr','rs','sp']: return -1 else: return 1 # player 2 wins
this i'm bit stuck. need activate function when executing simul()
function—how can that? have far following:
def rps(p1,p2): #tie if (p1==p2): return 0 # player 1 wins elif p1+p2 in ['pr','rs','sp']: return -1 else: return 1 # player 2 wins def choose_rps(): import random random.choice('rps') def simul(n): p1_wins, p2_wins = 0, 0 in range(n): p1 = choose_rps() p2 = choose_rps() result = rps(p1, p2) if result == -1: p1_wins += 1 elif result == 1: p2_wins += 1 if p1_wins > p2_wins: return 'player 1' elif p1_wins == p2_wins: return 'tie' else: return 'player 2'
to "activate" function, call it. example:
def simul(n): score = 0 in range(n): p1 = choose_rps() p2 = choose_rps() result = rps(p1, p2) score += result if score < 0: print('player 1') elif score == 0: print('tie') else: print('player 2')
of course need write choose_rps
function (which randomly chooses , returns 1 of r
, p
, or s
)—but, can see, call same way rps
function.
to put script:
def rps(p1, p2): # ... code here def choose_rps(): # implement here def simul(n): # code above
and you'll want drive it, such this:
if __name__ == '__main__': import sys n = int(sys.argv[1]) if len(sys.argv) > 1 else 5 simul(n)
… or…
while true: n = int(input('how many trials?')) # raw_input python 2.x simul(n)
if want, can simplify further. example, can turn whole loop sum
call generator expression:
def simul(n): score = sum(rps(choose_rps(), choose_rps()) _ in range(n))
Comments
Post a Comment