我正在为我的家人制作节目以保持乒乓球比分。当达到分数限制时,它应该结束游戏并说出谁赢了。这适用于一个玩家而不是另一个玩家,我无法弄清楚原因。当P2的分数达到11时,它表示P2获胜并重新开始,但是当P1的分数达到11时,它就会继续前进。请记住,我是新手。这是代码:
import sys
def defaults():
global p1sc
global p2sc
global p1adv
global p2adv
global p1name
global p2name
global sclimit
p1sc = 0
p2sc = 0
p1adv = 0
p2adv = 0
p1name = "Player 1"
p2name = "Player 2"
sclimit = 11
def checkwin():
global p1sc
global p2sc
global p1name
global p2name
global sclimit
if p2sc < sclimit:
program()
if p1sc < sclimit:
program()
if p2sc <= sclimit:
print(p2name + " wins!")
defaults()
print("New game!")
program()
if p1sc <= sclimit:
print(p1name + " wins!")
defaults()
print("New game!")
program()
elif p1sc == sclimit - 1 and p2sc == sclimit - 1:
print("Sudden Death!")
suddendeath()
else:
print("DEBUG: CHECKWIN FAILED")
def displayscore():
global p1name
global p2name
global p1sc
global p2sc
print(p1name + ": " + str(p1sc))
print(p2name + ": " + str(p2sc))
def program():
global p1sc
global p2sc
global p1name
global p2name
global sclimit
cmdinput = str(raw_input("Command: "))
if cmdinput == "1":
p1sc = p1sc + 1
displayscore()
checkwin()
elif cmdinput == "2":
p2sc = p2sc + 1
displayscore()
checkwin()
elif cmdinput == "q":
p1sc = p1sc - 1
displayscore()
checkwin()
elif cmdinput == "w":
p2sc = p2sc - 1
displayscore()
checkwin()
elif cmdinput == "name":
p1name = str(raw_input("Player 1 name: "))
print("Player 1 name has been set to " + p1name)
p2name = str(raw_input("Player 2 name: "))
print("Player 2 name has been set to " + p2name)
program()
elif cmdinput == "limit":
sclimit = raw_input("Score limit: ")
print("Score limit has been set to " + str(sclimit))
program()
elif cmdinput == "exit":
sys.exit()
else:
print("Command not recognised")
program()
def suddendeath():
global p1name
global p2name
global p1adv
global p2adv
cmdinput = str(raw_input("Command: "))
if cmdinput == "1":
if p2adv == 0:
p1adv = 1
elif p2adv == 1:
p2adv = 0
elif p1adv == 1:
print(p1name + " wins!")
defaults()
print("New game!")
program()
elif cmdinput == "2":
if p1adv == 0:
p2adv = 1
elif p1adv == 1:
p1adv = 0
elif p2adv == 1:
print(p2name + " wins!")
defaults()
print("New game!")
program()
defaults()
program()
答案 0 :(得分:0)
您的程序在条件方面存在一些问题,现在应该可以使用了:
def checkwin():
...
#call program only if both player's score is less than the limit
if p2sc < sclimit and p1sc < sclimit:
program()
#use if-elif conditions here, and you need `>=` here not `<=`.
if p2sc >= sclimit:
print(p2name + " wins!")
defaults()
print("New game!")
program()
elif p1sc >= sclimit:
print(p1name + " wins!")
defaults()
print("New game!")
program()
...
演示:(将sclimit
更改为3)
$ python so.py
Command: 1
Player 1: 1
Player 2: 0
Command: 1
Player 1: 2
Player 2: 0
Command: 2
Player 1: 2
Player 2: 1
Command: 1
Player 1: 3
Player 2: 1
Player 1 wins!
New game!
Command: 1
Player 1: 1
Player 2: 0
Command: 2
Player 1: 1
Player 2: 1
Command: 2
Player 1: 1
Player 2: 2
Command: 2
Player 1: 1
Player 2: 3
Player 2 wins!
New game!
Command: