The previous version of the game that implements playing against the computer does not present an opportunity for a strategy, because the computerâs choice is determined pseudo-randomly, with an essentially equal chance that it will choose rock, paper, or scissors. But, the getComputerInput
function can be modified to take the playerâs history into account. The simplest strategy that the computer can employ would be to predict that the player has the same likelihood of making each choice as the proportion that particular choice represents of the total number of choices that the player made previously. For example, if 10
out of 40
choices that the player made in the past were paper, the prediction would be that the player would choose paper 10
out of 40
times in the future. Accordingly, the computer would employ the strategy of choosing scissors in a proportion of about 10
out of 40
rounds, because scissors beats paper.
The following revision of the getComputerInput
function implements a strategy that is close to what is described above, but slightly modified to accommodate the first round of the game, when there is no history to consult. The computer picks a number between 1
and the total number of previous rounds + 3. The number that is chosen is mapped to rock, paper, or scissors, based on a proportion related to the playerâs history.
To use the new version of the function, which is displayed below, simply copy it, and paste it in place of the original version of the function.
So, what should the playerâs strategy be, considering that the computer is using this algorithm? Iâm not sure, but would suggest that the player consider what the computer is most likely to choose, based on the playerâs past choices. For example, if the player has chosen rock most of the time in the past, then the computer is most likely to choose paper, based on the algorithm. So the player should now begin to favor scissors, in order win by cutting that paper.
Hereâs the new version of the function:
def getComputerInput(): # make it generative
# Pick a "randomized" choice,
# biased according to the players past choices
# For example, if the player has picked mostly paper,
# the computer will favor choosing scissors
global history
user_r_count = 0
user_p_count = 0
user_s_count = 0
# Total up choices that user has made duirng previous rounds
for h in history:
ch = h[0]
if ch == "r":
user_r_count += 1 # rock count
elif ch == "p":
user_p_count += 1 # paper count
else:
user_s_count += 1 # scissors count
r = random.randint(1, user_r_count + user_p_count + user_s_count + 3)
# Bias the computer's randomized choice, based on player history
if r <= user_r_count + 1:
return "p"
elif user_r_count + 1 < r <= user_r_count + user_p_count + 2:
return "s"
else:
return "r"