competitive_tetris.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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
  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. pygame.font.init()
  17. # GLOBALS VARS
  18. S_WIDTH = 800
  19. S_HEIGHT = 700
  20. PLAY_WIDTH = 300 # meaning 300 // 10 = 30 width per block
  21. PLAY_HEIGHT = 600 # meaning 600 // 20 = 30 height per block
  22. BLOCK_SIZE = 30
  23. TOP_LEFT_X = (S_WIDTH - PLAY_WIDTH) // 2
  24. TOP_LEFT_Y = S_HEIGHT - PLAY_HEIGHT
  25. def draw_text_middle(surface, text, size, color):
  26. font = pygame.font.SysFont("comicsans", size, bold=True)
  27. label = font.render(text, 1, color)
  28. surface.blit(label, (TOP_LEFT_X + PLAY_WIDTH /2 - (label.get_width()/2), TOP_LEFT_Y + PLAY_HEIGHT/2 - label.get_height()/2))
  29. def draw_grid(surface, grid):
  30. sx = TOP_LEFT_X
  31. sy = TOP_LEFT_Y
  32. for i in range(len(grid)):
  33. pygame.draw.line(surface, (128,128,128), (sx, sy + i*BLOCK_SIZE), (sx+PLAY_WIDTH, sy+ i*BLOCK_SIZE))
  34. for j in range(len(grid[i])):
  35. pygame.draw.line(surface, (128, 128, 128), (sx + j*BLOCK_SIZE, sy),(sx + j*BLOCK_SIZE, sy + PLAY_HEIGHT))
  36. def draw_next_shape(shape, surface):
  37. font = pygame.font.SysFont('comicsans', 30)
  38. label = font.render('Next Shape', 1, (255,255,255))
  39. sx = TOP_LEFT_X + PLAY_WIDTH + 0
  40. sy = TOP_LEFT_Y + PLAY_HEIGHT/2 - 100
  41. shape_raw = tetrominos.SHAPES_RAW[shape][0]
  42. for i, line in enumerate(shape_raw):
  43. row = list(line)
  44. for j, column in enumerate(row):
  45. if column == '0':
  46. pygame.draw.rect(
  47. surface, (255,0,0),
  48. (sx + j*BLOCK_SIZE, sy + i*BLOCK_SIZE,
  49. BLOCK_SIZE, BLOCK_SIZE),
  50. 0)
  51. surface.blit(label, (sx + 10, sy - 30))
  52. def draw_game_state_to_window(surface, game_state):
  53. surface.fill((0, 0, 0))
  54. pygame.font.init()
  55. font = pygame.font.SysFont('comicsans', 60)
  56. label = font.render('Tetris', 1, (255, 255, 255))
  57. surface.blit(label,
  58. (TOP_LEFT_X + PLAY_WIDTH / 2 - (label.get_width() / 2), 30))
  59. # current score
  60. font = pygame.font.SysFont('comicsans', 30)
  61. label = font.render(f'Score: {game_state.score}', 1, (255,255,255))
  62. sx = TOP_LEFT_X + PLAY_WIDTH + 50
  63. sy = TOP_LEFT_Y + PLAY_HEIGHT/2 - 100
  64. surface.blit(label, (sx + 20, sy + 160))
  65. field = game.get_game_state_field(game_state)
  66. for row in range(field.shape[0]):
  67. for col in range(field.shape[1]):
  68. color = (0,0,0)
  69. tile = field[row,col]
  70. if tile == 1:
  71. color = (0,255,0)
  72. elif tile == 2:
  73. color = (255,0,0)
  74. pygame.draw.rect(surface, color,
  75. (TOP_LEFT_X + col*BLOCK_SIZE,
  76. TOP_LEFT_Y + row*BLOCK_SIZE,
  77. BLOCK_SIZE, BLOCK_SIZE), 0)
  78. pygame.draw.rect(surface, (255, 0, 0),
  79. (TOP_LEFT_X, TOP_LEFT_Y, PLAY_WIDTH, PLAY_HEIGHT), 5)
  80. draw_grid(surface, field)
  81. def main(win):
  82. run = True
  83. frame_time = 0
  84. clock = pygame.time.Clock()
  85. zmq_context = zmq.Context()
  86. socket = zmq_context.socket(zmq.REP)
  87. socket.bind("tcp://*:5555")
  88. poller = zmq.Poller()
  89. poller.register(socket, zmq.POLLIN)
  90. def _next_piece_func():
  91. return random.choice(range(len(tetrominos.SHAPES)))
  92. game_state = game.initial_game_state(_next_piece_func(),
  93. _next_piece_func())
  94. while run:
  95. clock.tick()
  96. dt_millis = clock.get_time()
  97. frame_time += dt_millis
  98. for event in pygame.event.get():
  99. if event.type == pygame.QUIT:
  100. run = False
  101. pygame.display.quit()
  102. for sock, _ in poller.poll(timeout=0):
  103. req_buf = sock.recv()
  104. req = wire_protocol.CommandRequest.CommandRequest.GetRootAs(req_buf)
  105. error_code = wire_protocol.CommandResponseError.CommandResponseError.OK
  106. cells = None
  107. if req.Command() == wire_protocol.Command.Command.ShiftLeft:
  108. game_state = game.game_state_shift(game_state, -1)
  109. elif req.Command() == wire_protocol.Command.Command.ShiftRight:
  110. game_state = game.game_state_shift(game_state, 1)
  111. elif req.Command() == wire_protocol.Command.Command.Rotate:
  112. game_state = game.game_state_rotate(game_state)
  113. elif req.Command() == wire_protocol.Command.Command.Land:
  114. game_state = game.game_state_land(game_state)
  115. elif req.Command() == wire_protocol.Command.Command.GetGameState:
  116. cells = game.get_game_state_field(game_state)
  117. else:
  118. error_code = wire_protocol.CommandResponseError.CommandResponseError.UNKNOWN_COMMAND
  119. builder = flatbuffers.Builder()
  120. playfield = None
  121. if cells is not None:
  122. wire_protocol.Playfield.StartCellsVector(builder, cells.size)
  123. builder.head -= cells.size
  124. builder.Bytes[builder.head:(builder.head + cells.size)] = cells.tobytes()
  125. cells_vector = builder.EndVector(cells.size)
  126. wire_protocol.Playfield.Start(builder)
  127. wire_protocol.Playfield.AddRows(builder, cells.shape[0])
  128. wire_protocol.Playfield.AddCols(builder, cells.shape[1])
  129. wire_protocol.Playfield.AddCells(builder, cells_vector)
  130. playfield = wire_protocol.Playfield.End(builder)
  131. wire_protocol.CommandResponse.Start(builder)
  132. wire_protocol.CommandResponse.AddError(builder, error_code)
  133. if playfield is not None:
  134. wire_protocol.CommandResponse.AddPlayfield(builder, playfield)
  135. rsp = wire_protocol.CommandResponse.End(builder)
  136. builder.Finish(rsp)
  137. socket.send(builder.Output())
  138. is_game_running = True
  139. if frame_time >= 500:
  140. game_state, is_game_running = game.advance_game_state(
  141. game_state, _next_piece_func)
  142. frame_time = 0
  143. draw_game_state_to_window(win, game_state)
  144. draw_next_shape(game_state.next_piece, win)
  145. pygame.display.update()
  146. if not is_game_running:
  147. draw_text_middle(win, "YOU LOST!", 80, (255,255,255))
  148. pygame.display.update()
  149. pygame.time.delay(1500)
  150. run = False
  151. def main_menu(win):
  152. run = True
  153. while run:
  154. win.fill((0,0,0))
  155. draw_text_middle(win, 'Press Any Key To Play', 60, (255,255,255))
  156. pygame.display.update()
  157. for event in pygame.event.get():
  158. if event.type == pygame.QUIT:
  159. run = False
  160. if event.type == pygame.KEYDOWN:
  161. main(win)
  162. pygame.display.quit()
  163. win = pygame.display.set_mode((S_WIDTH, S_HEIGHT))
  164. pygame.display.set_caption('Tetris')
  165. main_menu(win)