Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. # Add your Python code here. E.g.
  2. from microbit import *
  3. from random import randint as rnd
  4.  
  5. FREE=0
  6. UP=1
  7. RIGHT=2
  8. DOWN=3
  9. LEFT=4
  10. FOOD=5
  11.  
  12. class Coord:
  13. def __init__(self, y, x):
  14. self.x = x
  15. self.y = y
  16.  
  17. def move(self, dir):
  18. if dir == UP:
  19. if self.y > 0:
  20. self.y -= 1
  21. if dir == DOWN:
  22. if self.y < 4:
  23. self.y += 1
  24. if dir == LEFT:
  25. if self.x > 0:
  26. self.x -= 1
  27. if dir == RIGHT:
  28. if self.x < 4:
  29. self.x += 1
  30.  
  31. board = [
  32. [FREE,FREE,FREE,FREE,FREE],
  33. [FREE,FREE,FREE,FREE,FREE],
  34. [FREE,FREE,FREE,FREE,FREE],
  35. [FREE,FREE,FREE,FREE,FREE],
  36. [FREE,FREE,FREE,FREE,FREE]
  37. ];
  38.  
  39. def bget(coord):
  40. return board[coord.y][coord.x]
  41.  
  42. def bset(coord, val):
  43. board[coord.y][coord.x] = val
  44.  
  45. def put_food():
  46. while True:
  47. x = rnd(0,4)
  48. y = rnd(0,4)
  49. if board[y][x] == FREE:
  50. board[y][x] = FOOD
  51. break
  52.  
  53. board[2][0] = RIGHT
  54. board[2][1] = RIGHT
  55.  
  56. head = Coord(2,1)
  57. tail = Coord(2,0)
  58.  
  59. put_food()
  60.  
  61. while True:
  62. for y in range(0,5):
  63. for x in range(0,5):
  64. n = board[y][x]
  65. brt = 0
  66.  
  67. if n == FOOD:
  68. brt = 3
  69. elif x==head.x and y == head.y:
  70. brt = 9
  71. elif n >= 1 and brt <= 4:
  72. brt = 6
  73.  
  74. display.set_pixel(x,y, brt)
  75.  
  76. sleep(500)
  77.  
  78. # handle input, move head
  79. dire = bget(head)
  80.  
  81. if button_a.was_pressed():
  82. dire -= 1
  83. if dire == 0:
  84. dire = 4
  85.  
  86. if button_b.was_pressed():
  87. dire += 1
  88. if dire == 5:
  89. dire = 1
  90.  
  91. bset(head, dire)
  92. head.move(dire)
  93.  
  94. if head.x < 0 or head.x > 4 or head.y < 0 or head.y > 4:
  95. break
  96.  
  97. oldh = bget(head)
  98. if oldh != FREE and oldh != FOOD:
  99. break
  100.  
  101. bset(head, dire)
  102.  
  103. if oldh == FOOD:
  104. put_food()
  105. else:
  106. tt = bget(tail)
  107. bset(tail, FREE)
  108. tail.move(tt)
  109.  
  110. while True:
  111. if button_a.was_pressed() or button_b.was_pressed():
  112. reset()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement