python珠玑妙算
时间: 2023-11-17 10:03:01 浏览: 330
珠玑妙算是一种猜数字游戏,游戏规则如下:
1. 系统随机生成一个四位数,每个数字都不相同。
2. 玩家需要在10次机会内猜出这个四位数,每次猜测系统会给出两个数字,分别表示猜对了几个数字且位置正确(称为A),以及猜对了几个数字但位置不正确(称为B)。
3. 玩家根据系统给出的A和B来推测正确的数字。
下面是一个Python珠玑妙算的实现范例:
```python
import random
class MasterMind:
def __init__(self):
self.answer = ''.join(random.sample('0123456789', 4))
self.guess_count = 0
def guess(self, num):
self.guess_count += 1
if self.guess_count > 10:
return 'Game Over'
if not num.isdigit() or len(num) != 4:
return 'Invalid Input'
A = 0
B = 0
for i in range(4):
if num[i] == self.answer[i]:
A += 1
elif num[i] in self.answer:
B += 1
if A == 4:
return 'Congratulations! You Win!'
else:
return '{}A{}B, {} chances left.'.format(A, B, 10 - self.guess_count)
```
使用方法:
```python
game = MasterMind()
print(game.guess('1234')) # 0A2B, 9 chances left.
print(game.guess('5678')) # 0A0B, 8 chances left.
print(game.guess('4321')) # 0A4B, 7 chances left.
print(game.guess('5678')) # Invalid Input
print(game.guess('12345')) # Invalid Input
print(game.guess('56789')) # Invalid Input
print(game.guess('5670')) # Congratulations! You Win!
print(game.guess('5670')) # Game Over
```
阅读全文