回答編集履歴

1

コードを単純化

2019/08/11 00:28

投稿

can110
can110

スコア38266

test CHANGED
@@ -189,3 +189,123 @@
189
189
  ```
190
190
 
191
191
  ![イメージ説明](a60c8568cdb8607c6ad9faa969d815da.png)
192
+
193
+
194
+
195
+ ちょっと単純&汎化したコードと動画も示します。
196
+
197
+ ```Python
198
+
199
+ import numpy as np
200
+
201
+ import matplotlib.pyplot as plt
202
+
203
+ import matplotlib.animation as animation
204
+
205
+ import random
206
+
207
+
208
+
209
+ N = 10
210
+
211
+
212
+
213
+ # 描画領域を初期化
214
+
215
+ def init_plot():
216
+
217
+ plt.cla()
218
+
219
+ ax.set_xlim(-1,N+2)
220
+
221
+ ax.set_ylim(-1,N+2) # y軸を反転させる
222
+
223
+
224
+
225
+ #animateに呼び出される
226
+
227
+ def SelectData(t) :
228
+
229
+ #V_wall、H_wallについて
230
+
231
+ #[[[x,y], [X,Y]],,,],,,]となっていて
232
+
233
+ #点[x,y]と[X,Y]を結ぶと長さ1の直線になる
234
+
235
+ V_wall = [[[[i,y],[i,y+1]] for y in range(N+1)] for i in range(N+1)] #タテ線
236
+
237
+ H_wall = [[[[x,i],[x+1,i] ]for x in range(N+1)] for i in range(N+1)] #ヨコ線
238
+
239
+
240
+
241
+ i = random.randint(0,N)
242
+
243
+ j = random.randint(0,N)
244
+
245
+ if t == 1 :
246
+
247
+ u1 = V_wall[i][j][0]
248
+
249
+ u2 = V_wall[i][j][1]
250
+
251
+ else :
252
+
253
+ u1 = H_wall[i][j][0]
254
+
255
+ u2 = H_wall[i][j][1]
256
+
257
+ return (u1[0], u1[1], u2[0], u2[1])
258
+
259
+
260
+
261
+
262
+
263
+ #animation.FuncAnimationに呼び出される
264
+
265
+ def animate(data):
266
+
267
+ t = random.randint(0,1)
268
+
269
+ line = SelectData(t)
270
+
271
+ print(line) #数値確認用
272
+
273
+
274
+
275
+ # 初出現なら線分を追加
276
+
277
+ if not line in line_set:
278
+
279
+ global lines
280
+
281
+ lines = np.vstack((lines,line))
282
+
283
+ line_set.add((line))
284
+
285
+ print('add line.')
286
+
287
+
288
+
289
+ init_plot()
290
+
291
+ plt.plot(lines[:,::2].T, lines[:,1::2].T, color='red', linewidth=2)
292
+
293
+
294
+
295
+ fig = plt.figure(figsize=(5, 5))
296
+
297
+ ax = plt.gca()
298
+
299
+ lines = np.empty((0,4))
300
+
301
+ line_set = set() # 線分重複チェック用
302
+
303
+
304
+
305
+ ani = animation.FuncAnimation(fig, animate, interval=500)
306
+
307
+ plt.show()
308
+
309
+ ```
310
+
311
+ ![イメージ説明](ff103e3c165c3969044b565c2cb5409b.gif)