我正在制作一個簡單的剪刀紙石頭游戲。我有一個功能可以提示用戶選擇他們想要的形狀,然后將所有形狀存盤到一個串列中。他們可以選擇的圓形/形狀的數量取決于“大小”引數。這就是我目前擁有的
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
但是,我想這樣做,如果用戶在同一形狀中鍵入兩次以上,則該形狀將不會附加到串列中,并且將在該輪提示時再次提示用戶。所需輸出的示例如下所示
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']
uj5u.com熱心網友回復:
添加一個條件來計算實際發生的次數,因此請改用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
uj5u.com熱心網友回復:
好吧,既然您希望將用戶保持在某個提示內,那么最好的辦法是使用 while 陳述句并跟蹤用戶輸入的形狀數量。例如rock = counter[0],paper = counter[1],scissors = counter[2]。我只是在這里放下邏輯而不是真正在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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/505435.html
下一篇:訪問具有已知深度變數的嵌套串列
