Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
zmx0142857
GitHub Repository: zmx0142857/mini-games
Path: blob/master/py/24points.py
363 views
1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
4
"""24 points"""
5
6
from random import randint
7
8
def welcome():
9
print("""[24 points]
10
11
Enter a arithmetic expression using the 4 given numbers, try to make
12
result 24! Note that you have only one chance for each problem.
13
14
g - give up
15
s - view score
16
q - quit
17
""")
18
19
def parse(s, L):
20
b = 0
21
while b != len(s):
22
while b != len(s) and not s[b].isdigit():
23
b += 1
24
e = b
25
while e != len(s) and s[e].isdigit():
26
e += 1
27
if b == e:
28
break
29
try:
30
i = int(s[b:e])
31
idx = L.index(i)
32
L.pop(idx)
33
except Exception:
34
return False
35
b = e
36
if len(L) != 0:
37
return False
38
try:
39
val = eval(s)
40
except Exception:
41
return False
42
if val != 24:
43
return False
44
if '//' in s:
45
print('floor division is not allowed')
46
return False
47
if '#' in s:
48
print('you thought this works?')
49
return False
50
for c in s:
51
if c.isalpha():
52
print('haha, I thought ahead of you!')
53
return False
54
return True
55
56
def run():
57
score = 0
58
welcome()
59
while True:
60
#L = [3, 7, 10, 12]
61
L = [randint(1, 13) for i in range(4)]
62
print(L)
63
while True:
64
s = input('> ')
65
if s == 's':
66
print('score', score)
67
elif s == 'g': # give up
68
print('you gave up')
69
score -= 1
70
break
71
elif s == 'q': # quit
72
print('game over\nscore:', score)
73
return
74
elif parse(s, L):
75
print('yay!')
76
score += 5
77
break
78
else:
79
print('oops!')
80
score -= 3
81
break
82
83
run()
84
85