Python RGB Matrix games and animations https://www.xythobuz.de/ledmatrix_v2.html
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. #!/usr/bin/env python3
  2. # ----------------------------------------------------------------------------
  3. # "THE BEER-WARE LICENSE" (Revision 42):
  4. # <xythobuz@xythobuz.de> wrote this file. As long as you retain this notice
  5. # you can do whatever you want with this stuff. If we meet some day, and you
  6. # think this stuff is worth it, you can buy me a beer in return. Thomas Buck
  7. # ----------------------------------------------------------------------------
  8. from scroll import ScrollText
  9. import time
  10. import random
  11. import util
  12. class Tetris:
  13. def __init__(self, g, i, ts = 0.5, to = 60.0, w = 10, h = 22):
  14. self.gui = g
  15. self.input = i
  16. self.timestep = ts
  17. self.timeout = to
  18. self.width = min(w, self.gui.width)
  19. self.height = min(h, self.gui.height)
  20. self.endText = ScrollText(self.gui, "Game Over!", "uushi",
  21. 2, 50, (251, 72, 196))
  22. self.scoreText = ScrollText(self.gui, "Score:", "uushi",
  23. 2, 50, (63, 255, 33))
  24. self.bg = (0, 0, 0)
  25. self.colors = [
  26. (251, 72, 196), # camp23 pink
  27. (63, 255, 33), # camp23 green
  28. (255, 0, 0),
  29. #(0, 255, 0),
  30. (0, 0, 255),
  31. (255, 255, 0),
  32. (0, 255, 255),
  33. (255, 0, 255),
  34. #(255, 255, 255),
  35. ]
  36. DrawText = util.getTextDrawer()
  37. self.text = []
  38. self.text.append(DrawText(self.gui, self.colors[1])) # Green, "Score"
  39. self.text.append(DrawText(self.gui, self.colors[0])) # Pink, Score Number
  40. self.text.append(DrawText(self.gui, self.colors[4])) # Yellow, "Paused"
  41. self.text.append(DrawText(self.gui, self.colors[5])) # Blue, "next"
  42. self.text.append(DrawText(self.gui, self.colors[0])) # Pink, "Tetris"
  43. self.text.append(DrawText(self.gui, self.colors[5])) # Blue, "up"
  44. self.text[0].setText("Score:", "tom-thumb")
  45. self.text[1].setText("0", "tom-thumb")
  46. self.text[2].setText("Paused", "tom-thumb")
  47. self.text[3].setText("next", "tom-thumb")
  48. self.text[4].setText("Tetris", "tom-thumb")
  49. self.text[5].setText("up", "tom-thumb")
  50. # all [y][x] sub-lists must be the same length
  51. self.pieces = [
  52. # "I"
  53. [
  54. [1],
  55. [1],
  56. [1],
  57. [1],
  58. ],
  59. # "L"
  60. [
  61. [1, 0],
  62. [1, 0],
  63. [1, 1],
  64. ],
  65. # "J"
  66. [
  67. [0, 1],
  68. [0, 1],
  69. [1, 1],
  70. ],
  71. # "T"
  72. [
  73. [1, 1, 1],
  74. [0, 1, 0],
  75. ],
  76. # "O"
  77. [
  78. [1, 1],
  79. [1, 1],
  80. ],
  81. # "S"
  82. [
  83. [0, 1, 1],
  84. [1, 1, 0],
  85. ],
  86. # "Z"
  87. [
  88. [1, 1, 0],
  89. [0, 1, 1],
  90. ],
  91. ]
  92. self.max_width = 0
  93. self.max_height = 0
  94. for piece in self.pieces:
  95. if len(piece) > self.max_height:
  96. self.max_height = len(piece)
  97. if len(piece[0]) > self.max_width:
  98. self.max_width = len(piece[0])
  99. self.max_width += 2
  100. self.max_height += 2
  101. self.x_off = 1
  102. self.y_off = self.gui.height - self.height - 3
  103. self.next_x_off = self.gui.panelW - self.max_width - 3
  104. self.next_y_off = self.gui.panelH - self.max_height - 3
  105. random.seed()
  106. self.restart()
  107. def restart(self):
  108. self.start = time.time()
  109. self.last = time.time()
  110. self.button = None
  111. self.score = 0
  112. self.text[1].setText(str(self.score), "tom-thumb")
  113. self.done = False
  114. self.data = [[self.bg for y in range(self.height)] for x in range(self.width)]
  115. self.piece = None
  116. self.next_piece = None
  117. self.old_keys = {
  118. "left": False,
  119. "right": False,
  120. "up": False,
  121. "down": False,
  122. "a": False,
  123. "b": False,
  124. "x": False,
  125. "y": False,
  126. "l": False,
  127. "r": False,
  128. "start": False,
  129. "select": False,
  130. }
  131. self.pause = False
  132. def finished(self):
  133. if self.input == None:
  134. # backup timeout for "AI"
  135. if (time.time() - self.start) >= self.timeout:
  136. return True
  137. if self.done:
  138. # game over screen
  139. return self.scoreText.finished()
  140. return False
  141. def collision(self):
  142. # check for collision of piece with data
  143. pos = (self.piece[2], self.piece[3])
  144. for y in range(0, len(self.piece[0])):
  145. for x in range(0, len(self.piece[0][y])):
  146. # only check where piece actually is
  147. if self.piece[0][y][x] == 0:
  148. continue
  149. # check for collision with bottom wall
  150. if (y + pos[1]) >= self.height:
  151. return True
  152. # check for collision with right wall
  153. if (x + pos[0]) >= self.width:
  154. return True
  155. # check for collision with previous pieces
  156. if self.data[x + pos[0]][y + pos[1]] != self.bg:
  157. return True
  158. return False
  159. # copy piece into data buffer
  160. def put(self, clear, pos = None, pie = None):
  161. position = pos
  162. if position == None:
  163. position = (self.piece[2], self.piece[3])
  164. piece = pie
  165. if piece == None:
  166. piece = self.piece[0]
  167. for y in range(0, len(piece)):
  168. for x in range(0, len(piece[y])):
  169. # only set or clear where piece actually is
  170. if piece[y][x] == 0:
  171. continue
  172. if clear:
  173. self.data[x + position[0]][y + position[1]] = self.bg
  174. else:
  175. self.data[x + position[0]][y + position[1]] = self.piece[1]
  176. def checkWin(self):
  177. had_data = False
  178. for y in range(0, self.height):
  179. line_full = True
  180. for x in range(0, self.width):
  181. if self.data[x][y] == self.bg:
  182. line_full = False
  183. else:
  184. had_data = True
  185. if had_data and line_full:
  186. self.score += 1
  187. self.text[1].setText(str(self.score), "tom-thumb")
  188. # move stuff above into this line
  189. for y2 in reversed(range(1, y + 1)):
  190. for x in range(0, self.width):
  191. self.data[x][y2] = self.data[x][y2 - 1]
  192. # clear out top line
  193. for x in range(0, self.width):
  194. self.data[x][0] = self.bg
  195. # check for complete win
  196. board_clear = (self.piece == None)
  197. for y in range(0, self.height):
  198. for x in range(0, self.width):
  199. if self.data[x][y] != self.bg:
  200. board_clear = False
  201. if board_clear == False:
  202. break
  203. if board_clear == False:
  204. break
  205. return board_clear
  206. def step(self):
  207. if self.next_piece == None:
  208. # select a new piece type and color
  209. self.next_piece = [
  210. self.pieces[random.randrange(0, len(self.pieces))], # piece
  211. self.colors[random.randrange(0, len(self.colors))], # color
  212. 0, # x
  213. 0, # y
  214. ]
  215. # center the piece on top of the playing board
  216. self.next_piece[2] = int((self.width - len(self.next_piece[0][0])) / 2)
  217. # offsets for drawing the next piece
  218. self.piece_x_off = int((self.max_width - len(self.next_piece[0][0])) / 2)
  219. self.piece_y_off = int((self.max_height - len(self.next_piece[0])) / 2)
  220. if self.piece == None:
  221. justPlaced = True
  222. self.piece = self.next_piece
  223. self.next_piece = None
  224. if self.collision():
  225. # new piece immediately collided. game over!
  226. return False
  227. # copy piece into data buffer
  228. self.put(False)
  229. # don't move in the placement-step
  230. return True
  231. oldPosition = (self.piece[2], self.piece[3])
  232. oldPiece = [x[:] for x in self.piece[0]]
  233. # button input
  234. if self.button == "u":
  235. # rotate piece
  236. # https://stackoverflow.com/a/48444999
  237. self.piece[0] = [list(x) for x in zip(*self.piece[0][::-1])]
  238. elif self.button == "l":
  239. if self.piece[2] > 0:
  240. self.piece[2] -= 1
  241. elif self.button == "r":
  242. if self.piece[2] < (self.width - 1):
  243. self.piece[2] += 1
  244. else:
  245. # one pixel down
  246. self.piece[3] += 1
  247. # clear out piece from its old location
  248. self.put(True, oldPosition, oldPiece)
  249. collision = self.collision()
  250. if collision:
  251. # piece collided, put it back
  252. self.put(False, oldPosition, oldPiece)
  253. self.piece[0] = oldPiece
  254. self.piece[2] = oldPosition[0]
  255. self.piece[3] = oldPosition[1]
  256. if (self.button != "l") and (self.button != "r") and (self.button != "u"):
  257. # but only stop playing it if it was moving down
  258. self.piece = None
  259. # check for cleared line
  260. if self.checkWin():
  261. return False
  262. else:
  263. # copy piece at new location into buffer
  264. self.put(False)
  265. # clear previous input
  266. self.button = None
  267. return True
  268. def buttons(self):
  269. keys = self.input.get()
  270. if keys["left"] and (not self.old_keys["left"]) and (not self.old_keys["select"]):
  271. self.button = "l"
  272. elif keys["right"] and (not self.old_keys["right"]) and (not self.old_keys["select"]):
  273. self.button = "r"
  274. elif keys["up"] and (not self.old_keys["up"]) and (not self.old_keys["select"]):
  275. self.button = "u"
  276. elif keys["down"] and (not self.old_keys["select"]):
  277. self.button = "d"
  278. elif (keys["select"] and keys["start"] and (not self.old_keys["start"])) or (keys["start"] and keys["select"] and (not self.old_keys["select"])):
  279. self.restart()
  280. elif keys["start"] and (not self.old_keys["start"]) and (not self.old_keys["select"]):
  281. self.pause = not self.pause
  282. elif self.done and keys["start"] and (not self.old_keys["start"]):
  283. self.restart()
  284. elif self.done and keys["a"] and (not self.old_keys["a"]):
  285. self.restart()
  286. elif self.done and keys["b"] and (not self.old_keys["b"]):
  287. self.restart()
  288. elif self.done and keys["x"] and (not self.old_keys["x"]):
  289. self.restart()
  290. elif self.done and keys["y"] and (not self.old_keys["y"]):
  291. self.restart()
  292. self.old_keys = keys.copy()
  293. def draw_stats(self, off):
  294. x_off, y_off = off
  295. self.text[0].draw(-x_off - 2, y_off - 11)
  296. self.text[1].draw(-x_off - 2, y_off - 5)
  297. if self.pause:
  298. self.text[2].draw(-x_off - 2, -y_off + 11)
  299. def draw(self):
  300. if self.input != None:
  301. self.buttons()
  302. else:
  303. # TODO "AI"
  304. self.button = None
  305. if self.done:
  306. if self.endText.finished():
  307. self.scoreText.draw()
  308. else:
  309. self.endText.draw()
  310. self.scoreText.restart()
  311. return
  312. now = time.time()
  313. if (not self.pause) and ((self.button != None) or ((now - self.last) >= self.timestep) or (now < self.last)):
  314. # don't let user stop falling pieces by moving/rotating endlessly
  315. if (self.button != "l") and (self.button != "r") and (self.button != "u"):
  316. self.last = now
  317. cont = self.step()
  318. if cont == False:
  319. self.done = True
  320. self.scoreText.setText("Score: " + str(self.score), "uushi")
  321. self.endText.restart()
  322. # static text
  323. self.text[4].draw(-2, -11)
  324. self.text[3].draw(-14, 5)
  325. self.text[5].draw(-14, 12)
  326. # draw play area and border
  327. for x in range(-1, self.width + 1):
  328. for y in range(-1, self.height + 1):
  329. c = self.colors[1] # border color
  330. if (x >= 0) and (y >= 0) and (x < self.width) and (y < self.height):
  331. c = self.data[x][y]
  332. self.gui.set_pixel(x + 1 + self.x_off, y + 1 + self.y_off, c)
  333. # draw next piece and border
  334. for x in range(-1, self.max_width + 1):
  335. for y in range(-1, self.max_height + 1):
  336. c = self.colors[0] # border color
  337. if (x >= 0) and (y >= 0) and (x < self.max_width) and (y < self.max_height):
  338. if self.next_piece == None:
  339. c = (0, 0, 0)
  340. else:
  341. if (y >= self.piece_y_off) and (y < (len(self.next_piece[0]) + self.piece_y_off)) and (x >= self.piece_x_off) and (x < (len(self.next_piece[0][0]) + self.piece_x_off)):
  342. if self.next_piece[0][y - self.piece_y_off][x - self.piece_x_off] != 0:
  343. c = self.next_piece[1]
  344. else:
  345. c = (0, 0, 0)
  346. else:
  347. c = (0, 0, 0)
  348. self.gui.set_pixel(x + 1 + self.next_x_off, y + 1 + self.next_y_off, c)
  349. # find position for stats
  350. stats_off = None
  351. if self.gui.width > self.gui.panelW:
  352. stats_off = (self.gui.panelW, 0)
  353. elif self.gui.height > self.gui.panelH:
  354. stats_off = (0, self.gui.panelH)
  355. # second screen with stats
  356. if stats_off != None:
  357. self.draw_stats(stats_off)
  358. if __name__ == "__main__":
  359. # Need to import InputWrapper before initializing RGB Matrix on Pi
  360. i = util.getInput()
  361. t = util.getTarget(i)
  362. # show splash screen while initializing
  363. from splash import SplashScreen
  364. splash = SplashScreen(t)
  365. t.loop_start()
  366. splash.draw()
  367. t.loop_end()
  368. d = Tetris(t, i)
  369. util.loop(t, d.draw)