def test_is_tetromino_colliding(self): gb = gameboard.Gameboard() self.assertEqual(gb.is_tetromino_colliding(), False) # Test for borders gb.falling_tetromino = tetromino.Tetromino("I", times_rotated=1, x=0) # for "I" shape, the most left block will overlaping with gameboard left border self.assertEqual(gb.is_tetromino_colliding(), True) gb.falling_tetromino = tetromino.Tetromino("I", times_rotated=1, x=config.BOARD_COLUMNS-4) self.assertEqual(gb.is_tetromino_colliding(), True) # for bottom row (border) gb.falling_tetromino = tetromino.Tetromino("Z", x=4, y=config.BOARD_ROWS-3) self.assertEqual(gb.is_tetromino_colliding(), True) # Test for some FALLEN BLOCKS gb.falling_tetromino = tetromino.Tetromino("Z", x=8, y=4) gb.fields[8][3] = config.FALLEN_BLOCK gb.fields[8][4] = config.FALLEN_BLOCK gb.fields[8][5] = config.FALLEN_BLOCK gb.fields[7][3] = config.FALLEN_BLOCK self.assertEqual(gb.is_tetromino_colliding(), True) # Check for changing single block from FALLEN to EMPTY (block witch causing collision) gb = gameboard.Gameboard() gb.falling_tetromino = tetromino.Tetromino("O", x=0, y=0) gb.fields[1][2] = config.FALLEN_BLOCK self.assertEqual(gb.is_tetromino_colliding(), True) gb.fields[1][2] = config.EMPTY_BLOCK self.assertEqual(gb.is_tetromino_colliding(), False)
def __init__(self, size_y, size_x): self.size_y = size_y self.size_x = size_x self.board = [[0 for x in range(size_x)] for y in range(size_y)] self.past_board = self.get_board_copy(self.board) self.color_board = self.get_board_copy(self.board) self.active_tetromino = tet.Tetromino(0) self.next_tetromino = tet.Tetromino(0)
def test_rotate_Z(self): t = tetromino.Tetromino('Z') t.rotate() expected = [[0, 0, 1], [0, 1, 1], [0, 1, 0]] self.assertEqual(t.cells, expected) expected = [[0, 0, 0], [1, 1, 0], [0, 1, 1]] t.rotate() self.assertEqual(t.cells, expected) expected = [[0, 1, 0], [1, 1, 0], [1, 0, 0]] t.rotate() self.assertEqual(t.cells, expected) t.rotate() p = tetromino.Tetromino('Z') self.assertEqual(t.cells, p.cells)
def update_window(cls, win): win.fill((0, 0, 0)) cls.run_board(win) current = cls.q.current() cls.preview(current, win, active_tetro=True) cls.preview(current.ghost, win, active_tetro=True) for m, n in enumerate(range(1, 4)): cls.preview(tm.Tetromino(cls.s.peek(n=n)[m]), win, cls.WIDTH - cls.PrevXPadd, cls.PrevYPadd * n * (0.3 * n)) if len(cls.holding_bag) != 0: cls.preview(cls.holding_bag.current(), win, cls.WIDTH - cls.PrevXPadd, cls.HEIGHT - 200) else: cls.rect(win, cls.DGRAY, cls.WIDTH - cls.PrevXPadd, cls.HEIGHT - 200) score_text = Game.main_font.render("Score = {}".format(Game.score), 1, Game.WHITE) win.blit(score_text, ((Game.BoardWidth * Game.zoom), score_text.get_height())) pg.display.update()
def Update(): if game_board.active_tetromino.id == 0: if not game_board.can_spawn(): global exit exit = True else: global score score += game_board.is_a_row() if game_board.next_tetromino.id == 0: game_board.next_tetromino = tet.Tetromino(randint(1, 7)) game_board.active_tetromino = game_board.next_tetromino game_board.next_tetromino = tet.Tetromino(randint(1, 7)) # game_board.active_tetromino.position = (1, game_board.size_x // 2 - game_board.active_tetromino.figure_stats['x'] // 2) game_board.active_tetromino.position = (1, 6) game_board.save_board() if not exit: debug.clear() game_board.load_board() game_board.combine_at_position(game_board.active_tetromino.position) game_board.set_color_board(game_board.active_tetromino.id) game_board.c_print() print("NEXT:") game_board.next_tetromino.c_print() print() global score print("SCORE: " + str(score)) # print("\nFRAME: " + str(frame) + " DRAWING") if game_board.collision_detected(): game_board.active_tetromino = tet.Tetromino(0) score += 10 else: game_board.set_color_board(-1) new_position = get_input.input_manager() if new_position[0] == 'R': if game_board.can_rotate(): game_board.active_tetromino.rotate(new_position) else: game_board.active_tetromino.get_new_position(new_position, game_board.size_y, game_board.size_x, game_board.is_propper_move(new_position)) # print("\nFRAME: " + str(frame) + " CALCULATION") global frame if frame == 60: frame = 0 else: frame += 1 debug.sleep(0.4)
def test_generate_new_tetromino(self): # Every time the Tetromino itself is diffrent this method should return diffrent value gb = gameboard.Gameboard() # gb.generate_new_tetromino = unittest.mock.MagicMock(return_value=tetromino.Tetromino("I")) # TODO Check if every call gives properly placed tetromino for shape in config.TETROMINO_SHAPES: for rotate in range(0, 3): gb.generate_new_tetromino = unittest.mock.MagicMock(return_value=tetromino.Tetromino(shape, rotate)) self.assertEqual(type(gb.falling_tetromino), tetromino.Tetromino)
def Square(color): tetro = tetromino.Tetromino(color, "square", (" \n" " \n" " ## \n" " ## \n")) def func(direction): pass tetro.rotate = func return tetro
def generate_tetromino_seq(self): seq = [] id_list = [i for i in range(1, tetromino.unique_types + 1)] # randomly pull ids from the list and put it into the sequence while len(id_list) != 0: rand_idx = randint(0, len(id_list) - 1) id = id_list[rand_idx] id_list.pop(rand_idx) tmino = tetromino.Tetromino(id) tmino.x_pos = (tmino.max_x - tmino.min_x) // 2 tmino.y_pos = tmino.min_y seq.append(tmino) return seq
def test_rotate_I(self): t = tetromino.Tetromino('I') t.rotate() expected = [[0, 0, 7, 0], [0, 0, 7, 0], [0, 0, 7, 0], [0, 0, 7, 0]] self.assertEqual(t.cells, expected) expected = [[0, 0, 0, 0], [0, 0, 0, 0], [7, 7, 7, 7], [0, 0, 0, 0]] t.rotate() self.assertEqual(t.cells, expected) expected = [[0, 7, 0, 0], [0, 7, 0, 0], [0, 7, 0, 0], [0, 7, 0, 0]] t.rotate() self.assertEqual(t.cells, expected) expected = [[0, 0, 0, 0], [7, 7, 7, 7], [0, 0, 0, 0], [0, 0, 0, 0]] t.rotate() self.assertEqual(t.cells, expected)
def test_rotate_L(self): t = tetromino.Tetromino('L') expected = [[0, 5, 0], [0, 5, 0], [0, 5, 5]] t.rotate() self.assertEqual(t.cells, expected) expected = [[0, 0, 0], [5, 5, 5], [5, 0, 0]] t.rotate() self.assertEqual(t.cells, expected) expected = [[5, 5, 0], [0, 5, 0], [0, 5, 0]] t.rotate() self.assertEqual(t.cells, expected) expected = [[0, 0, 5], [5, 5, 5], [0, 0, 0]] t.rotate() self.assertEqual(t.cells, expected)
def generate_tetromino(board: gameboard.Gameboard, malice_level: int): most_unwanted_tetrominos = Evaluator.test_all_cases(board) # make list with tuples - first elem. of tuple is shape-rotate-x_shift str, second - score of this tetromino most_unwanted_tetrominos = sorted(most_unwanted_tetrominos.items(), key=lambda x: x[1], reverse=False) diffrent_malice_levels = 10 size_range = len(most_unwanted_tetrominos) // diffrent_malice_levels random_but_malice = malice_level * size_range - random.randint( 0, size_range) chosed_tetromino = most_unwanted_tetrominos[random_but_malice][0] # shape, rotate, x_shift = chosed_tetromino.split("-") # print(f"{shape}-{rotate}-{x_shift}") rotate = int(rotate) x_shift = int(x_shift) return tetromino.Tetromino(shape, times_rotated=rotate, x=4)
def game(): """Runs whole game""" pygame.init() screen = pre_configure_window() buffer = tetromino.Tetromino("I", times_rotated=0, x=3, y=0) actuall_gameboard = gameboard.Gameboard() time_steps_done_before_fall = 0 game_over = False # main gameloop while not game_over: actuall_gameboard.draw_gameboard( screen) # only gameboard are redrawing in all frame time.sleep( config.GAME_SINGLE_FRAME_SEC) # sleeps for every 50 miliseconds buffer.move(actuall_gameboard) # controlled from keyboard buffer.draw(screen) time_steps_done_before_fall += 1 if time_steps_done_before_fall == config.TIME_STEPS_TO_FALL_BUFFER: has_falled = buffer.fall_down(actuall_gameboard) if has_falled: actuall_gameboard.add_blocks(buffer) buffer = evaluator.Evaluator.generate_tetromino( actuall_gameboard, config.MALICIOUS_LEVEL) if buffer.fall_down( actuall_gameboard ): # while newly added tetromino instantly touching fallen blocks game_over = True print( f"Thank You for your play - waiting to see u next time!" ) actuall_gameboard.delete_lines() time_steps_done_before_fall = 0 pygame.display.update()
def test_all_cases(board: gameboard.Gameboard): most_unwanted_tetrominos = {} start_width = 1 rotates = 4 for shape in config.TETROMINO_SHAPES: if shape == "I": end_width = config.BOARD_COLUMNS - 2 else: end_width = config.BOARD_COLUMNS - 1 for rotate in range(rotates): for x_shift in range(start_width, end_width): testing_buffer = tetromino.Tetromino( shape, rotates, x_shift) score = Evaluator.calculate(board, testing_buffer) if score is False: continue most_unwanted_tetrominos[ f"{shape}-{rotate}-{x_shift}"] = score return most_unwanted_tetrominos
def Leftsnake(color): return tetromino.Tetromino(color, "leftsnake", (" \n" " \n" " ## \n" " ##\n"))
def _get_new_tetromino(self): pattern = random.choice(tetrominos.all_patterns) return tetromino.Tetromino(self.game, *pattern)
def Tee(color): return tetromino.Tetromino(color, "tee", (" \n" " \n" " # \n" " ###\n"))
import tetromino import world print("starting") grid = world.World(10,20) pattern = [[0, 1, 0], [1, 1, 1], [0, 0, 0]] piece = tetromino.Tetromino(grid,pattern) piece.print() piece.rotate_counter_clockwise() piece.print() piece.rotate_clockwise() piece.print() grid.draw_piece(piece) print("world") grid.print() for i in range(25): grid.clear_piece(piece) piece.advance() grid.draw_piece(piece) print("world")
def Leftgun(color): return tetromino.Tetromino(color, "leftgun", (" \n" " # \n" " # \n" " ## \n"))
def Stick(color): return tetromino.Tetromino(color, "stick", (" # \n" " # \n" " # \n" " # \n"))
def Rightsnake(color): return tetromino.Tetromino(color, "rightsnake", (" \n" " \n" " ## \n" "## \n"))
def main(): pygame.init() pygame.display.set_caption("Tetris") screen = pygame.display.set_mode(screen_res) pygame.key.set_repeat(100, 70) normal_blocks_path = os.path.join('sprites', 'blocks.png') assist_blocks_path = os.path.join('sprites', 'assist_blocks.png') game_background_path = os.path.join('sprites', 'background.png') menu_background_path = os.path.join('sprites', 'background.png') grid_background_path = os.path.join('sprites', 'grid_background.png') background = pygame.image.load(game_background_path).convert() background = pygame.transform.scale(background, screen.get_size()) font = pygame.font.Font(os.path.join('fonts', font_file), 38) def load_blocks(path): blocks_list = [] blocks = pygame.image.load(path).convert_alpha() blocks = pygame.transform.scale(blocks, (block_width * 7, block_height)) for i in range(7): block_surface = blocks.subsurface(i * block_width, 0, block_width, block_height) blocks_list.append(block_surface) return blocks_list normal_blocks = load_blocks(normal_blocks_path) assist_blocks = load_blocks(assist_blocks_path) next_surface = write(font, "NEXT", text_color) menu_items = ['START', 'QUIT'] main_menu = menu.Menu('TETRIS', menu_background_path, screen_res, font_file, menu_coord) for item in menu_items: main_menu.add_item(item) while True: randomizer.reset() display_menu = True while display_menu: main_menu.show(screen) pygame.display.flip() event = pygame.event.wait() user_input = main_menu.check_input(event) if user_input == menu_items[0]: display_menu = False elif user_input == menu_items[1] or event.type == pygame.QUIT: exit() grid = net.Net(columns, rows, (block_width, block_height), screen_res, grid_background_path) tetromino_move_time = initial_move_time current_tetromino = tetromino.Tetromino((block_width, block_height), grid.get_center_coord(), tetromino_move_time) next_tetromino = tetromino.Tetromino((block_width, block_height), next_tetromino_coord, tetromino_move_time) game_over = game_paused = drop_tetromino = False clock = pygame.time.Clock() total_time = 0.0 difficulty_level = 1 dt = 1.0 / FPS accumulator = 0.0 while not game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: game_over = True elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT: current_tetromino.move_right() if grid.is_out_of_bounds(current_tetromino.get_coords()) or \ grid.overlap(current_tetromino.get_coords()): current_tetromino.move_left() elif event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT: current_tetromino.move_left() if grid.is_out_of_bounds(current_tetromino.get_coords()) or \ grid.overlap(current_tetromino.get_coords()): current_tetromino.move_right() elif event.type == pygame.KEYDOWN and event.key == pygame.K_UP: current_tetromino.rotate_cw() if grid.is_out_of_bounds(current_tetromino.get_coords()) or \ grid.overlap(current_tetromino.get_coords()): current_tetromino.rotate_ccw() elif event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN: current_tetromino.rotate_ccw() if grid.is_out_of_bounds(current_tetromino.get_coords()) or \ grid.overlap(current_tetromino.get_coords()): current_tetromino.rotate_cw() elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: current_tetromino.speed_up() elif event.type == pygame.KEYUP and event.key == pygame.K_SPACE: current_tetromino.reset_speed() elif event.type == pygame.KEYDOWN and event.key == pygame.K_d: drop_tetromino = True elif event.type == pygame.KEYDOWN and event.key == pygame.K_p: pause = True grid.display_message(screen, font, text_color, 'PAUSE') while pause: event = pygame.event.wait() if event.type == pygame.KEYDOWN and event.key == pygame.K_p: pause = False elif event.type == pygame.QUIT: exit() game_paused = True if game_paused: frame_time = dt game_paused = False clock.tick(FPS) else: frame_time = clock.tick(FPS) / 1000.0 # convert to seconds accumulator += frame_time while accumulator >= dt and not game_over: while True: current_tetromino.move_down(dt) overlap = grid.overlap(current_tetromino.get_coords()) if not drop_tetromino or overlap: drop_tetromino = False break if overlap: current_tetromino.move_up() grid.update(current_tetromino.get_coords(), current_tetromino.get_color_index()) if grid.get_score() // 10 + 1 != difficulty_level: difficulty_level += 1 tetromino_move_time *= difficulty_modifier current_tetromino = next_tetromino current_tetromino.set_coords(grid.get_center_coord()) current_tetromino.set_speed(tetromino_move_time) next_tetromino = tetromino.Tetromino( (block_width, block_height), next_tetromino_coord, tetromino_move_time) game_over = grid.is_game_over() accumulator -= dt if display_time: total_time += frame_time time_string = "TIME " + '{0:02d}'.format(int(total_time // 60))\ + ":" + '{0:02d}'.format(int(total_time % 60)) time_surface = write(font, time_string, text_color) if display_fps: fps_string = "FPS: " + str(int(clock.get_fps())) fps_surface = write(font, fps_string, text_color) score_string = "SCORE: " + str(grid.get_score()) score_surface = write(font, score_string, text_color) level_string = "LEVEL: " + str(difficulty_level) level_surface = write(font, level_string, text_color) screen.blit(background, min_screen_coord) screen.blit(score_surface, score_coord) screen.blit(level_surface, level_coord) if display_time: screen.blit(time_surface, time_coord) if display_fps: screen.blit(fps_surface, fps_coord) screen.blit(next_surface, next_coord) grid.show(screen, normal_blocks) if not game_over: assist_coords = grid.get_assist_coords( current_tetromino.get_coords()) for coord in assist_coords: screen.blit( assist_blocks[current_tetromino.get_color_index()], coord) current_tetromino.show(screen, normal_blocks) next_tetromino.show(screen, normal_blocks) pygame.display.flip() grid.display_message(screen, font, text_color, 'GAME OVER') clock.tick(0.7)
def Rightgun(color): return tetromino.Tetromino(color, "rightgun", (" \n" " # \n" " # \n" " ## \n"))
def push_upcoming_tet(upcoming_tets, board, screen): r = randint(0, 6) upcoming_tets.append(tet.Tetromino(r, board, screen)) return r