[英]Appending limited inputs to the list
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.
我有一个 function 提示用户选择他们想要的形状,然后将所有形状存储到一个列表中。 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
所需 output 的示例如下所示
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']
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.好吧,既然您希望将用户保持在某个提示内,那么最好的办法是使用 while 语句并跟踪用户输入的形状数量。 For example rock = counter[0], paper = counter[1], scissors = counter[2].
例如rock = counter[0],paper = counter[1],scissors = counter[2]。 I'm just laying down the logic here not really in python just pseudocode
我只是在 python 中放下逻辑,只是伪代码
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
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添加一个条件来计算实际发生的次数,因此请改用while循环,因为无论发生什么,for循环都会增加
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.