所以我最近开始编程python,并且我有这个代码的一个问题。当玩家在使用所有生命后得到的答案不正确时,应该打印出答案,但只有在第一次播放图层时他们再次播放,如果发现错误,他们不会得到正确答案。当玩家得到正确的答案时,它也会这样做。另外,当您使用再次播放功能时,电脑选择的号码保持不变。请尽量帮助我,但要记住我的理解手杖在Python的某些方面非常有限。我收录了很多评论来帮助别人了解正在发生的事情。我已经包含了我的代码以及我在shell中获得的内容。Python猜测游戏即使玩家获得答案,也会打印正确的答案
代码:
#imports required modules
import random
from time import sleep
#correct number variable created
num = 0
#generates number at random
comp_num = random.randint(1,10)
print('I\'m thinking of a number guess what it is...\n')
#main game code
def main():
#lives created
lives = 3
#correct number variable reset
num = 0
while lives >= 1:
#player guesses
guess = int(input('Guess: '))
if comp_num == guess:
#if correct says well done
input('\nWell Done! You guessed Correctly!\n')
#player doesn't get told what the number is if there right
num = num +1
break
elif comp_num >= guess:
#if guess is too low tells player
#one live taken for incorrect guess
lives = lives -1
print('\nToo low!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
elif comp_num <= guess:
#if guess is too high tells player
#one live taken for incorrect guess
lives = lives -1
print('\nToo high!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
def end():
#asks player if they want to play again
play_again = input('Would you like to play again?[Y/N] ')
while play_again.lower() == 'y':
#if they do game resets and plays again
if play_again.lower() == 'y':
comp_num = random.randint(1,10)
print('\nI\'m thinking of a number guess what it is...\n')
main()
play_again = input('Would you like to play again?[Y/N] ')
if play_again.lower() == 'n':
break
if play_again.lower() == 'n':
#if they don't game ends
input('\nOk, Press enter to exit')
exit()
main()
if num != 1:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
end()
SHELL:
I'm thinking of a number guess what it is...
Guess: 5
Well Done! You guessed Correctly!
The number I was thinking of was... 5 !
Would you like to play again?[Y/N] y
I'm thinking of a number guess what it is...
Guess: 5
Well Done! You guessed Correctly!
Would you like to play again?[Y/N] y
I'm thinking of a number guess what it is...
Guess: 5
Well Done! You guessed Correctly!
Would you like to play again?[Y/N] y
I'm thinking of a number guess what it is...
Guess: 5
Well Done! You guessed Correctly!
作为一个侧面说明:您可以使用双引号字符串,所以你不需要用反斜杠转义撇号。例如:'print(“我在想数字猜它是什么...... \ n”)'。另外,你是否真的希望所有这些'\ n'到处都是,给你在每行输出之间留出一条空白线? – abarnert 2014-11-22 00:05:09
您在'main'之前初始化变量,然后重复调用'main'(使用相同的变量)。相反,在'main'里初始化你的变量,这样它们就不会被重用。 – khelwood 2014-11-22 00:15:11
谢谢@abarnert会将其改为双引号 - 由于学校计算机系统较差,我需要备用线路,否则它们会被挤在一起。 – person101 2014-11-22 08:44:28