問候各位程式員!快速免責宣告我是編碼世界的新手,目前正在學習 Python,對所有資訊和幫助我感到高興!
因此,如果您不熟悉它,我正在嘗試撰寫策劃者游戲,這是維基百科的文章: 文本
我試圖使用全域變數,但每次在函式中使用全域變數時,它都會將其回傳到全域變數中,該變數只是設定回其原始值。
如果您需要我提供更多資訊,請告訴我!期待您的回音。
import random
colors = "YORPGB"
global secret
global round
global hits
global close
def gen_random_secret():
secret = ""
for i in range(4):
n = random.randrange(6)
secret = colors[n]
return secret
def get_guess(force_valid_input):
while True:
guess = input(f"Available letters: {colors}\nPut in a 4-letter Word with the available letters, there can be duplicates! ").upper()
if len(guess) ==4:
return guess
else:
if not force_valid_input:
return None
print("Wrong Input try again!")
def check_guess(guess,secret):
hits = 0
close = 0
for i in range(4):
if guess[i] == secret[i]:
hits = 1
for color in colors:
close = min(secret.count(color),guess.count(color))
close = close - hits
return hits, close
def start_game():
print("Welcome to the Mastermind game!\nGenerating random code...")
round = 1
history = []
hits = 0
close = 0
secret = gen_random_secret()
while round<=12:
guess = get_guess(True)
check_guess(guess,secret)
print(f"Hits: {hits} Close: {close}\n")
if hits == 4:
break
round = 1
history.append((guess,hits,close))
print()
for row in history:
for color in row[0]:
print(f" {color}", end="")
print(f" | {row[1]} {row[2]}")
print()
if hits == 4:
print(f"Congratz u guessed it the code was: {secret}")
else:
print(f"You ran out off attempts, you lose bitch!\n the secret Word was {secret}")
start_game()
uj5u.com熱心網友回復:
您必須global在函式內呼叫以讓函式知道使用全域變數。
例如:
def gen_random_secret():
global secret
secret = ""
for i in range(4):
n = random.randrange(6)
secret = colors[n]
return secret
代替:
global secret
def gen_random_secret():
secret = ""
for i in range(4):
n = random.randrange(6)
secret = colors[n]
return secret
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/415994.html
標籤:
