原创 newbit上的life game(生命游戏)

2017-5-7 21:23 2063 24 24 分类: MCU/ 嵌入式

Life game是一个广泛流传的游戏,也是一个数学/哲学问题。理论方面的问题先不研究了,它的基本规则是根据一个点周围点的数量,决定这个点是继续存在还是消失。


下面是国外网友写的life game例程,用micropython编程。使用方法是:



  • 长按B键切换运行模式和设置模式

  • 设置模式下长按A键设置或者消除一个点

  • 设置模式下倾斜newbit移动光标点


https://hackster.imgix.net/uploads/attachments/299089/mgol_mYikrUsa1c.gif?auto=compress%2Cformat&w=900&h=675&fit=min


micropython代码


from microbit import *

def draw_cursor(universe, mode, x, y):
if mode == "CONFIG":
if cell_state(universe, x, y) == 0:
display.set_pixel(x, y, 4)
else:
display.set_pixel(x, y, 6)

def draw_universe( universe ):
for y in range(0, 5):
for x in range(0, 5):
display.set_pixel(x, y, universe[x + y * 5])

def evolve( universe ):
next_universe = []
for y in range(0, 5):
for x in range(0, 5):
cell_neighbours = count_neighbours(universe, x, y)
cell_is_alive = cell_state(universe, x, y) == 1
if cell_is_alive and cell_neighbours < 2:
next_universe.append(0)
elif cell_is_alive and (cell_neighbours == 2 or cell_neighbours == 3):
next_universe.append(9)
elif cell_is_alive and cell_neighbours > 3:
next_universe.append(0)
elif not cell_is_alive and cell_neighbours == 3:
next_universe.append(9)
else:
next_universe.append(0)
return next_universe

def cell_state(universe, x, y):
state = 1
if universe[x + 5 * y] == 0:
state = 0
return state

def count_neighbours(universe, x, y):
neighbours = -cell_state(universe, x, y)
for dy in [-1, 0, 1]:
for dx in [-1, 0, 1]:
neighbours += cell_state(universe, (x + dx) % 5, (y + dy) % 5)
return neighbours


current_universe = [ 0, 0 ,0 ,0 ,0,
0, 0, 9, 0, 0,
0, 0, 9, 0, 0,
0, 0, 9, 0, 0,
0, 0, 0, 0, 0,]

cursor_x = 2
cursor_y = 2

mode = "CONFIG"
display.scroll(mode)

while True:

if mode == "RUN":
current_universe = evolve( current_universe )

if button_b.is_pressed():
mode = "CONFIG"
display.scroll(mode)


if mode == "CONFIG":

accelerometer_xyz = accelerometer.get_values()
if accelerometer_xyz[0] < -200:
cursor_x = (cursor_x - 1) % 5
if accelerometer_xyz[0] > 200:
cursor_x = (cursor_x + 1) % 5
if accelerometer_xyz[1] < -200:
cursor_y = (cursor_y - 1) % 5
if accelerometer_xyz[1] > 200:
cursor_y = (cursor_y + 1) % 5

if button_a.is_pressed():
if cell_state(current_universe, cursor_x, cursor_y) == 0:
current_universe[cursor_x + 5 * cursor_y] = 9
else:
current_universe[cursor_x + 5 * cursor_y] = 0

if button_b.is_pressed():
mode = "RUN"
display.scroll(mode)


draw_universe( current_universe )
draw_cursor(current_universe, mode, cursor_x, cursor_y)
sleep(1000)

转自:https://www.hackster.io/ivo-ruaro/conway-s-game-of-life-e383e3


文章评论0条评论)

登录后参与讨论
我要评论
0
24
关闭 站长推荐上一条 /2 下一条