我相信这段代码是相当不言自明的,但我对如何实现一个计数器感到困惑。
该代码适用于猜谜游戏
from random import randint
computer_guess = randint(0,10)
def endGame(computer_guess):
print("Cheerio")
finalOption = True
import sys
if 10/5 == 2:
sys.exit()
def menu(computer_guess):
finalOption = False
while not finalOption:
print("Welcome to this number guessing game sir")
print("You must see if you can guess my number...")
mainGame()
def mainGame():
anyInput = int(input('Give me your guess'))
if (anyInput == computer_guess):
print ("Well done, you got my number")
finalOption = True
endGame(computer_guess)
elif (computer_guess > anyInput):
print ("You need to go higher")
mainGame()
elif (anyInput > computer_guess):
print ("You need to go lower")
mainGame()
menu(computer_guess)
为代码中的空白道歉
答案 0 :(得分:0)
尝试以下模式
count = 1
while true:
guess = get input...
if guess > answer:
say something...
else if guess < answer:
say something...
else:
exit with count...
count++
答案 1 :(得分:0)
我发现像
这样的类结构class MyGame:
def __init__(self, options):
# set up initial game state
def play(self):
# play one full game;
# return WIN or LOSE when the game is over
def one_round(self):
# play one round;
# return WIN, LOSE if the game is over,
# or CONTINUE to keep playing
让您更容易思考游戏。这就像
from random import randint
LOSE, WIN, CONTINUE = 0, 1, 2
class GuessingGame:
def __init__(self, low=1, high=10, guesses=10):
self.low = low
self.high = high
self.prompt = "\nGive me your guess [{}-{}]: ".format(low, high)
self.turn = 0
self.guesses = guesses
self.target = randint(low, high)
def play(self):
print("Welcome to this number guessing game sir")
print("You must see if you can guess my number...")
while self.turn < self.guesses:
result = self.get_guess()
if result == WIN:
return WIN
# ran out of guesses!
print("Sorry, you lost! My number was {}.".format(self.target))
return LOSE
def get_guess(self):
self.turn += 1
# repeat until you get a valid guess
while True:
try:
num = int(input(self.prompt))
if self.low <= num <= self.high:
break
except ValueError:
print("It has to be an integer!")
# find the result
if num < self.target:
print("You need to go higher!")
return CONTINUE
elif num == self.target:
print("Well done, you guessed the number.")
return WIN
else:
print("You need to go lower!")
return CONTINUE
def main():
results = [0, 0]
while True:
result = GuessingGame().play()
results[result] += 1
print("\nYou have {} losses and {} wins.".format(*results))
yn = input("Do you want to play again [y/n]? ").strip().lower()
if yn in ["n", "no"]:
break
if __name__=="__main__":
main()