mardi 26 octobre 2021

Why does a randomizer act like a 'generator'

I am trying to make a simple rock paper scissors game on python

TypeError: unsupported operand type(s) for +: 'generator' and 'str'

This was the error message, that was given after I placed a randomizer in the code:

Traceback (most recent call last)

<ipython-input-4-dea4c40cfdcd> in <module>()
 49   if key == 'q':
 50     break
---> 51   player_score, comp_score = gameplay(player_score, comp_score)
 52   print('Score is: YOU ', player_score, ' - ', comp_score, ' COMPUTER')
 53   print('')

 <ipython-input-4-dea4c40cfdcd> in gameplay(player_score, comp_score)
 12 
 13   comp_move = moves[randomize]
 ---> 14   battle = key + '-' + comp_move
 15 
 16   comp_print = (word for position, word in ['rock', 'paper', 'scissors'] if position == randomize - 1)

What is this 'generator' object?? In google they say it is made from using a loop, so it is a kind of sequence, but didn't generate it with loop, rather than while loop. Is this loop the reason for the error? Moreover, I am not using the sequence of letters, but only a single letter from it, and I am calling it with its position number in the sequence?

Here is the code until the error:

 from random import randint

 player_score = 0
 comp_score = 0
 key = None

 # Setting the rules
 choices = {'r-s': 'rock breaks scissors', 'p-r': 'paper envelopes rock', 's-p': 'scissors cut paper'}
 moves = {1: 'r', 2: 'p', 3: 's'}

 def gameplay(player_score, comp_score):

   comp_move = moves[randomize]
   battle = key + '-' + comp_move

Here are more details about the code: the random number is initialized inside the while loop

while True:
  randomize = randint(1, 3)
  print('<r>ock, <p>aper or <s>cissors? Press any key to continue; <q> for exit')
  key = check_input()
  if key == 'q':
    break
  player_score, comp_score = gameplay(player_score, comp_score)
  print('Score is: YOU ', player_score, ' - ', comp_score, ' COMPUTER')
  print('')
  key = None

however, I am using a single variable not a sequence of variables here, or am I wrong?




Aucun commentaire:

Enregistrer un commentaire