所以我最近開始編程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