色婷婷狠狠18禁久久YY,CHINESE性内射高清国产,国产女人18毛片水真多1,国产AV在线观看

python盲棋代碼分析

呂致盈1年前7瀏覽0評論

Python盲棋代碼分析

import random
colors = ['R', 'G', 'B', 'Y']
# Generate the code
code = ''.join(random.choices(colors, k=4))
print('Guess the 4 color code!')
# Loop through all the guesses
for guess_num in range(1, 11):
print(f'Guess #{guess_num}')
guess = ''
# Get user input for guess
while len(guess) != 4 or any(color not in colors for color in guess):
guess = input('Enter your guess (RGBY): ').upper()
# Check the guess
correct = 0
misplaced = 0
for i in range(4):
if guess[i] == code[i]:
correct += 1
elif guess[i] in code:
misplaced += 1
print(f'Correct: {correct}')
print(f'Misplaced: {misplaced}')
if correct == 4:
print(f'You win in {guess_num} guesses!')
break
# If no correct guess in 10 tries, end the game
else:
print(f'Sorry, the code was {code}. Better luck next time!')

這段代碼是一個簡單的猜色盲棋游戲,其中:

colors = ['R', 'G', 'B', 'Y']

定義了棋子顏色列表。

code = ''.join(random.choices(colors, k=4))

使用random.choices函數(shù)隨機(jī)生成四個棋子顏色組成的顏色碼。

for guess_num in range(1, 11):

使用for循環(huán)進(jìn)行猜測,猜測次數(shù)最多為10次。

while len(guess) != 4 or any(color not in colors for color in guess):

使用while循環(huán)進(jìn)行用戶輸入驗證,當(dāng)用戶輸入的顏色碼不符合要求時,要求用戶重新輸入。

if guess[i] == code[i]:
correct += 1
elif guess[i] in code:
misplaced += 1

在每次猜測結(jié)束后,使用if語句進(jìn)行結(jié)果計算。其中,correct表示顏色與位置都猜對的數(shù)量,而misplaced表示顏色猜對但位置不對的數(shù)量。

if correct == 4:
print(f'You win in {guess_num} guesses!')
break

如果用戶在10次內(nèi)猜對了所有顏色與位置,就會使用if語句判斷,輸出勝利提示,并結(jié)束for循環(huán)。

else:
print(f'Sorry, the code was {code}. Better luck next time!')

如果for循環(huán)執(zhí)行完畢后,用戶沒有猜對所有顏色與位置,就會進(jìn)入到else語句,輸出失敗提示并結(jié)束游戲。