Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
zmx0142857
GitHub Repository: zmx0142857/mini-games
Path: blob/master/py/guess4digits.py
363 views
1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
4
"""A 4-digit guess game from my old television."""
5
6
__author__ = 'zmx0142857'
7
8
import random
9
10
def init():
11
L = [i for i in range(10)]
12
answer = ''
13
for i in range(4):
14
answer += str(L.pop(random.randint(0, 9-i)))
15
#print('answer:', answer)
16
return answer
17
18
def isvalid(guess):
19
msg = 'input must be a non-repeat 4-digit number'
20
if len(guess) != 4:
21
print('invalid input 1:', msg)
22
return False
23
if any(not c.isdigit() for c in guess):
24
print('invalid input 2:', msg)
25
return False
26
for i in range(4):
27
if guess[i] in guess[:i]:
28
print('invalid input 3:', msg)
29
return False
30
return True
31
32
def judge(gus, ans):
33
zipped = zip(gus, ans)
34
cntA = 0
35
for pair in zipped:
36
if pair[0] == pair[1]:
37
cntA += 1
38
cntB = len(set(gus) & set(ans)) - cntA
39
return cntA, cntB
40
41
def play():
42
answer = init()
43
cnt = 1
44
while True:
45
guess = input('guess %d: ' % cnt)
46
if not isvalid(guess):
47
continue
48
result = judge(guess, answer)
49
if result == (4, 0):
50
print('you win!')
51
break
52
else:
53
print('%dA %dB' % result)
54
cnt += 1
55
56
if input('another game? ')[0].lower() != 'y':
57
exit()
58
try:
59
while True:
60
play()
61
except EOFError:
62
print()
63
64