Home > Software engineering >  Appending limited inputs to the list
Appending limited inputs to the list

Time:09-05

I am making a simple scissors paper stone game. I have a function which prompts the user to choose the shapes they want, and then storing all the shapes into a list. The number of rounds/shapes they can choose depends on the "size" parameter. This is what i have currently

import random

shapes = []

def getHandOfShapes(size):
    if size < 3:
        print("Please enter a size of at least 3")
    else:
      for i in range(size):
        shape = input(f"Shape {i 1}: please select a shape: ")
        shapes.append(shape.upper())
        return shapes

However, i want to make it such that if the user keys in the same shape more than twice, the shape will not be appended into the list, and the user will be prompted again at that exact round of prompting. An example of the desired output is shown below

print(getHandOfShapes(4))

Shape 1: please select a shape: scissors 
Shape 2: please select a shape: SCISSORS 
Shape 3: please select a shape: scissors 
Cannot have more than 2 SCISSORS!!
Shape 3: please select a shape: Paper 
Shape 4: please select a shape: Stone
['SCISSORS','SCISSORS','PAPER','STONE']

CodePudding user response:

Well since you are looking to keep the user within a certain prompt the best thing to do is use a while statement and keep track of how many shapes the user enters. For example rock = counter[0], paper = counter[1], scissors = counter[2]. I'm just laying down the logic here not really in python just pseudocode

Initialize all counters to 0

if shape == rock 
   counter[0]  = 1
else if shape == paper
    counter[1]  = 1
else if shape == scissors 
    counter[1]  = 1
   

while counter[0] != 3 or counter[1] != 3 or counter[2] != 3
     if counter[0] == 3
        shape = input("Cannot have more than 2 rocks! Enter another value")  

        if shape != rocks     #The user must enter another value other than rock 
           counter[0] -= 1    #to exit the code otherwise the counter isn't      
           break              #reset to 2 and the loop continues to ask for a shape
     else if counter[1] == 3
         ... same as above

CodePudding user response:

Add a condition to count the actual number of occurences, and so use a while loop instead, because you the for loop will increment no mattre what happen

def getHandOfShapes(size):
    shapes = []
    if size < 3:
        print("Please enter a size of at least 3")
    else:
        while len(shapes) != size:
            shape = input(f"Shape {len(shapes)   1}: please select a shape: ").upper()
            if shapes.count(shape) >= 2:
                print("There is already 2 occurrences of that shape, that is the maximum")
                continue
            shapes.append(shape)
    return shapes
  • Related