competitive_tetris.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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(-1)
  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(1)
  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_land(state):
  122. error_code = wire_protocol.CommandResponseError.CommandResponseError.OK
  123. next_state = state.land()
  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_other(state):
  135. builder = flatbuffers.Builder()
  136. wire_protocol.CommandResponse.Start(builder)
  137. wire_protocol.CommandResponse.AddError(
  138. builder,
  139. wire_protocol.CommandResponseError.CommandResponseError.UNKNOWN_COMMAND)
  140. rsp = wire_protocol.CommandResponse.End(builder)
  141. builder.Finish(rsp)
  142. return state, builder
  143. def handle_get_game_state(state):
  144. error_code = wire_protocol.CommandResponseError.CommandResponseError.OK
  145. builder = flatbuffers.Builder()
  146. wire_protocol.GameState.StartGridVector(builder, state.data.grid.size)
  147. builder.head -= state.data.grid.size
  148. builder.Bytes[builder.head:(builder.head + state.data.grid.size)] = state.data.grid.tobytes()
  149. grid_vector = builder.EndVector(state.data.grid.size)
  150. wire_protocol.GameState.Start(builder)
  151. wire_protocol.GameState.AddRows(builder, state.data.grid.shape[0])
  152. wire_protocol.GameState.AddCols(builder, state.data.grid.shape[1])
  153. wire_protocol.GameState.AddNextPiece(builder, state.data.next_piece)
  154. wire_protocol.GameState.AddCurrentPiece(builder, state.data.current_piece)
  155. wire_protocol.GameState.AddPieceRotation(builder, state.data.rotation)
  156. wire_protocol.GameState.AddPieceRow(builder, state.data.row)
  157. wire_protocol.GameState.AddPieceCol(builder, state.data.col)
  158. wire_protocol.GameState.AddScore(builder, state.data.score)
  159. wire_protocol.GameState.AddGrid(builder, grid_vector)
  160. game_state_msg = wire_protocol.GameState.End(builder)
  161. wire_protocol.CommandResponse.Start(builder)
  162. wire_protocol.CommandResponse.AddError(builder, error_code)
  163. wire_protocol.CommandResponse.AddGameState(builder, game_state_msg)
  164. rsp = wire_protocol.CommandResponse.End(builder)
  165. builder.Finish(rsp)
  166. return state, builder
  167. def main(win):
  168. run = True
  169. frame_time = 0
  170. clock = pygame.time.Clock()
  171. zmq_context = zmq.Context()
  172. socket = zmq_context.socket(zmq.REP)
  173. socket.bind("tcp://*:5555")
  174. poller = zmq.Poller()
  175. poller.register(socket, zmq.POLLIN)
  176. def _next_piece_func():
  177. return random.choice(range(len(tetrominos.SHAPES)))
  178. state = game_state.create_initial_game_state(_next_piece_func)
  179. while run:
  180. clock.tick()
  181. dt_millis = clock.get_time()
  182. frame_time += dt_millis
  183. for event in pygame.event.get():
  184. if event.type == pygame.QUIT:
  185. run = False
  186. pygame.display.quit()
  187. for sock, _ in poller.poll(timeout=0):
  188. req_buf = sock.recv()
  189. req = wire_protocol.CommandRequest.CommandRequest.GetRootAs(req_buf)
  190. builder = None
  191. if req.Command() == wire_protocol.Command.Command.ShiftLeft:
  192. state, builder = handle_shift_left(state)
  193. elif req.Command() == wire_protocol.Command.Command.ShiftRight:
  194. state, builder = handle_shift_right(state)
  195. elif req.Command() == wire_protocol.Command.Command.Rotate:
  196. state, builder = handle_rotate(state)
  197. elif req.Command() == wire_protocol.Command.Command.Land:
  198. state, builder = handle_land(state)
  199. elif req.Command() == wire_protocol.Command.Command.GetGameState:
  200. state, builder = handle_get_game_state(state)
  201. else:
  202. state, builder = handle_other(state)
  203. socket.send(builder.Output())
  204. is_game_running = True
  205. if frame_time >= 500:
  206. state, is_game_running = state.advance()
  207. frame_time = 0
  208. draw_game_state_to_window(win, state)
  209. draw_next_shape(state.data.next_piece, win)
  210. pygame.display.update()
  211. if not is_game_running:
  212. draw_text_middle(win, "YOU LOST!", 80, (255,255,255))
  213. pygame.display.update()
  214. pygame.time.delay(1500)
  215. run = False
  216. def main_menu(win):
  217. run = True
  218. while run:
  219. win.fill((0,0,0))
  220. draw_text_middle(win, 'Press Any Key To Play', 60, (255,255,255))
  221. pygame.display.update()
  222. for event in pygame.event.get():
  223. if event.type == pygame.QUIT:
  224. run = False
  225. if event.type == pygame.KEYDOWN:
  226. main(win)
  227. pygame.display.quit()
  228. win = pygame.display.set_mode((S_WIDTH, S_HEIGHT))
  229. pygame.display.set_caption('Tetris')
  230. main_menu(win)