Advertisement
Guest User

Untitled

a guest
Nov 15th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.58 KB | None | 0 0
  1. from random import randrange as rand
  2. import pygame, sys
  3.  
  4.  
  5.  
  6. config = {
  7.     'cell_size':    20,
  8.     'cols':     8,
  9.     'rows':     16,
  10.     'delay':    750,
  11.     'maxfps':   30
  12. }
  13.  
  14. colors = [
  15. (0,   0,   0  ),
  16. (255, 0,   0  ),
  17. (0,   150, 0  ),
  18. (0,   0,   255),
  19. (255, 120, 0  ),
  20. (255, 255, 0  ),
  21. (180, 0,   255),
  22. (0,   220, 220)
  23. ]
  24.  
  25. # Define the shapes of the single parts
  26. tetris_shapes = [
  27.     [[1, 1, 1],
  28.      [0, 1, 0]],
  29.    
  30.     [[0, 2, 2],
  31.      [2, 2, 0]],
  32.    
  33.     [[3, 3, 0],
  34.      [0, 3, 3]],
  35.    
  36.     [[4, 0, 0],
  37.      [4, 4, 4]],
  38.    
  39.     [[0, 0, 5],
  40.      [5, 5, 5]],
  41.    
  42.     [[6, 6, 6, 6]],
  43.    
  44.     [[7, 7],
  45.      [7, 7]]
  46. ]
  47.  
  48. def rotate_clockwise(shape):
  49.     return [ [ shape[y][x]
  50.             for y in xrange(len(shape)) ]
  51.         for x in xrange(len(shape[0]) - 1, -1, -1) ]
  52.  
  53. def check_collision(board, shape, offset):
  54.     off_x, off_y = offset
  55.     for cy, row in enumerate(shape):
  56.         for cx, cell in enumerate(row):
  57.             try:
  58.                 if cell and board[ cy + off_y ][ cx + off_x ]:
  59.                     return True
  60.             except IndexError:
  61.                 return True
  62.     return False
  63.  
  64. def remove_row(board, row):
  65.     del board[row]
  66.     return [[0 for i in xrange(config['cols'])]] + board
  67.    
  68. def join_matrixes(mat1, mat2, mat2_off):
  69.     off_x, off_y = mat2_off
  70.     for cy, row in enumerate(mat2):
  71.         for cx, val in enumerate(row):
  72.             mat1[cy+off_y-1 ][cx+off_x] += val
  73.     return mat1
  74.  
  75. def new_board():
  76.     board = [ [ 0 for x in xrange(config['cols']) ]
  77.             for y in xrange(config['rows']) ]
  78.     board += [[ 1 for x in xrange(config['cols'])]]
  79.     return board
  80.  
  81. class TetrisApp(object):
  82.     def __init__(self):
  83.         pygame.init()
  84.         pygame.key.set_repeat(250,25)
  85.         self.width = config['cell_size']*config['cols']
  86.         self.height = config['cell_size']*config['rows']
  87.        
  88.         self.screen = pygame.display.set_mode((self.width, self.height))
  89.         pygame.event.set_blocked(pygame.MOUSEMOTION)
  90.         self.init_game()
  91.    
  92.     def new_stone(self):
  93.         self.stone = tetris_shapes[rand(len(tetris_shapes))]
  94.         self.stone_x = int(config['cols'] / 2 - len(self.stone[0])/2)
  95.         self.stone_y = 0
  96.        
  97.         if check_collision(self.board,
  98.                            self.stone,
  99.                            (self.stone_x, self.stone_y)):
  100.             self.gameover = True
  101.    
  102.     def init_game(self):
  103.         self.board = new_board()
  104.         self.new_stone()
  105.    
  106.     def center_msg(self, msg):
  107.         for i, line in enumerate(msg.splitlines()):
  108.             msg_image =  pygame.font.Font(
  109.                 pygame.font.get_default_font(), 12).render(
  110.                     line, False, (255,255,255), (0,0,0))
  111.        
  112.             msgim_center_x, msgim_center_y = msg_image.get_size()
  113.             msgim_center_x //= 2
  114.             msgim_center_y //= 2
  115.        
  116.             self.screen.blit(msg_image, (
  117.               self.width // 2-msgim_center_x,
  118.               self.height // 2-msgim_center_y+i*22))
  119.    
  120.     def draw_matrix(self, matrix, offset):
  121.         off_x, off_y  = offset
  122.         for y, row in enumerate(matrix):
  123.             for x, val in enumerate(row):
  124.                 if val:
  125.                     pygame.draw.rect(
  126.                         self.screen,
  127.                         colors[val],
  128.                         pygame.Rect(
  129.                             (off_x+x) *
  130.                               config['cell_size'],
  131.                             (off_y+y) *
  132.                               config['cell_size'],
  133.                             config['cell_size'],
  134.                             config['cell_size']),0)
  135.    
  136.     def move(self, delta_x):
  137.         if not self.gameover and not self.paused:
  138.             new_x = self.stone_x + delta_x
  139.             if new_x < 0:
  140.                 new_x = 0
  141.             if new_x > config['cols'] - len(self.stone[0]):
  142.                 new_x = config['cols'] - len(self.stone[0])
  143.             if not check_collision(self.board,
  144.                                    self.stone,
  145.                                    (new_x, self.stone_y)):
  146.                 self.stone_x = new_x
  147.     def quit(self):
  148.         self.center_msg("Exiting...")
  149.         pygame.display.update()
  150.         sys.exit()
  151.    
  152.     def drop(self):
  153.         if not self.gameover and not self.paused:
  154.             self.stone_y += 1
  155.             if check_collision(self.board,
  156.                                self.stone,
  157.                                (self.stone_x, self.stone_y)):
  158.                 self.board = join_matrixes(
  159.                   self.board,
  160.                   self.stone,
  161.                   (self.stone_x, self.stone_y))
  162.                 self.new_stone()
  163.                 while True:
  164.                     for i, row in enumerate(self.board[:-1]):
  165.                         if 0 not in row:
  166.                             self.board = remove_row(
  167.                               self.board, i)
  168.                             break
  169.                     else:
  170.                         break
  171.    
  172.     def rotate_stone(self):
  173.         if not self.gameover and not self.paused:
  174.             new_stone = rotate_clockwise(self.stone)
  175.             if not check_collision(self.board,
  176.                                    new_stone,
  177.                                    (self.stone_x, self.stone_y)):
  178.                 self.stone = new_stone
  179.    
  180.     def toggle_pause(self):
  181.         self.paused = not self.paused
  182.    
  183.     def start_game(self):
  184.         if self.gameover:
  185.             self.init_game()
  186.             self.gameover = False
  187.    
  188.     def run(self):
  189.         key_actions = {
  190.             'ESCAPE':   self.quit,
  191.             'LEFT':     lambda:self.move(-1),
  192.             'RIGHT':    lambda:self.move(+1),
  193.             'DOWN':     self.drop,
  194.             'UP':       self.rotate_stone,
  195.             'p':        self.toggle_pause,
  196.             'SPACE':    self.start_game
  197.         }
  198.        
  199.         self.gameover = False
  200.         self.paused = False
  201.        
  202.         pygame.time.set_timer(pygame.USEREVENT+1, config['delay'])
  203.         dont_burn_my_cpu = pygame.time.Clock()
  204.         while 1:
  205.             self.screen.fill((0,0,0))
  206.             if self.gameover:
  207.                 self.center_msg("""Game Over!
  208. Press space to continue""")
  209.             else:
  210.                 if self.paused:
  211.                     self.center_msg("Paused")
  212.                 else:
  213.                     self.draw_matrix(self.board, (0,0))
  214.                     self.draw_matrix(self.stone,
  215.                                      (self.stone_x,
  216.                                       self.stone_y))
  217.             pygame.display.update()
  218.            
  219.             for event in pygame.event.get():
  220.                 if event.type == pygame.USEREVENT+1:
  221.                     self.drop()
  222.                 elif event.type == pygame.QUIT:
  223.                     self.quit()
  224.                 elif event.type == pygame.KEYDOWN:
  225.                     for key in key_actions:
  226.                         if event.key == eval("pygame.K_"
  227.                         +key):
  228.                             key_actions[key]()
  229.                    
  230.             dont_burn_my_cpu.tick(config['maxfps'])
  231.  
  232. if __name__ == '__main__':
  233.     App = TetrisApp()
  234.     App.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement