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

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