1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
|
import numpy as np
import matplotlib.pyplot as plt from matplotlib import animation import matplotlib.ticker as plticker
class Direction(object): D = ['E', 'N', 'W', 'S']
def __init__(self, position, direct): self.direct = direct self.position = position
def go_one_step(self, left=True): lr = 1 if left else -1 direct = self.D[(self.D.index(self.direct) + 1 * lr) % len(self.D)] next_position = { 'E': lambda p: [p[0], p[1] + 1 * lr], 'N': lambda p: [p[0] - 1 * lr, p[1]], 'W': lambda p: [p[0], p[1] - 1 * lr], 'S': lambda p: [p[0] + 1 * lr, p[1]] } position = next_position[self.direct](self.position) return Direction(position=position, direct=direct)
N = 100 lc, hc = 1, -1
fig, ax = plt.subplots(figsize=(50, 50)) data = np.zeros((N, N)) + lc data[int(N/2), int(N/2)] *= -1
ax.get_yaxis().set_visible(False) ax.get_xaxis().set_visible(False)
time_template = 'step = %d' time_text = plt.text(0.5, N+0.1, '', fontdict={'size': 20, 'color': 'red'})
ln = plt.imshow(data, animated=True, cmap='gray')
dct = Direction(position=[int(N / 2), int(N / 2)], direct='N')
def init(): ax.set_xlim(0, N) ax.set_ylim(0, N+5) time_text.set_text('') return ln, time_text
def move(dct, data): ''' 当前为白色方格,则对当前方格取反,左转前进一格;若当前为黑色方格,取反后右转前进一格 :param dct: :param mat: :return: ''' pos = dct.position if data[pos[0], pos[1]] > 0: data[pos[0], pos[1]] *= -1 dct_ = dct.go_one_step(left=True) else: data[pos[0], pos[1]] *= -1 dct_ = dct.go_one_step(left=False)
return dct_, data
def update(f): global dct global data dct, data = move(dct, data) ln.set_data(data) time_text.set_text(time_template % f) return ln, time_text
def data_gen(): frame = 0 max_step = 11000
while frame < max_step: frame += 1 yield frame
anim = animation.FuncAnimation(fig, update, frames=data_gen, interval=10, init_func=init, blit=True, repeat=False)
anim.save('ant.gif', writer='imagemagick', fps=100)
plt.show()
|