Python 实现珠玑妙算
时间: 2023-11-19 09:56:52 浏览: 227
编程珠玑 .
是Python实现珠玑妙算的代码:
```python
import random
# 生成随机的4个颜色
def generate_code():
colors = ['R', 'G', 'B', 'Y', 'O', 'P']
code = []
for i in range(4):
color = random.choice(colors)
code.append(color)
return code
# 判断猜测的结果
def check_guess(code, guess):
result = {'black': 0, 'white': 0}
for i in range(4):
if guess[i] == code[i]:
result['black'] += 1
elif guess[i] in code:
result['white'] += 1
return result
# 主函数
def play_game():
print('Welcome to Mastermind!')
print('Guess the 4 color code in as few tries as possible.')
print('After each guess you will get two clues.')
print('A black peg for each correct color in the correct position.')
print('A white peg for each correct color in the wrong position.')
print('Here are the colors:')
print('R G B Y O P')
code = generate_code()
guesses = 0
while True:
guess = input('Enter your guess: ').upper()
if len(guess) != 4 or not all(color in 'RGBYOP' for color in guess):
print('Invalid guess. Try again.')
continue
guesses += 1
result = check_guess(code, guess)
print('Result: ', end='')
for i in range(result['black']):
print('B', end='')
for i in range(result['white']):
print('W', end='')
print()
if result['black'] == 4:
print('Congratulations! You guessed the code in', guesses, 'tries.')
break
play_game()
```
阅读全文