competitive_tetris.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. #!/usr/bin/python3
  2. """
  3. Competitive tetris server
  4. """
  5. import random
  6. import pygame
  7. import zmq
  8. import flatbuffers
  9. import tetrominos
  10. import game_state
  11. import wire_protocol.Command
  12. import wire_protocol.CommandRequest
  13. import wire_protocol.CommandResponse
  14. import wire_protocol.Playfield
  15. import wire_protocol.CommandResponseError
  16. import wire_protocol.GameState
  17. pygame.font.init()
  18. # GLOBALS VARS
  19. S_WIDTH = 800
  20. S_HEIGHT = 700
  21. PLAY_WIDTH = 300 # meaning 300 // 10 = 30 width per block
  22. PLAY_HEIGHT = 600 # meaning 600 // 20 = 30 height per block
  23. BLOCK_SIZE = 30
  24. TOP_LEFT_X = (S_WIDTH - PLAY_WIDTH) // 2
  25. TOP_LEFT_Y = S_HEIGHT - PLAY_HEIGHT
  26. def draw_text_middle(surface, text, size, color):
  27. font = pygame.font.SysFont("comicsans", size, bold=True)
  28. label = font.render(text, 1, color)
  29. surface.blit(label, (TOP_LEFT_X + PLAY_WIDTH /2 - (label.get_width()/2), TOP_LEFT_Y + PLAY_HEIGHT/2 - label.get_height()/2))
  30. def draw_grid(surface, grid):
  31. sx = TOP_LEFT_X
  32. sy = TOP_LEFT_Y
  33. for i in range(len(grid)):
  34. pygame.draw.line(surface, (128,128,128), (sx, sy + i*BLOCK_SIZE), (sx+PLAY_WIDTH, sy+ i*BLOCK_SIZE))
  35. for j in range(len(grid[i])):
  36. pygame.draw.line(surface, (128, 128, 128), (sx + j*BLOCK_SIZE, sy),(sx + j*BLOCK_SIZE, sy + PLAY_HEIGHT))
  37. def draw_next_shape(shape, surface):
  38. font = pygame.font.SysFont('comicsans', 30)
  39. label = font.render('Next Shape', 1, (255,255,255))
  40. sx = TOP_LEFT_X + PLAY_WIDTH + 0
  41. sy = TOP_LEFT_Y + PLAY_HEIGHT/2 - 100
  42. shape_raw = tetrominos.SHAPES_RAW[shape][0]
  43. for i, line in enumerate(shape_raw):
  44. row = list(line)
  45. for j, column in enumerate(row):
  46. if column == '0':
  47. pygame.draw.rect(
  48. surface, (255,0,0),
  49. (sx + j*BLOCK_SIZE, sy + i*BLOCK_SIZE,
  50. BLOCK_SIZE, BLOCK_SIZE),
  51. 0)
  52. surface.blit(label, (sx + 10, sy - 30))
  53. def draw_game_state_to_window(surface, state):
  54. surface.fill((0, 0, 0))
  55. pygame.font.init()
  56. font = pygame.font.SysFont('comicsans', 60)
  57. label = font.render('Tetris', 1, (255, 255, 255))
  58. surface.blit(label,
  59. (TOP_LEFT_X + PLAY_WIDTH / 2 - (label.get_width() / 2), 30))
  60. # current score
  61. font = pygame.font.SysFont('comicsans', 30)
  62. label = font.render(f'Score: {state.data.score}', 1, (255,255,255))
  63. sx = TOP_LEFT_X + PLAY_WIDTH + 50
  64. sy = TOP_LEFT_Y + PLAY_HEIGHT/2 - 100
  65. surface.blit(label, (sx + 20, sy + 160))
  66. field = state.get_field()
  67. for row in range(field.shape[0]):
  68. for col in range(field.shape[1]):
  69. color = (0,0,0)
  70. tile = field[row,col]
  71. if tile == 1:
  72. color = (0,255,0)
  73. elif tile == 2:
  74. color = (255,0,0)
  75. pygame.draw.rect(surface, color,
  76. (TOP_LEFT_X + col*BLOCK_SIZE,
  77. TOP_LEFT_Y + row*BLOCK_SIZE,
  78. BLOCK_SIZE, BLOCK_SIZE), 0)
  79. pygame.draw.rect(surface, (255, 0, 0),
  80. (TOP_LEFT_X, TOP_LEFT_Y, PLAY_WIDTH, PLAY_HEIGHT), 5)
  81. draw_grid(surface, field)
  82. def handle_shift_left(state):
  83. error_code = wire_protocol.CommandResponseError.CommandResponseError.OK
  84. next_state = state.shift_left()
  85. if next_state is None:
  86. error_code = wire_protocol.CommandResponseError.CommandResponseError.INVALID_COMMAND
  87. else:
  88. state = next_state
  89. builder = flatbuffers.Builder()
  90. wire_protocol.CommandResponse.Start(builder)
  91. wire_protocol.CommandResponse.AddError(builder, error_code)
  92. rsp = wire_protocol.CommandResponse.End(builder)
  93. builder.Finish(rsp)
  94. return state, builder
  95. def handle_shift_right(state):
  96. error_code = wire_protocol.CommandResponseError.CommandResponseError.OK
  97. next_state = state.shift_right()
  98. if next_state is None:
  99. error_code = wire_protocol.CommandResponseError.CommandResponseError.INVALID_COMMAND
  100. else:
  101. state = next_state
  102. builder = flatbuffers.Builder()
  103. wire_protocol.CommandResponse.Start(builder)
  104. wire_protocol.CommandResponse.AddError(builder, error_code)
  105. rsp = wire_protocol.CommandResponse.End(builder)
  106. builder.Finish(rsp)
  107. return state, builder
  108. def handle_rotate(state):
  109. error_code = wire_protocol.CommandResponseError.CommandResponseError.OK
  110. next_state = state.rotate()
  111. if next_state is None:
  112. error_code = wire_protocol.CommandResponseError.CommandResponseError.INVALID_COMMAND
  113. else:
  114. state = next_state
  115. builder = flatbuffers.Builder()
  116. wire_protocol.CommandResponse.Start(builder)
  117. wire_protocol.CommandResponse.AddError(builder, error_code)
  118. rsp = wire_protocol.CommandResponse.End(builder)
  119. builder.Finish(rsp)
  120. return state, builder
  121. def handle_down(state):
  122. error_code = wire_protocol.CommandResponseError.CommandResponseError.OK
  123. next_state = state.down()
  124. if next_state is None:
  125. error_code = wire_protocol.CommandResponseError.CommandResponseError.INVALID_COMMAND
  126. else:
  127. state = next_state
  128. builder = flatbuffers.Builder()
  129. wire_protocol.CommandResponse.Start(builder)
  130. wire_protocol.CommandResponse.AddError(builder, error_code)
  131. rsp = wire_protocol.CommandResponse.End(builder)
  132. builder.Finish(rsp)
  133. return state, builder
  134. def handle_land(state):
  135. error_code = wire_protocol.CommandResponseError.CommandResponseError.OK
  136. next_state = state.land()
  137. if next_state is None:
  138. error_code = wire_protocol.CommandResponseError.CommandResponseError.INVALID_COMMAND
  139. else:
  140. state = next_state
  141. builder = flatbuffers.Builder()
  142. wire_protocol.CommandResponse.Start(builder)
  143. wire_protocol.CommandResponse.AddError(builder, error_code)
  144. rsp = wire_protocol.CommandResponse.End(builder)
  145. builder.Finish(rsp)
  146. return state, builder
  147. def handle_other(state):
  148. builder = flatbuffers.Builder()
  149. wire_protocol.CommandResponse.Start(builder)
  150. wire_protocol.CommandResponse.AddError(
  151. builder,
  152. wire_protocol.CommandResponseError.CommandResponseError.UNKNOWN_COMMAND)
  153. rsp = wire_protocol.CommandResponse.End(builder)
  154. builder.Finish(rsp)
  155. return state, builder
  156. def handle_get_game_state(state):
  157. error_code = wire_protocol.CommandResponseError.CommandResponseError.OK
  158. builder = flatbuffers.Builder()
  159. wire_protocol.GameState.StartGridVector(builder, state.data.grid.size)
  160. builder.head -= state.data.grid.size
  161. builder.Bytes[builder.head:(builder.head + state.data.grid.size)] = state.data.grid.tobytes()
  162. grid_vector = builder.EndVector(state.data.grid.size)
  163. wire_protocol.GameState.Start(builder)
  164. wire_protocol.GameState.AddRows(builder, state.data.grid.shape[0])
  165. wire_protocol.GameState.AddCols(builder, state.data.grid.shape[1])
  166. wire_protocol.GameState.AddNextPiece(builder, state.data.next_piece)
  167. wire_protocol.GameState.AddCurrentPiece(builder, state.data.current_piece)
  168. wire_protocol.GameState.AddPieceRotation(builder, state.data.rotation)
  169. wire_protocol.GameState.AddPieceRow(builder, state.data.row)
  170. wire_protocol.GameState.AddPieceCol(builder, state.data.col)
  171. wire_protocol.GameState.AddScore(builder, state.data.score)
  172. wire_protocol.GameState.AddGrid(builder, grid_vector)
  173. game_state_msg = wire_protocol.GameState.End(builder)
  174. wire_protocol.CommandResponse.Start(builder)
  175. wire_protocol.CommandResponse.AddError(builder, error_code)
  176. wire_protocol.CommandResponse.AddGameState(builder, game_state_msg)
  177. rsp = wire_protocol.CommandResponse.End(builder)
  178. builder.Finish(rsp)
  179. return state, builder
  180. def main(win):
  181. run = True
  182. frame_time = 0
  183. clock = pygame.time.Clock()
  184. zmq_context = zmq.Context()
  185. socket = zmq_context.socket(zmq.REP)
  186. socket.bind("tcp://*:5555")
  187. poller = zmq.Poller()
  188. poller.register(socket, zmq.POLLIN)
  189. def _next_piece_func():
  190. return random.choice(range(len(tetrominos.SHAPES)))
  191. state = game_state.create_initial_game_state(_next_piece_func)
  192. while run:
  193. clock.tick()
  194. dt_millis = clock.get_time()
  195. frame_time += dt_millis
  196. for event in pygame.event.get():
  197. if event.type == pygame.QUIT:
  198. run = False
  199. pygame.display.quit()
  200. for sock, _ in poller.poll(timeout=0):
  201. req_buf = sock.recv()
  202. req = wire_protocol.CommandRequest.CommandRequest.GetRootAs(req_buf)
  203. builder = None
  204. if req.Command() == wire_protocol.Command.Command.ShiftLeft:
  205. state, builder = handle_shift_left(state)
  206. elif req.Command() == wire_protocol.Command.Command.ShiftRight:
  207. state, builder = handle_shift_right(state)
  208. elif req.Command() == wire_protocol.Command.Command.Rotate:
  209. state, builder = handle_rotate(state)
  210. elif req.Command() == wire_protocol.Command.Command.Down:
  211. state, builder = handle_down(state)
  212. elif req.Command() == wire_protocol.Command.Command.Land:
  213. state, builder = handle_land(state)
  214. elif req.Command() == wire_protocol.Command.Command.GetGameState:
  215. state, builder = handle_get_game_state(state)
  216. else:
  217. state, builder = handle_other(state)
  218. socket.send(builder.Output())
  219. is_game_running = True
  220. if frame_time >= 500:
  221. state, is_game_running = state.advance()
  222. frame_time = 0
  223. draw_game_state_to_window(win, state)
  224. draw_next_shape(state.data.next_piece, win)
  225. pygame.display.update()
  226. if not is_game_running:
  227. draw_text_middle(win, "YOU LOST!", 80, (255,255,255))
  228. pygame.display.update()
  229. pygame.time.delay(1500)
  230. run = False
  231. def main_menu(win):
  232. run = True
  233. while run:
  234. win.fill((0,0,0))
  235. draw_text_middle(win, 'Press Any Key To Play', 60, (255,255,255))
  236. pygame.display.update()
  237. for event in pygame.event.get():
  238. if event.type == pygame.QUIT:
  239. run = False
  240. if event.type == pygame.KEYDOWN:
  241. main(win)
  242. pygame.display.quit()
  243. win = pygame.display.set_mode((S_WIDTH, S_HEIGHT))
  244. pygame.display.set_caption('Tetris')
  245. main_menu(win)