Tetris In Python Code
The Tetris In Python Code is a GUI based title matching puzzle game which is very easy to understand and use. Talking about the gameplay it’s all same as the real one. The user has to manage the random sequence of Tetriminos. This Tetris Game In Python project, I will teach you on How To Make A Tetris Game In Python.
A Tetris Game Python player has steps to be follow of playing the game, first the player has to move each one sideways and rotate quarter-turns to form a solid horizontal line without leaving gaps. It disappears whenever such lines are formed. The user can only enter to next level if they cross the specific number by the game rules. As the game progresses, the Tetriminos falls faster and faster. As a result, the game ends when the stack of Tetriminos reaches to the top of the field and no new Tetriminos are able to enter.
Anyway if you want level up your knowledge in programming especially games in python, try this new article I’ve made for you Code For Game in Python: Python Game Projects With Source Code
This Tetris Game In Python also includes a downloadable Tetris Game Source Code In Python, just find the downloadable source code below and click to start downloading.
To start Create Tetris In Python,makes sure that you have PyCharm IDE installed in you computer.
By the way if you are new to python programming and you don’t know what would be the the Python IDE to use, I have here a list of Best Python IDE for Windows, Linux, Mac OS that will suit for you. I also have here How to Download and Install Latest Version of Python on Windows.
Steps on how to create Tetris In Python Code
Tetris In Python Code
- Step 1: Create a project name.
First open Pycharm IDE and then create a “project name” after creating a project name click the “create” button.
- Step 2: Create a python file.
Second after creating a project name, “right click” your project name and then click “new” after that click the “python file“.
- Step 3: Name your python file.
Third after creating a python file, Name your python file after that click “enter“.
- Step 4: The Actual Code.
You are free to copy the code given below and download the full source code below.
The Code Given Below Is For The Class Matris
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 |
class Matris(object): def __init__(self): self.surface = screen.subsurface(Rect((MATRIS_OFFSET+BORDERWIDTH, MATRIS_OFFSET+BORDERWIDTH), (MATRIX_WIDTH * BLOCKSIZE, (MATRIX_HEIGHT-2) * BLOCKSIZE))) self.matrix = dict() for y in range(MATRIX_HEIGHT): for x in range(MATRIX_WIDTH): self.matrix[(y,x)] = None """ `self.matrix` is the current state of the tetris board, that is, it records which squares are currently occupied. It does not include the falling tetromino. The information relating to the falling tetromino is managed by `self.set_tetrominoes` instead. When the falling tetromino "dies", it will be placed in `self.matrix`. """ self.next_tetromino = random.choice(list_of_tetrominoes) self.set_tetrominoes() self.tetromino_rotation = 0 self.downwards_timer = 0 self.base_downwards_speed = 0.4 # Move down every 400 ms self.movement_keys = {'left': 0, 'right': 0} self.movement_keys_speed = 0.05 self.movement_keys_timer = (-self.movement_keys_speed)*2 self.level = 1 self.score = 0 self.lines = 0 self.combo = 1 # Combo will increase when you clear lines with several tetrominos in a row self.paused = False self.highscore = load_score() self.played_highscorebeaten_sound = False self.levelup_sound = get_sound("levelup.wav") self.gameover_sound = get_sound("gameover.wav") self.linescleared_sound = get_sound("linecleared.wav") self.highscorebeaten_sound = get_sound("highscorebeaten.wav") def set_tetrominoes(self): self.current_tetromino = self.next_tetromino self.next_tetromino = random.choice(list_of_tetrominoes) self.surface_of_next_tetromino = self.construct_surface_of_next_tetromino() self.tetromino_position = (0,4) if len(self.current_tetromino.shape) == 2 else (0, 3) self.tetromino_rotation = 0 self.tetromino_block = self.block(self.current_tetromino.color) self.shadow_block = self.block(self.current_tetromino.color, shadow=True) def hard_drop(self): amount = 0 while self.request_movement('down'): amount += 1 self.score += 10*amount self.lock_tetromino() def update(self, timepassed): self.needs_redraw = False pressed = lambda key: event.type == pygame.KEYDOWN and event.key == key unpressed = lambda key: event.type == pygame.KEYUP and event.key == key events = pygame.event.get() for event in events: if pressed(pygame.K_p): self.surface.fill((0,0,0)) self.needs_redraw = True self.paused = not self.paused elif event.type == pygame.QUIT: self.gameover(full_exit=True) elif pressed(pygame.K_ESCAPE): self.gameover() if self.paused: return self.needs_redraw for event in events: if pressed(pygame.K_SPACE): self.hard_drop() elif pressed(pygame.K_UP) or pressed(pygame.K_w): self.request_rotation() elif pressed(pygame.K_LEFT) or pressed(pygame.K_a): self.request_movement('left') self.movement_keys['left'] = 1 elif pressed(pygame.K_RIGHT) or pressed(pygame.K_d): self.request_movement('right') self.movement_keys['right'] = 1 elif unpressed(pygame.K_LEFT) or unpressed(pygame.K_a): self.movement_keys['left'] = 0 self.movement_keys_timer = (-self.movement_keys_speed)*2 elif unpressed(pygame.K_RIGHT) or unpressed(pygame.K_d): self.movement_keys['right'] = 0 self.movement_keys_timer = (-self.movement_keys_speed)*2 self.downwards_speed = self.base_downwards_speed ** (1 + self.level/10.) self.downwards_timer += timepassed downwards_speed = self.downwards_speed*0.10 if any([pygame.key.get_pressed()[pygame.K_DOWN], pygame.key.get_pressed()[pygame.K_s]]) else self.downwards_speed if self.downwards_timer > downwards_speed: if not self.request_movement('down'): self.lock_tetromino() self.downwards_timer %= downwards_speed if any(self.movement_keys.values()): self.movement_keys_timer += timepassed if self.movement_keys_timer > self.movement_keys_speed: self.request_movement('right' if self.movement_keys['right'] else 'left') self.movement_keys_timer %= self.movement_keys_speed return self.needs_redraw def draw_surface(self): with_tetromino = self.blend(matrix=self.place_shadow()) for y in range(MATRIX_HEIGHT): for x in range(MATRIX_WIDTH): # I hide the 2 first rows by drawing them outside of the surface block_location = Rect(x*BLOCKSIZE, (y*BLOCKSIZE - 2*BLOCKSIZE), BLOCKSIZE, BLOCKSIZE) if with_tetromino[(y,x)] is None: self.surface.fill(BGCOLOR, block_location) else: if with_tetromino[(y,x)][0] == 'shadow': self.surface.fill(BGCOLOR, block_location) self.surface.blit(with_tetromino[(y,x)][1], block_location) def gameover(self, full_exit=False): """ Gameover occurs when a new tetromino does not fit after the old one has died, either after a "natural" drop or a hard drop by the player. That is why `self.lock_tetromino` is responsible for checking if it's game over. """ write_score(self.score) if full_exit: exit() else: raise GameOver("Sucker!") def place_shadow(self): posY, posX = self.tetromino_position while self.blend(position=(posY, posX)): posY += 1 position = (posY-1, posX) return self.blend(position=position, shadow=True) def fits_in_matrix(self, shape, position): posY, posX = position for x in range(posX, posX+len(shape)): for y in range(posY, posY+len(shape)): if self.matrix.get((y, x), False) is False and shape[y-posY][x-posX]: # outside matrix return False return position def request_rotation(self): rotation = (self.tetromino_rotation + 1) % 4 shape = self.rotated(rotation) y, x = self.tetromino_position position = (self.fits_in_matrix(shape, (y, x)) or self.fits_in_matrix(shape, (y, x+1)) or self.fits_in_matrix(shape, (y, x-1)) or self.fits_in_matrix(shape, (y, x+2)) or self.fits_in_matrix(shape, (y, x-2))) # ^ That's how wall-kick is implemented if position and self.blend(shape, position): self.tetromino_rotation = rotation self.tetromino_position = position self.needs_redraw = True return self.tetromino_rotation else: return False def request_movement(self, direction): posY, posX = self.tetromino_position if direction == 'left' and self.blend(position=(posY, posX-1)): self.tetromino_position = (posY, posX-1) self.needs_redraw = True return self.tetromino_position elif direction == 'right' and self.blend(position=(posY, posX+1)): self.tetromino_position = (posY, posX+1) self.needs_redraw = True return self.tetromino_position elif direction == 'up' and self.blend(position=(posY-1, posX)): self.needs_redraw = True self.tetromino_position = (posY-1, posX) return self.tetromino_position elif direction == 'down' and self.blend(position=(posY+1, posX)): self.needs_redraw = True self.tetromino_position = (posY+1, posX) return self.tetromino_position else: return False def rotated(self, rotation=None): if rotation is None: rotation = self.tetromino_rotation return rotate(self.current_tetromino.shape, rotation) def block(self, color, shadow=False): colors = {'blue': (105, 105, 255), 'yellow': (225, 242, 41), 'pink': (242, 41, 195), 'green': (22, 181, 64), 'red': (204, 22, 22), 'orange': (245, 144, 12), 'cyan': (10, 255, 226)} if shadow: end = [90] # end is the alpha value else: end = [] # Adding this to the end will not change the array, thus no alpha value border = Surface((BLOCKSIZE, BLOCKSIZE), pygame.SRCALPHA, 32) border.fill(list(map(lambda c: c*0.5, colors[color])) + end) borderwidth = 2 box = Surface((BLOCKSIZE-borderwidth*2, BLOCKSIZE-borderwidth*2), pygame.SRCALPHA, 32) boxarr = pygame.PixelArray(box) for x in range(len(boxarr)): for y in range(len(boxarr)): boxarr[x][y] = tuple(list(map(lambda c: min(255, int(c*random.uniform(0.8, 1.2))), colors[color])) + end) del boxarr # deleting boxarr or else the box surface will be 'locked' or something like that and won't blit. border.blit(box, Rect(borderwidth, borderwidth, 0, 0)) return border def lock_tetromino(self): """ This method is called whenever the falling tetromino "dies". `self.matrix` is updated, the lines are counted and cleared, and a new tetromino is chosen. """ self.matrix = self.blend() lines_cleared = self.remove_lines() self.lines += lines_cleared if lines_cleared: if lines_cleared >= 4: self.linescleared_sound.play() self.score += 100 * (lines_cleared**2) * self.combo if not self.played_highscorebeaten_sound and self.score > self.highscore: if self.highscore != 0: self.highscorebeaten_sound.play() self.played_highscorebeaten_sound = True if self.lines >= self.level*10: self.levelup_sound.play() self.level += 1 self.combo = self.combo + 1 if lines_cleared else 1 self.set_tetrominoes() if not self.blend(): self.gameover_sound.play() self.gameover() self.needs_redraw = True def remove_lines(self): lines = [] for y in range(MATRIX_HEIGHT): line = (y, []) for x in range(MATRIX_WIDTH): if self.matrix[(y,x)]: line[1].append(x) if len(line[1]) == MATRIX_WIDTH: lines.append(y) for line in sorted(lines): for x in range(MATRIX_WIDTH): self.matrix[(line,x)] = None for y in range(0, line+1)[::-1]: for x in range(MATRIX_WIDTH): self.matrix[(y,x)] = self.matrix.get((y-1,x), None) return len(lines) def blend(self, shape=None, position=None, matrix=None, shadow=False): """ Does `shape` at `position` fit in `matrix`? If so, return a new copy of `matrix` where all the squares of `shape` have been placed in `matrix`. Otherwise, return False. This method is often used simply as a test, for example to see if an action by the player is valid. It is also used in `self.draw_surface` to paint the falling tetromino and its shadow on the screen. """ if shape is None: shape = self.rotated() if position is None: position = self.tetromino_position copy = dict(self.matrix if matrix is None else matrix) posY, posX = position for x in range(posX, posX+len(shape)): for y in range(posY, posY+len(shape)): if (copy.get((y, x), False) is False and shape[y-posY][x-posX] # shape is outside the matrix or # coordinate is occupied by something else which isn't a shadow copy.get((y,x)) and shape[y-posY][x-posX] and copy[(y,x)][0] != 'shadow'): return False # Blend failed; `shape` at `position` breaks the matrix elif shape[y-posY][x-posX]: copy[(y,x)] = ('shadow', self.shadow_block) if shadow else ('block', self.tetromino_block) return copy def construct_surface_of_next_tetromino(self): shape = self.next_tetromino.shape surf = Surface((len(shape)*BLOCKSIZE, len(shape)*BLOCKSIZE), pygame.SRCALPHA, 32) for y in range(len(shape)): for x in range(len(shape)): if shape[y][x]: surf.blit(self.block(self.next_tetromino.color), (x*BLOCKSIZE, y*BLOCKSIZE)) return surf |
In this class which is declare the following module:
- set_tetrominoes – In this module which is declaring the position of the tetromino in its color ,position and shape
- hard_drop – In this module which is you can move the tetromino quick down in the surface.
- update – In this module which you can change the position of the tetromino either up, down, left and right.
- draw_surface – In this module which is the position of the tetromino in the surface.
- gameover – In this module which is the finish or the game over and write a score.
- place_shadow – In this module which display the shadow of tetromino in the surface that the player can exact put the tetromino perfectly.
- fits_in_matrix – In this module which is declaring the shape and position in matrix.
- request_rotation – In this module which declaring the position to be rotate.
- request_movement – In this module which is declaring the condition of the movement.
- rotated – In this module which is declaring the rotation conditions.
- block – In this module which is declaring the color of block and its sizes.
- lock_tetromino – In this module which is whenever the falling tetromino is updated, the lines are counted and cleared.
- remove_lines – In this Module which is remoding the lines.
- construct_surface_of_next_tetrominos – In this module which you can change or construct the surface.
The Code Given Below Is For The Class Game
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
class Game(object): def main(self, screen): clock = pygame.time.Clock() self.matris = Matris() screen.blit(construct_nightmare(screen.get_size()), (0,0)) matris_border = Surface((MATRIX_WIDTH*BLOCKSIZE+BORDERWIDTH*2, VISIBLE_MATRIX_HEIGHT*BLOCKSIZE+BORDERWIDTH*2)) matris_border.fill(BORDERCOLOR) screen.blit(matris_border, (MATRIS_OFFSET,MATRIS_OFFSET)) self.redraw() while True: try: timepassed = clock.tick(50) if self.matris.update((timepassed / 1000.) if not self.matris.paused else 0): self.redraw() except GameOver: return def redraw(self): if not self.matris.paused: self.blit_next_tetromino(self.matris.surface_of_next_tetromino) self.blit_info() self.matris.draw_surface() pygame.display.flip() def blit_info(self): textcolor = (255, 255, 255) font = pygame.font.Font(None, 30) width = (WIDTH-(MATRIS_OFFSET+BLOCKSIZE*MATRIX_WIDTH+BORDERWIDTH*2)) - MATRIS_OFFSET*2 def renderpair(text, val): text = font.render(text, True, textcolor) val = font.render(str(val), True, textcolor) surf = Surface((width, text.get_rect().height + BORDERWIDTH*2), pygame.SRCALPHA, 32) surf.blit(text, text.get_rect(top=BORDERWIDTH+10, left=BORDERWIDTH+10)) surf.blit(val, val.get_rect(top=BORDERWIDTH+10, right=width-(BORDERWIDTH+10))) return surf scoresurf = renderpair("Score", self.matris.score) levelsurf = renderpair("Level", self.matris.level) linessurf = renderpair("Lines", self.matris.lines) combosurf = renderpair("Combo", "x{}".format(self.matris.combo)) height = 20 + (levelsurf.get_rect().height + scoresurf.get_rect().height + linessurf.get_rect().height + combosurf.get_rect().height ) area = Surface((width, height)) area.fill(BORDERCOLOR) area.fill(BGCOLOR, Rect(BORDERWIDTH, BORDERWIDTH, width-BORDERWIDTH*2, height-BORDERWIDTH*2)) area.blit(levelsurf, (0,0)) area.blit(scoresurf, (0, levelsurf.get_rect().height)) area.blit(linessurf, (0, levelsurf.get_rect().height + scoresurf.get_rect().height)) area.blit(combosurf, (0, levelsurf.get_rect().height + scoresurf.get_rect().height + linessurf.get_rect().height)) screen.blit(area, area.get_rect(bottom=HEIGHT-MATRIS_OFFSET, centerx=TRICKY_CENTERX)) def blit_next_tetromino(self, tetromino_surf): area = Surface((BLOCKSIZE*5, BLOCKSIZE*5)) area.fill(BORDERCOLOR) area.fill(BGCOLOR, Rect(BORDERWIDTH, BORDERWIDTH, BLOCKSIZE*5-BORDERWIDTH*2, BLOCKSIZE*5-BORDERWIDTH*2)) areasize = area.get_size()[0] tetromino_surf_size = tetromino_surf.get_size()[0] # ^^ I'm assuming width and height are the same center = areasize/2 - tetromino_surf_size/2 area.blit(tetromino_surf, (center, center)) screen.blit(area, area.get_rect(top=MATRIS_OFFSET, centerx=TRICKY_CENTERX)) |
In this class which is declare the following module:
- main – The main module of the class Game
- redraw – In this module which is the draw surface
- blit_info – In this module which is declaring the text color, font and width
- renderpair – In this module which is displayed the score, level ,lines and combo of the game in changing process of time.
- blit_next_tetromino – In this module which is declaring the size of the surface
The Code Given Below Is For The Class Menu
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
class Menu(object): running = True def main(self, screen): clock = pygame.time.Clock() menu = kezmenu.KezMenu( ['Play!', lambda: Game().main(screen)], ['Quit', lambda: setattr(self, 'running', False)], ) menu.position = (50, 50) menu.enableEffect('enlarge-font-on-focus', font=None, size=60, enlarge_factor=1.2, enlarge_time=0.3) menu.color = (255,255,255) menu.focus_color = (40, 200, 40) nightmare = construct_nightmare(screen.get_size()) highscoresurf = self.construct_highscoresurf() timepassed = clock.tick(30) / 1000. while self.running: events = pygame.event.get() for event in events: if event.type == pygame.QUIT: exit() menu.update(events, timepassed) timepassed = clock.tick(30) / 1000. if timepassed > 1: # A game has most likely been played highscoresurf = self.construct_highscoresurf() screen.blit(nightmare, (0,0)) screen.blit(highscoresurf, highscoresurf.get_rect(right=WIDTH-50, bottom=HEIGHT-50)) menu.draw(screen) pygame.display.flip() def construct_highscoresurf(self): font = pygame.font.Font(None, 50) highscore = load_score() text = "Highscore: {}".format(highscore) return font.render(text, True, (255,255,255)) def construct_nightmare(size): surf = Surface(size) boxsize = 8 bordersize = 1 vals = '1235' # only the lower values, for darker colors and greater fear arr = pygame.PixelArray(surf) for x in range(0, len(arr), boxsize): for y in range(0, len(arr[x]), boxsize): color = int(''.join([random.choice(vals) + random.choice(vals) for _ in range(3)]), 16) for LX in range(x, x+(boxsize - bordersize)): for LY in range(y, y+(boxsize - bordersize)): if LX < len(arr) and LY < len(arr[x]): arr[LX][LY] = color del arr return surf |
In this class which is declare the following module:
- main – The main module of the class menu that you see in the first page when you run the game.
- construct_highscoresurf – In this module which is declaring the font design and highscore of the game.
- construct_nightmare – In this module which is declaring the size of the surface and its conditions.
The Code Given Below Is For The Class Game Over
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class GameOver(Exception): """Exception used for its control flow properties""" def get_sound(filename): return pygame.mixer.Sound(os.path.join(os.path.dirname(__file__), "resources", filename)) BGCOLOR = (15, 15, 20) BORDERCOLOR = (140, 140, 140) BLOCKSIZE = 30 BORDERWIDTH = 10 MATRIS_OFFSET = 20 MATRIX_WIDTH = 10 MATRIX_HEIGHT = 22 LEFT_MARGIN = 340 WIDTH = MATRIX_WIDTH*BLOCKSIZE + BORDERWIDTH*2 + MATRIS_OFFSET*2 + LEFT_MARGIN HEIGHT = (MATRIX_HEIGHT-2)*BLOCKSIZE + BORDERWIDTH*2 + MATRIS_OFFSET*2 TRICKY_CENTERX = WIDTH-(WIDTH-(MATRIS_OFFSET+BLOCKSIZE*MATRIX_WIDTH+BORDERWIDTH*2))/2 VISIBLE_MATRIX_HEIGHT = MATRIX_HEIGHT - 2 |
In this class which is declare the following module:
- get_sound – This module which is getting the sound when you are already game over.
Complete Source Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 |
#!/usr/bin/env python import pygame from pygame import Rect, Surface import random import os import kezmenu from tetrominoes import list_of_tetrominoes from tetrominoes import rotate from scores import load_score, write_score class GameOver(Exception): """Exception used for its control flow properties""" def get_sound(filename): return pygame.mixer.Sound(os.path.join(os.path.dirname(__file__), "resources", filename)) BGCOLOR = (15, 15, 20) BORDERCOLOR = (140, 140, 140) BLOCKSIZE = 30 BORDERWIDTH = 10 MATRIS_OFFSET = 20 MATRIX_WIDTH = 10 MATRIX_HEIGHT = 22 LEFT_MARGIN = 340 WIDTH = MATRIX_WIDTH*BLOCKSIZE + BORDERWIDTH*2 + MATRIS_OFFSET*2 + LEFT_MARGIN HEIGHT = (MATRIX_HEIGHT-2)*BLOCKSIZE + BORDERWIDTH*2 + MATRIS_OFFSET*2 TRICKY_CENTERX = WIDTH-(WIDTH-(MATRIS_OFFSET+BLOCKSIZE*MATRIX_WIDTH+BORDERWIDTH*2))/2 VISIBLE_MATRIX_HEIGHT = MATRIX_HEIGHT - 2 class Matris(object): def __init__(self): self.surface = screen.subsurface(Rect((MATRIS_OFFSET+BORDERWIDTH, MATRIS_OFFSET+BORDERWIDTH), (MATRIX_WIDTH * BLOCKSIZE, (MATRIX_HEIGHT-2) * BLOCKSIZE))) self.matrix = dict() for y in range(MATRIX_HEIGHT): for x in range(MATRIX_WIDTH): self.matrix[(y,x)] = None """ `self.matrix` is the current state of the tetris board, that is, it records which squares are currently occupied. It does not include the falling tetromino. The information relating to the falling tetromino is managed by `self.set_tetrominoes` instead. When the falling tetromino "dies", it will be placed in `self.matrix`. """ self.next_tetromino = random.choice(list_of_tetrominoes) self.set_tetrominoes() self.tetromino_rotation = 0 self.downwards_timer = 0 self.base_downwards_speed = 0.4 # Move down every 400 ms self.movement_keys = {'left': 0, 'right': 0} self.movement_keys_speed = 0.05 self.movement_keys_timer = (-self.movement_keys_speed)*2 self.level = 1 self.score = 0 self.lines = 0 self.combo = 1 # Combo will increase when you clear lines with several tetrominos in a row self.paused = False self.highscore = load_score() self.played_highscorebeaten_sound = False self.levelup_sound = get_sound("levelup.wav") self.gameover_sound = get_sound("gameover.wav") self.linescleared_sound = get_sound("linecleared.wav") self.highscorebeaten_sound = get_sound("highscorebeaten.wav") def set_tetrominoes(self): self.current_tetromino = self.next_tetromino self.next_tetromino = random.choice(list_of_tetrominoes) self.surface_of_next_tetromino = self.construct_surface_of_next_tetromino() self.tetromino_position = (0,4) if len(self.current_tetromino.shape) == 2 else (0, 3) self.tetromino_rotation = 0 self.tetromino_block = self.block(self.current_tetromino.color) self.shadow_block = self.block(self.current_tetromino.color, shadow=True) def hard_drop(self): amount = 0 while self.request_movement('down'): amount += 1 self.score += 10*amount self.lock_tetromino() def update(self, timepassed): self.needs_redraw = False pressed = lambda key: event.type == pygame.KEYDOWN and event.key == key unpressed = lambda key: event.type == pygame.KEYUP and event.key == key events = pygame.event.get() for event in events: if pressed(pygame.K_p): self.surface.fill((0,0,0)) self.needs_redraw = True self.paused = not self.paused elif event.type == pygame.QUIT: self.gameover(full_exit=True) elif pressed(pygame.K_ESCAPE): self.gameover() if self.paused: return self.needs_redraw for event in events: if pressed(pygame.K_SPACE): self.hard_drop() elif pressed(pygame.K_UP) or pressed(pygame.K_w): self.request_rotation() elif pressed(pygame.K_LEFT) or pressed(pygame.K_a): self.request_movement('left') self.movement_keys['left'] = 1 elif pressed(pygame.K_RIGHT) or pressed(pygame.K_d): self.request_movement('right') self.movement_keys['right'] = 1 elif unpressed(pygame.K_LEFT) or unpressed(pygame.K_a): self.movement_keys['left'] = 0 self.movement_keys_timer = (-self.movement_keys_speed)*2 elif unpressed(pygame.K_RIGHT) or unpressed(pygame.K_d): self.movement_keys['right'] = 0 self.movement_keys_timer = (-self.movement_keys_speed)*2 self.downwards_speed = self.base_downwards_speed ** (1 + self.level/10.) self.downwards_timer += timepassed downwards_speed = self.downwards_speed*0.10 if any([pygame.key.get_pressed()[pygame.K_DOWN], pygame.key.get_pressed()[pygame.K_s]]) else self.downwards_speed if self.downwards_timer > downwards_speed: if not self.request_movement('down'): self.lock_tetromino() self.downwards_timer %= downwards_speed if any(self.movement_keys.values()): self.movement_keys_timer += timepassed if self.movement_keys_timer > self.movement_keys_speed: self.request_movement('right' if self.movement_keys['right'] else 'left') self.movement_keys_timer %= self.movement_keys_speed return self.needs_redraw def draw_surface(self): with_tetromino = self.blend(matrix=self.place_shadow()) for y in range(MATRIX_HEIGHT): for x in range(MATRIX_WIDTH): # I hide the 2 first rows by drawing them outside of the surface block_location = Rect(x*BLOCKSIZE, (y*BLOCKSIZE - 2*BLOCKSIZE), BLOCKSIZE, BLOCKSIZE) if with_tetromino[(y,x)] is None: self.surface.fill(BGCOLOR, block_location) else: if with_tetromino[(y,x)][0] == 'shadow': self.surface.fill(BGCOLOR, block_location) self.surface.blit(with_tetromino[(y,x)][1], block_location) def gameover(self, full_exit=False): """ Gameover occurs when a new tetromino does not fit after the old one has died, either after a "natural" drop or a hard drop by the player. That is why `self.lock_tetromino` is responsible for checking if it's game over. """ write_score(self.score) if full_exit: exit() else: raise GameOver("Sucker!") def place_shadow(self): posY, posX = self.tetromino_position while self.blend(position=(posY, posX)): posY += 1 position = (posY-1, posX) return self.blend(position=position, shadow=True) def fits_in_matrix(self, shape, position): posY, posX = position for x in range(posX, posX+len(shape)): for y in range(posY, posY+len(shape)): if self.matrix.get((y, x), False) is False and shape[y-posY][x-posX]: # outside matrix return False return position def request_rotation(self): rotation = (self.tetromino_rotation + 1) % 4 shape = self.rotated(rotation) y, x = self.tetromino_position position = (self.fits_in_matrix(shape, (y, x)) or self.fits_in_matrix(shape, (y, x+1)) or self.fits_in_matrix(shape, (y, x-1)) or self.fits_in_matrix(shape, (y, x+2)) or self.fits_in_matrix(shape, (y, x-2))) # ^ That's how wall-kick is implemented if position and self.blend(shape, position): self.tetromino_rotation = rotation self.tetromino_position = position self.needs_redraw = True return self.tetromino_rotation else: return False def request_movement(self, direction): posY, posX = self.tetromino_position if direction == 'left' and self.blend(position=(posY, posX-1)): self.tetromino_position = (posY, posX-1) self.needs_redraw = True return self.tetromino_position elif direction == 'right' and self.blend(position=(posY, posX+1)): self.tetromino_position = (posY, posX+1) self.needs_redraw = True return self.tetromino_position elif direction == 'up' and self.blend(position=(posY-1, posX)): self.needs_redraw = True self.tetromino_position = (posY-1, posX) return self.tetromino_position elif direction == 'down' and self.blend(position=(posY+1, posX)): self.needs_redraw = True self.tetromino_position = (posY+1, posX) return self.tetromino_position else: return False def rotated(self, rotation=None): if rotation is None: rotation = self.tetromino_rotation return rotate(self.current_tetromino.shape, rotation) def block(self, color, shadow=False): colors = {'blue': (105, 105, 255), 'yellow': (225, 242, 41), 'pink': (242, 41, 195), 'green': (22, 181, 64), 'red': (204, 22, 22), 'orange': (245, 144, 12), 'cyan': (10, 255, 226)} if shadow: end = [90] # end is the alpha value else: end = [] # Adding this to the end will not change the array, thus no alpha value border = Surface((BLOCKSIZE, BLOCKSIZE), pygame.SRCALPHA, 32) border.fill(list(map(lambda c: c*0.5, colors[color])) + end) borderwidth = 2 box = Surface((BLOCKSIZE-borderwidth*2, BLOCKSIZE-borderwidth*2), pygame.SRCALPHA, 32) boxarr = pygame.PixelArray(box) for x in range(len(boxarr)): for y in range(len(boxarr)): boxarr[x][y] = tuple(list(map(lambda c: min(255, int(c*random.uniform(0.8, 1.2))), colors[color])) + end) del boxarr # deleting boxarr or else the box surface will be 'locked' or something like that and won't blit. border.blit(box, Rect(borderwidth, borderwidth, 0, 0)) return border def lock_tetromino(self): """ This method is called whenever the falling tetromino "dies". `self.matrix` is updated, the lines are counted and cleared, and a new tetromino is chosen. """ self.matrix = self.blend() lines_cleared = self.remove_lines() self.lines += lines_cleared if lines_cleared: if lines_cleared >= 4: self.linescleared_sound.play() self.score += 100 * (lines_cleared**2) * self.combo if not self.played_highscorebeaten_sound and self.score > self.highscore: if self.highscore != 0: self.highscorebeaten_sound.play() self.played_highscorebeaten_sound = True if self.lines >= self.level*10: self.levelup_sound.play() self.level += 1 self.combo = self.combo + 1 if lines_cleared else 1 self.set_tetrominoes() if not self.blend(): self.gameover_sound.play() self.gameover() self.needs_redraw = True def remove_lines(self): lines = [] for y in range(MATRIX_HEIGHT): line = (y, []) for x in range(MATRIX_WIDTH): if self.matrix[(y,x)]: line[1].append(x) if len(line[1]) == MATRIX_WIDTH: lines.append(y) for line in sorted(lines): for x in range(MATRIX_WIDTH): self.matrix[(line,x)] = None for y in range(0, line+1)[::-1]: for x in range(MATRIX_WIDTH): self.matrix[(y,x)] = self.matrix.get((y-1,x), None) return len(lines) def blend(self, shape=None, position=None, matrix=None, shadow=False): """ Does `shape` at `position` fit in `matrix`? If so, return a new copy of `matrix` where all the squares of `shape` have been placed in `matrix`. Otherwise, return False. This method is often used simply as a test, for example to see if an action by the player is valid. It is also used in `self.draw_surface` to paint the falling tetromino and its shadow on the screen. """ if shape is None: shape = self.rotated() if position is None: position = self.tetromino_position copy = dict(self.matrix if matrix is None else matrix) posY, posX = position for x in range(posX, posX+len(shape)): for y in range(posY, posY+len(shape)): if (copy.get((y, x), False) is False and shape[y-posY][x-posX] # shape is outside the matrix or # coordinate is occupied by something else which isn't a shadow copy.get((y,x)) and shape[y-posY][x-posX] and copy[(y,x)][0] != 'shadow'): return False # Blend failed; `shape` at `position` breaks the matrix elif shape[y-posY][x-posX]: copy[(y,x)] = ('shadow', self.shadow_block) if shadow else ('block', self.tetromino_block) return copy def construct_surface_of_next_tetromino(self): shape = self.next_tetromino.shape surf = Surface((len(shape)*BLOCKSIZE, len(shape)*BLOCKSIZE), pygame.SRCALPHA, 32) for y in range(len(shape)): for x in range(len(shape)): if shape[y][x]: surf.blit(self.block(self.next_tetromino.color), (x*BLOCKSIZE, y*BLOCKSIZE)) return surf class Game(object): def main(self, screen): clock = pygame.time.Clock() self.matris = Matris() screen.blit(construct_nightmare(screen.get_size()), (0,0)) matris_border = Surface((MATRIX_WIDTH*BLOCKSIZE+BORDERWIDTH*2, VISIBLE_MATRIX_HEIGHT*BLOCKSIZE+BORDERWIDTH*2)) matris_border.fill(BORDERCOLOR) screen.blit(matris_border, (MATRIS_OFFSET,MATRIS_OFFSET)) self.redraw() while True: try: timepassed = clock.tick(50) if self.matris.update((timepassed / 1000.) if not self.matris.paused else 0): self.redraw() except GameOver: return def redraw(self): if not self.matris.paused: self.blit_next_tetromino(self.matris.surface_of_next_tetromino) self.blit_info() self.matris.draw_surface() pygame.display.flip() def blit_info(self): textcolor = (255, 255, 255) font = pygame.font.Font(None, 30) width = (WIDTH-(MATRIS_OFFSET+BLOCKSIZE*MATRIX_WIDTH+BORDERWIDTH*2)) - MATRIS_OFFSET*2 def renderpair(text, val): text = font.render(text, True, textcolor) val = font.render(str(val), True, textcolor) surf = Surface((width, text.get_rect().height + BORDERWIDTH*2), pygame.SRCALPHA, 32) surf.blit(text, text.get_rect(top=BORDERWIDTH+10, left=BORDERWIDTH+10)) surf.blit(val, val.get_rect(top=BORDERWIDTH+10, right=width-(BORDERWIDTH+10))) return surf scoresurf = renderpair("Score", self.matris.score) levelsurf = renderpair("Level", self.matris.level) linessurf = renderpair("Lines", self.matris.lines) combosurf = renderpair("Combo", "x{}".format(self.matris.combo)) height = 20 + (levelsurf.get_rect().height + scoresurf.get_rect().height + linessurf.get_rect().height + combosurf.get_rect().height ) area = Surface((width, height)) area.fill(BORDERCOLOR) area.fill(BGCOLOR, Rect(BORDERWIDTH, BORDERWIDTH, width-BORDERWIDTH*2, height-BORDERWIDTH*2)) area.blit(levelsurf, (0,0)) area.blit(scoresurf, (0, levelsurf.get_rect().height)) area.blit(linessurf, (0, levelsurf.get_rect().height + scoresurf.get_rect().height)) area.blit(combosurf, (0, levelsurf.get_rect().height + scoresurf.get_rect().height + linessurf.get_rect().height)) screen.blit(area, area.get_rect(bottom=HEIGHT-MATRIS_OFFSET, centerx=TRICKY_CENTERX)) def blit_next_tetromino(self, tetromino_surf): area = Surface((BLOCKSIZE*5, BLOCKSIZE*5)) area.fill(BORDERCOLOR) area.fill(BGCOLOR, Rect(BORDERWIDTH, BORDERWIDTH, BLOCKSIZE*5-BORDERWIDTH*2, BLOCKSIZE*5-BORDERWIDTH*2)) areasize = area.get_size()[0] tetromino_surf_size = tetromino_surf.get_size()[0] # ^^ I'm assuming width and height are the same center = areasize/2 - tetromino_surf_size/2 area.blit(tetromino_surf, (center, center)) screen.blit(area, area.get_rect(top=MATRIS_OFFSET, centerx=TRICKY_CENTERX)) class Menu(object): running = True def main(self, screen): clock = pygame.time.Clock() menu = kezmenu.KezMenu( ['Play!', lambda: Game().main(screen)], ['Quit', lambda: setattr(self, 'running', False)], ) menu.position = (50, 50) menu.enableEffect('enlarge-font-on-focus', font=None, size=60, enlarge_factor=1.2, enlarge_time=0.3) menu.color = (255,255,255) menu.focus_color = (40, 200, 40) nightmare = construct_nightmare(screen.get_size()) highscoresurf = self.construct_highscoresurf() timepassed = clock.tick(30) / 1000. while self.running: events = pygame.event.get() for event in events: if event.type == pygame.QUIT: exit() menu.update(events, timepassed) timepassed = clock.tick(30) / 1000. if timepassed > 1: # A game has most likely been played highscoresurf = self.construct_highscoresurf() screen.blit(nightmare, (0,0)) screen.blit(highscoresurf, highscoresurf.get_rect(right=WIDTH-50, bottom=HEIGHT-50)) menu.draw(screen) pygame.display.flip() def construct_highscoresurf(self): font = pygame.font.Font(None, 50) highscore = load_score() text = "Highscore: {}".format(highscore) return font.render(text, True, (255,255,255)) def construct_nightmare(size): surf = Surface(size) boxsize = 8 bordersize = 1 vals = '1235' # only the lower values, for darker colors and greater fear arr = pygame.PixelArray(surf) for x in range(0, len(arr), boxsize): for y in range(0, len(arr[x]), boxsize): color = int(''.join([random.choice(vals) + random.choice(vals) for _ in range(3)]), 16) for LX in range(x, x+(boxsize - bordersize)): for LY in range(y, y+(boxsize - bordersize)): if LX < len(arr) and LY < len(arr[x]): arr[LX][LY] = color del arr return surf if __name__ == '__main__': pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("MaTris") Menu().main(screen) |
Tetris Game In Python : Project Information
Project Name: | Tetris Game In Python |
Language/s Used: | Python (GUI) Based |
Python version (Recommended): | 2.x or 3.x |
Database: | None |
Type: | Python App |
Developer: | IT SOURCECODE |
Updates: | 0 |
Run Quick Virus Scan for secure Download
Run Quick Scan for secure DownloadDownloadable Source Code
I have here the list of Best Python Project with Source code free to download for free, I hope this can help you a lot.
Summary
The Tetris In Python Code is written in python programming language, Python is very smooth to research the syntax emphasizes readability and it is able to reduces time ingesting in developing.Also in this tutorial is the simplest way for the beginners or the student to enhance their logical skills in programming. and also in this game project is the way for the students or beginners in designing and developing games.
Related Articles
- Aircraft War Game in Python with Source Code
- Mario Game In Python With Source Code
- Hangman Game In Python With Source Code
- Aircraft War Game in Python with Source Code
- Snake Game In Python Code
- How to Make Bouncing Ball Game in Python with Source Code
- How to Create Rock-Paper-Scissor Game in Python
Inquiries
If you have any questions or suggestions about Tetris In Python Code , please feel free to leave a comment below.