In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article shows you how to achieve a simple Tetris in python, which is concise and easy to understand, and can definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
What Python is mainly used to do? Python is mainly used in: 1, Web development; 2, data science research; 3, web crawler; 4, embedded application development; 5, game development; 6, desktop application development.
1. Case introduction
Tetris is composed of four small squares with different shapes, which randomly fall from the top of the screen, press the direction key to adjust the position and direction of the plate, and spell out a complete line or lines at the bottom. These complete stripes will disappear, making room for newly fallen plates and receiving points rewards. The squares that have not been eliminated continue to pile up, and once they are piled to the top, they lose and the game is over. This example is of advanced difficulty and is suitable for users with advanced Python and Pygame programming skills.
two。 Design essentials
Border-consists of 15 to 25 spaces in which the square falls. A box, one of the small squares that make up a square, is the basic unit that makes up a square. Square-something that falls from the top of the frame, the player can flip and change position. Each square consists of four boxes. Shape-different types of squares. The name of the shape here is called T, S, Z, J, L, I, O. As shown in the following figure:
Templates-use a list to store all possible styles after the shape has been flipped. All stored in variables, variable names such as S or J. Landing-when a square reaches the bottom of the border or touches another box, the square is said to have landed. In that case, the other square will begin to fall.
3. Example effect
4. Example source code import pygameimport randomimport os pygame.init () GRID_WIDTH = 20GRID_NUM_WIDTH = 15GRID_NUM_HEIGHT = 25WIDTH, HEIGHT = GRID_WIDTH * GRID_NUM_WIDTH, GRID_WIDTH * GRID_NUM_HEIGHTSIDE_WIDTH = 200SCREEN_WIDTH = WIDTH + SIDE_WIDTHWHITE = (0xff, 0xff, 0xff) BLACK = (0,0,0) LINE_COLOR = (0x33, 0x33, 0x33) CUBE_COLORS = [(0xcc, 0x99, 0x99), (0xff, 0xff, 0x99), (0x66, 0x66, 0x99), (0x99, 0x00) 0x66), (0xff, 0xcc, 0x00), (0xcc, 0x00, 0x33), (0xff, 0x00, 0x33), (0x00, 0x66, 0x99), (0xff, 0xff, 0x33), (0x99, 0x00, 0x33), (0xcc, 0xff, 0x66), (0xff, 0x99, 0x00)] screen = pygame.display.set_mode ((SCREEN_WIDTH HEIGHT) pygame.display.set_caption ("Tetris") clock = pygame.time.Clock () FPS = 30 score = 0level = 1 screen_color_matrix = [[None] * GRID_NUM_WIDTH for i in range (GRID_NUM_HEIGHT)] # set the root directory of the game to the current folder base_folder = os.path.dirname (_ _ file__) def show_text (surf, text, size, x, y Color=WHITE): font_name = os.path.join (base_folder, 'font/font.ttc') font = pygame.font.Font (font_name, size) text_surface = font.render (text, True, color) text_rect = text_surface.get_rect () text_rect.midtop = (x, y) surf.blit (text_surface, text_rect) class CubeShape (object): SHAPES = [' Illustrated, 'jacked,' lumped,'O' I = [(0,-1), (0, 0), (0, 2)], [(- 1, 0), (0, 0), (1, 0), (2, 0)] J = [[(- 2, 0), (- 1, 0), (0, 0)]] [(- 1,0), (0,0), (0,1), (0,2)], [(0,1), (0,0), (1,0)], [(0,2), (0,1), (0,0)] L = [[(- 2,0), (- 1,0), (0)] 0), (0,1)], [(1,0), (0,0), (0,1), (0,2)], [(0,1), (0,0), (1,0)], [(0,2), (0,1), (0,0)] O = [[(0,0)] (0,1), (1,0), (1,1)] S = [[(- 1,0), (0,0), (0,1), (1,1)], [(1,1), (1,0), (0,0), (0,1)]] T = [[(0,1), (0,0), (0,1), (- 1,0)] [(- 1,0), (0,0), (1,0)], [(0,1), (0,0), (0,1), (1,0)], [(- 1,0), (0,0), (1,0), (0,1)] Z = [[(0,1), (0,0)] (1,0), (1,1)], [(- 1,0), (0,0), (0,0), (0,1)]] SHAPES_WITH_DIR = {'Illustrated: I,' Jacks: J, 'Lhasa: l,' Olympus: O, 'slots: s,' tipped: t 'Zhuan: Z} def _ init__ (self): self.shape = self.SHAPES [random.randint (0, len (self.SHAPES)-1)] # Row of dominoes self.center = (2, GRID_NUM_WIDTH / / 2) self.dir = random.randint (0 Len (self.SHAPES_WITH_ Dir [self.shape])-1) self.color = CUBE_ Colors [def get_all_gridpos. Randint (0, len (CUBE_COLORS)-1)] def get_all_gridpos (self, center=None): curr_shape = self.SHAPES_WITH_ Dir [self.shape] [self.dir] if center is None: center= [self.center [0] Self.center [1]] return [(cube [0] + center [0], cube [1] + center [1]) for cube in curr_shape] def conflict (self, center): for cube in self.get_all_gridpos (center): # beyond the screen Illegal if cube [0]
< 0 or cube[1] < 0 or cube[0] >= GRID_NUM_HEIGHT or\ cube [1] > = GRID_NUM_WIDTH: return True # is not None, indicating that a small square already exists It is also illegal to if screen_color_matrix [cube [0]] [cube [1]] is not None: return True return False def rotate (self): new_dir = self.dir + 1 new_dir% = len (self.SHAPES_WITH_ Dir [self.shape]) old_dir = self.dir self.dir = new_dir if self.conflict (self .center): self.dir = old_dir return False def down (self): # import pdb Pdb.set_trace () center = (self.center [0] + 1, self.center [1]) if self.conflict (center): return False self.center = center return True def left (self): center = (self.center [0]) Self.center [1]-1) if self.conflict (center): return False self.center = center return True def right (self): center = (self.center [0]) Self.center [1] + 1) if self.conflict (center): return False self.center = center return True def draw (self): for cube in self.get_all_gridpos (): pygame.draw.rect (screen, self.color, (cube [1] * GRID_WIDTH, cube [0] * GRID_WIDTH GRID_WIDTH, GRID_WIDTH) pygame.draw.rect (screen, WHITE, (cube [1] * GRID_WIDTH, cube [0] * GRID_WIDTH, GRID_WIDTH, GRID_WIDTH) 1) def draw_grids (): for i in range (GRID_NUM_WIDTH): pygame.draw.line (screen, LINE_COLOR, (I * GRID_WIDTH, 0), (I * GRID_WIDTH, HEIGHT)) for i in range (GRID_NUM_HEIGHT): pygame.draw.line (screen, LINE_COLOR) (0, I * GRID_WIDTH), (WIDTH, I * GRID_WIDTH) pygame.draw.line (screen, WHITE, (GRID_WIDTH * GRID_NUM_WIDTH, 0), (GRID_WIDTH * GRID_NUM_WIDTH, GRID_WIDTH * GRID_NUM_HEIGHT) def draw_matrix (): for I, row in zip (range (GRID_NUM_HEIGHT)) Screen_color_matrix): for j, color in zip (range (GRID_NUM_WIDTH), row): if color is not None: pygame.draw.rect (screen, color, (j * GRID_WIDTH, I * GRID_WIDTH, GRID_WIDTH, GRID_WIDTH)) pygame.draw.rect (screen WHITE, (j * GRID_WIDTH, I * GRID_WIDTH, GRID_WIDTH, GRID_WIDTH), 2) def draw_score (): show_text (screen, u' score: {} '.format (score), 20, WIDTH + SIDE_WIDTH / / 2 Def remove_full_line (): global screen_color_matrix global score global level new_matrix = [[None] * GRID_NUM_WIDTH for i in range (GRID_NUM_HEIGHT)] index = GRID_NUM_HEIGHT-1 n_full_line = 0 for i in range (GRID_NUM_HEIGHT-1,-1) -1): is_full = True for j in range (GRID_NUM_WIDTH): if screen_color_ Matrix [I] [j] is None: is_full = False continue if not is_full: new_ Matrix [index] = screen_color_ Matrix [I] index-= 1 else: N_full_line + = 1 score + = n_full_line level = score / / 20 + 1 screen_color_matrix = new_matrixdef show_welcome (screen): show_text (screen U 'Tetris', 30, WIDTH / 2, HEIGHT / 2) show_text (screen, u 'press any key to start the game', 20, WIDTH / 2 HEIGHT / 2 + 50) running = Truegameover = Truecounter = 0live_cube = Nonewhile running: clock.tick (FPS) for event in pygame.event.get (): if event.type = = pygame.QUIT: running = False elif event.type = = pygame.KEYDOWN: if gameover: gameover = False live_cube = CubeShape () break If event.key = = pygame.K_LEFT: live_cube.left () elif event.key = = pygame.K_RIGHT: live_cube.right () elif event.key = = pygame.K_DOWN: live_cube.down () elif event.key = = pygame.K_UP: live_cube .games () elif event.key = = pygame.K_SPACE: while live_cube.down () = = True: pass remove_full_line () # level is to facilitate the difficulty of the game The higher the level, the smaller the value of FPS / / level. The faster the screen refreshes, and the more difficult it is. If gameover is False and counter% (FPS / / level) = = 0: # down indicates moving down the dominoes, and returning False indicates that the downward move is not successful. May exceed the screen or conflict with the previously fixed # square if live_cube.down () = = False: for cube in live_cube.get_all_gridpos (): screen_color_matrix [cube [0]] [cube [1]] = live_cube.color live_cube = CubeShape () if live_cube.conflict (live _ cube.center): gameover = True score = 0 live_cube = None screen_color_matrix = [[None] * GRID_NUM_WIDTH for i in range (GRID_NUM_HEIGHT)] # eliminate full line remove_full_line () counter + = 1 # update screen screen.fill (BLACK) draw _ grids () draw_matrix () draw_score () if live_cube is not None: live_cube.draw () if gameover: show_welcome (screen) pygame.display.update () the above is how python implements simple Tetris. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.