Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
zmx0142857
GitHub Repository: zmx0142857/mini-games
Path: blob/master/py/jiulianhuan.py
363 views
1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
4
"""Class simulating the Chinese toy Jiulianhuan."""
5
6
__author__ = 'zmx0142857'
7
8
class Jiulianhuan(object):
9
def __init__(self, loaded=True):
10
self.reset(loaded)
11
12
def reset(self, loaded=True):
13
self.log = []
14
# use 9-bit int to represent the status of jiulianhuan
15
if loaded == True:
16
self.status = (1 << 9) - 1
17
elif loaded == False:
18
self.status = 0
19
elif isinstance(loaded, int):
20
self.status = loaded
21
else:
22
raise TypeError("cannot set Jiulianhuan with type '%s'"
23
% str(type(loaded)))
24
25
def load(self, n):
26
# load the first n rings. 1 <= n <= 9
27
if n == 1:
28
self.move(1)
29
return
30
if n == 2:
31
self.move(1)
32
self.move(2)
33
return
34
self.load(n-1)
35
self.unload(n-2)
36
self.move(n)
37
self.load(n-2)
38
39
def unload(self, n):
40
# unload the first n rings. 1 <= n <= 9
41
if n == 1:
42
self.move(1)
43
return
44
if n == 2:
45
self.move(2)
46
self.move(1)
47
return
48
self.unload(n-2)
49
self.move(n)
50
self.load(n-2)
51
self.unload(n-1)
52
53
def move(self, n):
54
# change the status, then log n. 1 <= n <= 9
55
mask = 1 << (n-1)
56
self.status ^= mask
57
self.log.append(n if self.status & mask != 0 else -n)
58
59
def view(self):
60
# a straightforward view of current status
61
return format(self.status, '09b')
62
63
j = Jiulianhuan()
64
j.unload(9)
65
print(j.log)
66
print('total step:', len(j.log))
67
68