Python RGB Matrix games and animations https://www.xythobuz.de/ledmatrix_v2.html
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tetris.py 16KB

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