我正在学习python并参加猜谜游戏。我的游戏正常,但是我的获胜条件同时显示“您赢”和“您输”,我认为我的“如果”陈述不正确,但我可能是错误的。 另外,我的赢失打印存在问题,我只能让它打印损失。 预先感谢!
import random
print("Number guessing game")
name = input("Hello, please input your name: ")
win = 0
loss = 0
diceRoll = random.randint(1, 6)
if diceRoll == 1:
print("You have 1 guess.")
if diceRoll == 2:
print("You have 2 guesses.")
if diceRoll == 3:
print("You have 3 guesses.")
if diceRoll == 4:
print("You have 4 guesses.")
if diceRoll == 5:
print("You have 5 guesses.")
if diceRoll == 6:
print("You have 6 guesses.")
number = random.randint(1, 5)
chances = 0
print("Guess a number between 1 and 5:")
while chances < diceRoll:
guess = int(input())
if guess == number:
print("Congratulation YOU WON!!!")
break
win += 1
elif guess < number:
print("Your guess was too low")
else:
print("Your guess was too high")
chances += 1
if not chances == 0:
print("YOU LOSE!!! The number is", number)
loss += 1
print(name)
print("win: "+str(win))
print("loss: "+str(loss))
答案 0 :(得分:0)
尝试更改循环。由于正确无误,因此可以使用while: else
。否则,您可以赢得最后的机会,但仍然会收到失败的消息。
while chances < diceRoll:
guess = int(input())
if guess == number:
print("Congratulation YOU WON!!!")
break
win += 1
elif guess < number:
print("Your guess was too low")
else:
print("Your guess was too high")
chances += 1
else:
print("YOU LOSE!!! The number is", number)
loss += 1
答案 1 :(得分:0)
在while循环中,if语句应为...
int cmpStructs(const void *a1, const void *a2){
struct data *a = (struct data *)a1;
struct data *b = (struct data *)a2;
if(strcmp(a->win,b->win)>0){
return -1;
} else if (strcmp(a->wine,b->wine)<0){
return 1;
} else if(a->stall>b->stall){
return 1;
} else if(a->stall<b->stall){
return -1;
}
///continued if else statements for the rest of the fields
return 0;
};
最后一个if语句应该是...
if guess == number:
print("Something)
win += 1
break
答案 2 :(得分:0)
问题出在最后的if
语句中。如果玩家的chances
大于diceRoll
,则玩家输球;而如果玩家的机会不为0,即玩家失败一次,则if条件为true。
最终if语句的代码应如下所示:
if chances >= diceRoll:
print("YOU LOSE!!! The number is", number)
loss += 1
关于打印获胜的问题,这里的问题是while循环内的第一个if语句。如果玩家首先赢了break
语句,则代码会在不增加win
计数器的情况下退出while循环。
只需将break
语句与win += 1
交换,就会产生奇迹:
if guess == number:
print("Congratulation YOU WON!!!")
win += 1
break
答案 3 :(得分:0)
开始看看