Python RGB Matrix games and animations https://www.xythobuz.de/ledmatrix_v2.html
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

tetris.py 16KB

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