Advertisement
Guest User

RPS

a guest
Jan 30th, 2016
576
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.07 KB | None | 0 0
  1. #Rock paper scissors with predictive AI
  2. import random
  3.  
  4. def CPUPlay(choices, pastMoves):
  5.     """CPUPlay() - generate computer's move based on previous player moves. returns CPU move: string"""
  6.     #if player has a favorite, pick its weakness, else pick a random one
  7.     v = list(pastMoves.values())
  8.     weakness = {'rock': 'paper', 'paper': 'scissors', 'scissors': 'rock'}
  9.     if v.count(max(v)) > 1 or sum(v) < 3: #more than one maximum -> no favorite, OR sample too small
  10.         return random.choice(choices)
  11.     else:
  12.         for key in pastMoves:
  13.             if pastMoves[key] == max(v): #find key corresponding to unique max value (favorite) and return its weakness
  14.                 return weakness[key]
  15.  
  16. def detResult(player, CPU, scores):
  17.     """detResult(player, CPU) - determine winner and update scores. return result: string."""
  18.     strength = {'rock': 'scissors', 'paper': 'rock', 'scissors': 'paper'}
  19.     if player == CPU:
  20.         return 'Tie.'
  21.     elif strength[player] == CPU:
  22.         scores['player'] += 1
  23.         return 'You win!'
  24.     else:
  25.         scores['CPU'] += 1
  26.         return 'You Lose.'
  27.  
  28. def mainGame():
  29.     """mainGame() - type rock, paper, or scissors to play the CPU. type quit to stop playing."""
  30.     playing = True
  31.     scores = {'player': 0, 'CPU': 0}
  32.     pastMoves = {'rock': 0, 'paper': 0, 'scissors': 0}
  33.     choices = 'rock', 'paper', 'scissors'
  34.     while(playing):
  35.         #receive input from player
  36.         playerMove = ''
  37.         while(playerMove not in choices): #repeat until valid input
  38.             playerMove = input('Rock, paper, scissors:\n').lower()
  39.             if playerMove == 'quit':
  40.                 playing = False
  41.                 break
  42.            
  43.         if playing:
  44.             CPUMove = CPUPlay(choices, pastMoves)            
  45.             print('CPU chooses ' + CPUMove + '!', detResult(playerMove, CPUMove, scores), 'CPU: ' + str(scores['CPU']) + ' You: ' + str(scores['player']), sep='\n', end='\n\n')
  46.             #record player's move for future decisions
  47.             pastMoves[playerMove] += 1
  48.            
  49. mainGame()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement