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函数随机生成四个棋子颜色组成的颜色码。
for guess_num in range(1, 11):
使用for循环进行猜测,猜测次数最多为10次。
while len(guess) != 4 or any(color not in colors for color in guess):
使用while循环进行用户输入验证,当用户输入的颜色码不符合要求时,要求用户重新输入。
if guess[i] == code[i]: correct += 1 elif guess[i] in code: misplaced += 1
在每次猜测结束后,使用if语句进行结果计算。其中,correct表示颜色与位置都猜对的数量,而misplaced表示颜色猜对但位置不对的数量。
if correct == 4: print(f'You win in {guess_num} guesses!') break
如果用户在10次内猜对了所有颜色与位置,就会使用if语句判断,输出胜利提示,并结束for循环。
else: print(f'Sorry, the code was {code}. Better luck next time!')
如果for循环执行完毕后,用户没有猜对所有颜色与位置,就会进入到else语句,输出失败提示并结束游戏。
本文可能转载于网络公开资源,如果侵犯您的权益,请联系我们删除。
0