满足特定条件时如何停止时间或打印时间

时间:2019-02-10 18:50:09

标签: python python-3.7

此代码是针对森林大火的模拟,我希望当所有树木都“烧焦”时停止模拟,或者运行到最后,但打印燃烧所有树木所需的时间。我不知道该如何开始,因此我们将不胜感激!我没有编码方面的经验,因此,最简单的方法将不胜感激,因为目前我必须手动查看所有树木何时烧焦,很容易错过正确的时间。

import pylab as plt
import matplotlib as mpl
import scipy as sp
import random as rd
import copy as cp
import time as tm

cdict = {
  'red'  :  ( (0.0, 1.0, 1.0),
              (0.3, 0.0, 0.0),
              (0.6, 255./256, 255./256),
              (1.0, 0.0, 0.0)),

  'green':  ( (0.0, 1.0, 1.0),
              (0.3, 1.0, 1.0),
              (0.6, 160./256, 160./256),
              (1.0, 0.0, 0.0)),

  'blue' :  ( (0.0, 1.0, 1.0),
              (0.3, 0.0, 0.0),
              (0.6, 0.0, 0.0),
              (1.0, 0.0, 0.0))
        }
cm = mpl.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)

empty, tree, fire, charred = range(4)

plt.ion()

fig1 = plt.figure(num=1)

fig1.clear()
plt.show()
fig1.canvas.draw()
fig1.canvas.flush_events()

def count_states(matrix_):

counts = [0,0,0,0]
w,h = sp.shape(matrix_)
for y in range(h):
    for x in range(w):
        state = matrix_[x,y]
        counts[int(state)] = counts[int(state)] + 1

return list(counts)

def visualise(figure,matrix,time):

plt.cla()

plt.pcolor(matrix.T, vmin=0, vmax=3, cmap=cm)

plt.axis('square')

plt.title('time = ' + str(time))

figure.canvas.draw()
figure.canvas.flush_events()
maxTime = 50
width = 20
height = 20
ptree = 1
initial_delay = 2
time_between_frames = 0.2
matrix = sp.zeros([width, height])

initial_forest = cp.copy(matrix)
for x in range(width):
for y in range(height):

    random = rd.random()

    if random < ptree:
        matrix[x,y] = tree
matrix[:0] = empty


newmatrix = cp.copy(matrix)

visualise(fig1,matrix,'initial')

plt.savefig(name + '_initial.png')


matrix[rd.randint(0,width-1), rd.randint(0,height-1)] = fire

tm.sleep(initial_delay)

for time in range(maxTime):

    visualise(fig1,matrix,time)


for y in range(height):

    for x in range(width):

        state = matrix[x,y]

        if state == fire:
            state = charred


        if state == tree:

            for dx in [-1,0,1]:

                for dy in [-1,0,1]:

                    if matrix[(x+dx)%width, (y+dy)%height] == fire:

                        state = fire
        newmatrix[x,y] = state
matrix, newmatrix = newmatrix, matrix
tm.sleep(time_between_frames)
visualise(fig1,matrix,maxTime)
plt.savefig(name + '_final.png')

0 个答案:

没有答案