代码:
import random
def createlist(c):
a=[]
b=[]
for i in range(c):
b=[]
for j in range(c):
b.append(0)
a.append(b)
return a
def printlist(a):
for i in range(len(a)):
print(a[i])
print()
def createpeople(list,people):
for i in range(len(list)):
for j in range(people):
list[i][j]=1
list[0][0]=2
return list
def listrandom(list):
for i in range(len(list)):
for i in range(len(list[i])):
random.shuffle(list[i])
random.shuffle(list)
return list
def goto(list,x,y,a):
if list[y][x]==2:
if a==1:
if y-1>=0 and list[y-1][x]!=1 and list[y-1][x]!=2:
list[y-1][x]=2
list[y][x]=0
if a==2:
if y+1
list[y+1][x]=2
list[y][x]=0
if a==3:
if x-1>=0 and list[y][x-1]!=1 and list[y][x-1]!=2:
list[y][x-1]=2
list[y][x]=0
if a==4:
if x+1
list[y][x+1]=2
list[y][x]=0
if list[y][x]==1:
if a==1:
if y-1>=0 and list[y-1][x]!=1 and list[y-1][x]!=2:
list[y-1][x]=1
list[y][x]=0
if a==2:
if y+1
list[y+1][x]=1
list[y][x]=0
if a==3:
if x-1>=0 and list[y][x-1]!=1 and list[y][x-1]!=2:
list[y][x-1]=1
list[y][x]=0
if a==4:
if x+1
list[y][x+1]=1
list[y][x]=0
return list
def refresh(list):
for i in range(len(list)):
for j in range(len(list[i])):
if list[i][j]==1:
list=goto(list,j,i,random.randint(1,4))
return list
def disease(list,a,x,y):
if y+1
b=random.randint(1,100)
if b<=a:
list[y][x]=2
if y-1>-1 and list[y-1][x]==2:
b=random.randint(1,100)
if b<=a:
list[y][x]=2
if y+1
b=random.randint(1,100)
if b<=a:
list[y][x]=2
if y+1-1 and list[y+1][x-1]==2:
b=random.randint(1,100)
if b<=a:
list[y][x]=2
if y>-1 and x+1
b=random.randint(1,100)
if b<=a:
list[y][x]=2
if y-1>-1 and x-1>-1 and list[y-1][x-1]==2:
b=random.randint(1,100)
if b<=a:
list[y][x]=2
return list
def refresh2(list,s):
for i in range(len(list)):
for j in range(len(list[i])):
if list[i][j]==1:
list=disease(list,s,i,j)
return list
list1=createlist(10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1, 1, 0, 1, 0, 0]
[0, 1, 0, 0, 0, 1, 0, 0, 0, 0]
[1, 0, 1, 1, 0, 1, 0, 0, 0, 0]
[0, 0, 0, 0, 1, 1, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
[0, 0, 0, 0, 0, 2, 0, 0, 0, 0]
[0, 1, 0, 0, 1, 0, 2, 0, 1, 0]
[1, 1, 1, 1, 0, 0, 1, 0, 0, 0]
[0, 0, 0, 1, 1, 0, 0, 0, 0, 1]
[0, 0, 0, 0, 0, 0, 1, 1, 1, 0](结果有随机性,不一样很正常)
list1=createlist(10)
list1=createpeople(list1,3)
list1=listrandom(list1)
for i in range(5):
list1=refresh(list1)
list1=refresh2(list1,25)
printlist(list1)
此段为运行部分。
disease(list,n,x,y):判断list[y][x]处的人是否在感染者旁边,如果是,判断是否感染(取决于n)
goto(list,x,y,n): 让在list[y][x]处的人往前走一步。
createlist(n): 生成n×n的二维数组
createpeople(list,n):在二维数组中每个列表里添加n个人
listrandom(list): 将list随机打乱
refresh(list):让每个人随机迈出一步
refresh2(list,n): 判断每个人是否在感染者旁边,如果是,判断是否感染(取决于n)
printlist(list): 打印list
备注:1是普通人,2是感染者,0是空地。