[英]Game with 2-player
一個有2個玩家的游戲。 在此游戲中,每個玩家輪流從三個袋子之一(A,B,C)中刪除1-5個對象。刪除最后一個對象的玩家將贏得比賽。 規則如下:
•在游戲開始時,每個袋子都包含10個物體。
•玩家可以一次從一個袋子中取出物品。
•播放器無法選擇刪除0個對象。 對象的數量必須在1到5(含)之間。
•當所有行李都空了時,游戲結束。
•當前玩家必須先選擇包(A或B或C),然后再選擇必須從該包中移除的物體數。
•您還必須檢查用戶輸入是否有效。 它是有效的行李包(A或B或C)嗎? 它是有效數字(介於1到5之間)嗎? 另外,袋子中是否有足夠的物品? 如果不滿足這些條件中的任何一個,請再次要求用戶輸入。 (您需要使用循環來執行此操作)
例:
ABC
10 10 10 Player1從B獲得5個對象。
10 5 10 Player2從C獲取5個對象。
10 5 5 Player1從A獲得3個對象。
7 5 5 Player2從B獲得3個對象。
7 2 5 Player1從C獲取5個對象。
7 2 0 Player2從A獲得2個對象。
5 2 0 Player1從A獲得1個對象。
4 2 0 Player2從A獲得3個對象。
1 2 0 Player1從B獲取1個對象。
1 1 0 Player2從B獲得1個對象。
1 0 0 Player1從A獲得1個對象。
* 注意: *我只能使用循環,或者如果條件沒有列表或其他
我已經走了這么遠:
A=5
B=5
C=5
total_objects=15
Player1=0
Player2=0
while total_objects>0:
selected_bag=input("Choose the bag:")
if selected_bag == A or B or C:
print("Valid bag")
else:
selected_bag=input("Not a valid bag choose again:")
removed=int(input("How many objects do you want to remove?"))
if removed>5 or removed<1:
int(input("You must enter between 1 and 5:"))
elif removed == 1 or 2 or 3 or 4 or 5:
if selected_bag == A:
A-=removed
if selected_bag == B:
B-=removed
if selected_bag == C:
C-=removed
if A>0:
print("There are",A,"objects left")
elif B>0:
print("There are",B,"objects left")
elif C>0:
print("There are",C,"objects left")
print("You win!")
那不是您檢查項目的方式。 這行:
if selected_bag == A or B or C:
不按照您的想法去做。 它計算A or B or C
,然后將其與selected_bag
進行比較。
改用in
運算符。 另外,您需要檢查的是字符串,而不是變量:
if selected in ('A', 'B', 'C'):
正如abarnert所述,您還需要更改其他內容。
另外,更改此行:
elif removed == 1 or 2 or 3 or 4 or 5:
為了正確循環,您需要在條件為false時continue
執行以下操作:
else:
selected_bag=input("Not a valid bag choose again:")
continue
簡單的else
語句。
else:
老實說,您的代碼有很多問題。 @abarnert比我能更好地解釋這一點。
這條線有兩個大問題:
if selected_bag == A or B or C:
正如aikid已經解釋過的,第一個問題就是那樣做or
不能那樣做。 你想in
。
第二個問題是您要檢查用戶是否輸入了任何字符串"A"
, "B"
和"C"
,而不是是否輸入了A
, B
和C
變量的值。
因此,您想要的是:
if selected_bag in ('A', 'B', 'C'):
您會再次重復這兩個問題,並需要再次解決它們:
elif removed == 1 or 2 or 3 or 4 or 5:
… 需要是 …
elif removed in (1, 2, 3, 4, 5):
……也許更好……
elif 1 <= removed <= 5:
然后,在其中:
if selected_bag == A:
A-=removed
… 需要是 …
if selected_bag == "A":
A-=removed
…和B和C一樣。
最后,這一部分:
if removed>5 or removed<1:
int(input("You must enter between 1 and 5:"))
……沒有任何用處。 它要求用戶輸入另一個數字,將結果轉換為int
,然后將其忽略,直到if A>0:
part為止。 如果要一直詢問直到用戶給出有效答案,則需要某種循環。 當然,您必須將該值存儲在某個地方才能有用。 例如:
removed=int(input("How many objects do you want to remove?"))
while removed>5 or removed<1:
removed = int(input("You must enter between 1 and 5:"))
而且, selected_bag
輸入部分也有一個非常相似的錯誤。
如果要處理兩名玩家,則需要跟蹤當前輪到誰。 一種簡單的方法是存儲一個current_player
變量,並在每次循環時都對其進行更新。 例如:
current_player = 2
while total_objects>0:
current_player = 2 if current_player == 1 else 1
print("Player", current_player, " is now up.")
# all the existing code
print('Player", current_player, "wins!")
如果您想“擲硬幣”以決定誰先走,則只需將第一行更改為:
import random
current_player = random.choice((1, 2))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.