def mainarena(self, win, direction, snake): global foodlist randpos = numpy.random.randint(low=1, high=29, size=2) * 10 if numpy.random.randint(low=0, high=100) < 5: newfood = Food(edge + randpos[0], edge + randpos[1]) newfood.draw(win) newfood.init = True foodlist.append(newfood) self.isGameStarted = True snake.draw(win, direction) for food, val in enumerate(foodlist): if (snake.xPos, snake.yPos) == (foodlist[food].xPos, foodlist[food].yPos): foodlist[food].Eaten = True snake.HasEaten = True del foodlist[food]
class Game: def __init__(self): pygame.init() self.setting = Setting() self.screen = pygame.display.set_mode( (self.setting.WIDTH, self.setting.HIGH), 0, 32) self.food = Food(self) self.snake = Snake(self) self.message = Message(self) self.map = Map(self) def update_draw(self): self.screen.fill(self.setting.BACKGROUND) #self.map.draw() self.snake.update() self.snake.draw() self.food.draw() pygame.display.update() def run(self): while True: self.message.Get_Key() self.update_draw() pygame.time.Clock().tick(self.setting.FPS)
clock = pygame.time.Clock() pygame.mixer.init() chomp = pygame.mixer.Sound("chomp.wav") score = 0 worm = Worm(screen) food = Food(screen) running = True while running: screen.fill((0, 0, 0)) worm.move() worm.draw() food.draw() if worm.crashed: running = False elif worm.x <= 0 or worm.x >= w - 1: running = False elif worm.y <= 0 or worm.y >= h - 1: running = False elif food.check(worm.x, worm.y): score += 1 worm.eat() chomp.play() print "Score: %d" % score
def gameLoop(): global dirn global k global highscore global namehighscore pyExit = False pyOver = False score = 0 world_num = 0 scorestr = "Score:0" # Initialize the game snake = Snake(200, 200, img) food = Food(int(width / 2), int(height / 2)) blocks = worlds(width, height, world_num) # Keeps track of the direction of the snake. dx, dy = 0, 0 lossreason = '' while not pyExit: while pyOver: image = pygame.image.load(python_path) game_display.blit(image, (0, 0)) message("Game Over! Press C to play Again, Q to Quit", (255, 0, 0), -20) message(lossreason, (255, 0, 0), 30) # display score on game over message("Your" + scorestr, (255, 0, 0), 80) if totalscore > highscore: # message("Highscore!!!",(255,0,0),120) # write new highscore highscorefile = open('highscore.txt', 'wt') highscorefile.write(str(totalscore) + "\n") # name window def namewrite(): highscorefile.write(v.get()) scorewindow.destroy() scorewindow = Tk() scorewindow.geometry('300x100') frame = Frame(scorewindow, width=100, height=100) frame.pack() scorewindow.title("congratulations") Label(frame, text='you\'ve made highscore!!!!').pack(side='top') v = StringVar() v.set("type your name") textbox = Entry(frame, textvariable=v) textbox.pack(side='top') okbutton = Button(frame, text="ok", fg="black", bg="white", command=namewrite) okbutton.pack(side='bottom') scorewindow.mainloop() highscorefile.close() # incase user wants to countinue after creating highscore # to read his new score highscorefile = open('highscore.txt', 'rt') highscore = highscorefile.readline() highscore = int(highscore) namehighscore = highscorefile.readline() highscorefile.close() else: message("Highscore by " + namehighscore + ":" + str(highscore), (255, 0, 0), 120) pygame.display.update() for event in pygame.event.get(): keyp = action() if keyp != None or event.type == pygame.KEYDOWN: try: if keyp == 'q' or event.key == pygame.K_q: pyExit = True pyOver = False except: blank = [] # bypass the exception try: if keyp == 'c' or event.key == pygame.K_c: gameLoop() except: blank = [] # bypass the exception """ Events """ #the conditions are modified to work with the buttons for event in pygame.event.get(): keyp = action() # blank is not used anywhere # it is just used to jump the exception if event.type == pygame.QUIT: pyExit = True if event.type == pygame.KEYDOWN or keyp != None: try: if keyp == 'lt' or event.key == pygame.K_LEFT: dirn = "left" dx = -1 dy = 0 except: blank = [] try: if keyp == 'rt' or event.key == pygame.K_RIGHT: dirn = "right" dx = 1 dy = 0 except: blank = [] try: if keyp == 'up' or event.key == pygame.K_UP: dirn = "up" dy = -1 dx = 0 except: blank = [] try: if keyp == 'dn' or event.key == pygame.K_DOWN: dirn = "down" dy = 1 dx = 0 except: blank = [] try: if keyp == 'p' or event.key == pygame.K_p: pause() except: blank = [] try: if keyp == 'q' or event.key == pygame.K_q: pygame.quit() quit(0) except: blank = [] # level changer value if score > 10: score = 0 world_num += 1 blocks = worlds(width, height, world_num) food.x, food.y = int(width / 2), int(height / 2) # Engage boost of pressing shift keyp = action() keyPresses = pygame.key.get_pressed() boost_speed = keyPresses[pygame.K_LSHIFT] or keyPresses[ pygame.K_RSHIFT] or keyp == 'st' # if boost_speed is true it will move 2 blocks in one gameloop # else it will just move one block iterations = [1] if boost_speed == 1: iterations.append(2) for i in iterations: """ Update snake """ snake.move(dx, dy, 10) snake.check_boundary(width, height) snake_rect = snake.get_rect() food_rect = food.get_rect() """ Snake-Snake collision """ if snake.ate_itself(): pyOver = True lossreason = 'Oooops You Hit YOURSELF' sound = pygame.mixer.Sound(point_path) sound.play() """ Snake-Block collision """ for block in blocks: block_rect = block.get_rect() if block_rect.colliderect(snake_rect): pyOver = True lossreason = 'Ooops You Hit a BLOCKER' sound = pygame.mixer.Sound(point_path) sound.play() """ Snake-Food collision """ # if snake collides with food, increase its length. if food_rect.colliderect(snake_rect): score += 1 snake.increment_length() sound = pygame.mixer.Sound(point_path) sound.play() # generate food at random x, y. food.generate_food(width, height) # try generating the food at a position where blocks are not present. while food_collides_block(food.get_rect(), blocks): food.generate_food(width - food.size, height - food.size) """ Draw """ game_display.fill((255, 255, 255)) showButton() # draw the food and snake. snake.draw(game_display, dirn, (0, 155, 0)) food.draw(game_display, (0, 255, 0)) # draw the blocks. for block in blocks: block.draw(game_display, (255, 0, 0)) # count and display score on screen totalscore = total(score, world_num) scorestr = 'Score: ' + str(totalscore) font = pygame.font.SysFont(None, 30) text = font.render(scorestr, True, (0, 0, 255)) game_display.blit(text, (0, 0, 20, 20)) pygame.display.update() clock.tick(FPS) pygame.quit() quit()
elif event.key == K_RIGHT or event.key == K_d: dir = Snake.RIGHT elif event.key == K_RETURN: if snake.isDead: # to restart the game snake.reset() food.reset() ############# snake.score = 0 snake.maxLength = 10 # update game if not snake.isDead: snake.update(currTime, dir) food.update(currTime) # redraw game screen.fill(WHITE) food.draw(screen) snake.draw(screen) scoreStr = font.render(str(snake.score), True, BLACK) screen.blit(scoreStr, (10, 0)) if snake.isDead: drawGameOver(screen) pygame.display.update() pygame.quit()
FONT.render_to(screen, (350, 250), f'SCORE: {snake.score}', (255, 255, 255)) pygame.display.update() pygame.time.wait(1000) sys.exit(0) # -------------------------------------- # Eating food if snake.head.rect.colliderect(food.rect): food.eaten(snake) snake.score += 1 snake.add_block(food.rect.x, food.rect.y, food.rect.width, food.rect.height) print(snake.score) # print(snake.movements) # -------------------------------------- snake.draw(screen, (255, 0, 0), snake) food.draw(screen, food.color, food.rect) draw_grid(screen, width, 40) pygame.display.update() screen.fill((0, 0, 0)) clock.tick(4) pygame.quit()
class App(Logger): windowWidth = 880 windowHeight = 660 snake = 0 food = 0 def __init__(self, controller_type, brick_layout_type): Logger.__init__(self) self._running = True self._display_surf = None self._image_surf = None self._food_surf = None self._brick_image = None self.game = Game() self.snake = Snake(3, self.windowHeight, self.windowWidth) self.bricks = Bricks(5, 5, brick_layout_type) self.food = Food() self.food.generate_food(self.snake, self.bricks) self._score = 0 # this needs to be updated as required self.controller_type = controller_type self.snake_controller = constants.controller_name_mapping[ controller_type]() def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode( (self.windowWidth, self.windowHeight), pygame.HWSURFACE) # pygame.display.set_caption('Pygame pythonspot.com example') self._running = True self._image_surf = pygame.image.load("assets/snake.png").convert() self._food_surf = pygame.image.load("assets/food.png").convert() self._brick_image = pygame.image.load("assets/brick.png").convert() self._snake_head_image = pygame.image.load( "assets/snake_head.png").convert() def on_event(self, event): if event.type == QUIT: self._running = False def on_loop(self): self.snake.update() # does snake eat food? if self.game.isCollision(self.food.x, self.food.y, self.snake.x[0], self.snake.y[0], 44): # add score of 1 for eating food self._score += 1 self.food.generate_food(self.snake, self.bricks) self.snake.length = self.snake.length + 1 # does snake collide with itself? for i in range(2, self.snake.length): if self.game.isCollision(self.snake.x[0], self.snake.y[0], self.snake.x[i], self.snake.y[i], 40): print( "Snake tried to move in the {0} direction and collided with itself." .format(constants.move_direction_text_dict[ self.snake.getCurrentDirection()])) print("x[0] (" + str(self.snake.x[0]) + "," + str(self.snake.y[0]) + ")") print("x[" + str(i) + "] (" + str(self.snake.x[i]) + "," + str(self.snake.y[i]) + ")") print("Your score: {0}".format(self._score)) return True # does snake collide with a brick? for i in range(self.bricks.getNumBricks()): if self.game.isCollision(self.bricks.x[i], self.bricks.y[i], self.snake.x[0], self.snake.y[0], 40): print("You lose! Collision with brick: ") print("x[0] (" + str(self.snake.x[0]) + "," + str(self.snake.y[0]) + ")") print("x[" + str(i) + "] (" + str(self.bricks.x[i]) + "," + str(self.bricks.y[i]) + ")") print("Your score: {0}".format(self._score)) return True return False def on_render(self, game_over=False): if not game_over: self._display_surf.fill((0, 0, 0)) self.snake.draw(self._display_surf, self._image_surf, self._snake_head_image) self.food.draw(self._display_surf, self._food_surf) self.bricks.draw(self._display_surf, self._brick_image) self.draw_score(self._display_surf, self.windowWidth - 200, self.windowHeight - 50, self._score) self.draw_snake_direction( self._display_surf, 50, self.windowHeight - 50, constants.move_direction_text_dict[ self.snake.getCurrentDirection()]) else: self.draw_game_over(self._display_surf, self._score) pygame.display.flip() def on_cleanup(self): time.sleep(2) # self.draw_game_over(self._display_surf, self._score) pygame.quit() def on_execute(self): if self.on_init() == False: self._running = False # self.start_logging_new_game() while (self._running): pygame.event.pump() self.snake, should_continue_running = self.snake_controller.perform_next_move( self.snake, self.food, self.bricks) if self.controller_type != constants.MANUAL: keys = pygame.key.get_pressed() if (keys[K_ESCAPE]): print( "Escape key pressed and so quitting the current game.") should_continue_running = False # self.log_snake_move(self.snake.getCurrentDirection()) self._running = should_continue_running is_collision = self.on_loop() if is_collision: self._running = False self.on_render(True) else: self.on_render() time.sleep(50.0 / 1000.0) self.on_cleanup() #Create the text used to display the score and draw it on the screen def draw_score(self, screen, x, y, score): font = pygame.font.Font(None, 36) #Choose the font for the text text = font.render("Score = " + str(score), 1, (255, 255, 255)) #Create the text with white color screen.blit(text, (x, y)) #Draw the text on the screen #Create the text used to display the current direction the snake head is moving def draw_snake_direction(self, screen, x, y, snake_direction_text): font = pygame.font.Font(None, 36) #Choose the font for the text text = font.render("Going: " + snake_direction_text, 1, (255, 255, 255)) #Create the text with white color screen.blit(text, (x, y)) #Draw the text on the screen # draw the game over screen # taken from https://www.teachyourselfpython.com/challenges.php?a=03_Pygame_Challenges_and_Learn&t=01_Function_based_game&s=07_Add_Game_over_feature def draw_game_over(self, screen, score): font = pygame.font.Font(None, 28) #Choose the font for the text text = font.render("COLLISION! GAME OVER!", 1, constants.WHITE) #Create the text for "GAME OVER" screen.blit(text, (self.windowWidth / 2, self.windowHeight / 2)) #Draw the text on the screen
def gameLoop(): global dirn, k, highscore, namehighscore pyExit = False pyOver = False #stop intro music and play in game music infinite loop intro_sound.stop() game_sound.play(-1) score = 0 world_num = 0 scorestr = "Score:0" # Initialize the game snake = Snake(200, 200, img) food = Food(int(width / 2), int(height / 2)) blocks = worlds(width - 200, height, world_num) # Keeps track of the direction of the snake. dx, dy = 0, 0 lossreason = '' while not pyExit: if pyOver == True: #play end music endgame_sound.play(-1) while pyOver: image = pygame.image.load(python_path) game_display.blit(image, (0, 0)) message("Game Over! Press C to play Again, Q to Quit", (255, 0, 0), -20) message(lossreason, (255, 0, 0), 30) # display score on game over message("Your" + scorestr, (255, 0, 0), 80) if totalscore > highscore: # message("Highscore!!!",(255,0,0),120) # write new highscore highscorefile = open('highscore.txt', 'wt') highscorefile.write(str(totalscore) + "\n") # name window def namewrite(): highscorefile.write(v.get()) scorewindow.destroy() scorewindow = Tk() scorewindow.geometry('300x100') frame = Frame(scorewindow, width=100, height=100) frame.pack() scorewindow.title("congratulations") Label(frame, text='you\'ve made highscore!!!!').pack(side='top') v = StringVar() v.set("type your name") textbox = Entry(frame, textvariable=v) textbox.pack(side='top') okbutton = Button(frame, text="ok", fg="black", bg="white", command=namewrite) okbutton.pack(side='bottom') scorewindow.mainloop() highscorefile.close() # incase user wants to countinue after creating highscore # to read his new score highscorefile = open('highscore.txt', 'rt') highscore = highscorefile.readline() highscore = int(highscore) namehighscore = highscorefile.readline() highscorefile.close() else: message("Highscore by " + namehighscore + ":" + str(highscore), (255, 0, 0), 120) pygame.display.update() for event in pygame.event.get(): keyp = action() if keyp != None or event.type == pygame.KEYDOWN: try: if keyp == 'q' or event.key == pygame.K_q: pyExit = True pyOver = False except: blank = [] # bypass the exception try: if keyp == 'c' or event.key == pygame.K_c: #stop endgame music endgame_sound.stop() gameLoop() except: blank = [] # bypass the exception """ Events """ #the conditions are modified to work with the buttons for event in pygame.event.get(): keyp = action() # blank is not used anywhere # it is just used to jump the exception if event.type == pygame.QUIT: pyExit = True if event.type == pygame.KEYDOWN or keyp != None: try: if keyp == 'lt' or event.key == pygame.K_LEFT and dirn != "right": dirn = "left" dx = -1 dy = 0 except: blank = [] try: if keyp == 'rt' or event.key == pygame.K_RIGHT and dirn != "left": dirn = "right" dx = 1 dy = 0 except: blank = [] try: if keyp == 'up' or event.key == pygame.K_UP and dirn != "down": dirn = "up" dy = -1 dx = 0 except: blank = [] try: if keyp == 'dn' or event.key == pygame.K_DOWN and dirn != "up": dirn = "down" dy = 1 dx = 0 except: blank = [] try: if keyp == 'p' or event.key == pygame.K_p: pause(scorestr) except: blank = [] try: if keyp == 'q' or event.key == pygame.K_q: pygame.quit() quit(0) except: blank = [] # level changer value if score > 10: score = 0 world_num += 1 blocks = worlds(width - 200, height, world_num) food.x, food.y = int(width / 2), int(height / 2) # Engage boost of pressing shift keyp=action() keyPresses = pygame.key.get_pressed() boost_speed = keyPresses[pygame.K_LSHIFT] or keyPresses[pygame.K_RSHIFT] or keyp=='st' # if boost_speed is true it will move 2 blocks in one gameloop # else it will just move one block iterations = [1] if boost_speed == 1: iterations.append(2) for i in iterations: """ Update snake """ snake.move(dx, dy, 10) snake.check_boundary(width, height) snake_rect = snake.get_rect() food_rect = food.get_rect() """ Snake-Snake collision """ if snake.ate_itself(): #stop game sound game_sound.stop() pyOver = True lossreason = 'Oooops You Hit YOURSELF' """ Snake-Block collision """ for block in blocks: block_rect = block.get_rect() if block_rect.colliderect(snake_rect): #stop game sound game_sound.stop() pyOver = True lossreason = 'Ooops You Hit a BLOCKER' """ Snake-Food collision """ # if snake collides with food, increase its length. if food_rect.colliderect(snake_rect): score += 1 snake.increment_length() sound = pygame.mixer.Sound(point_path) sound.set_volume(0.3) sound.play() # generate food at random x, y. food.generate_food(width, height) # try generating the food at a position where blocks are not present. while food_collides_block(food.get_rect(), blocks): food.generate_food(width - food.size, height - food.size) """ Draw """ game_display.fill((255, 255, 255)) showButton() # draw the food and snake. snake.draw(game_display, dirn, (0, 155, 0)) food.draw(game_display, (0, 255, 0)) # draw the blocks. for block in blocks: block.draw(game_display, (255, 0, 0)) # count and display score on screen totalscore = total(score, world_num) scorestr = 'Score: ' + str(totalscore) font = pygame.font.SysFont(None, 30) text = font.render(scorestr, True, (0, 0, 255)) game_display.blit(text, (0, 0, 20, 20)) pygame.display.update() clock.tick(FPS) pygame.quit() quit()
elif food_dist < previous_dist: reward = 5 elif food_dist > previous_dist: reward = -5 print('Reward: {}'.format(reward)) q_model.train(features, reward, do_decay=False) previous_dist = food_dist do_train = False if episodes_index >= MAX_EPISODES_TRAIN: is_training = False if moves_since_score > 100 and state != GameState.FINISHED: state = GameState.FINISHED player_died = True episodes_index += 1 print('At Episode: {} out of {}'.format(episodes_index, MAX_EPISODES_TRAIN)) q_model.decay() q_model.print_q_table() screen.fill((255, 255, 255)) grid.draw(screen) snake.draw(screen, grid) food.draw(screen, grid) screen.blit(text, (WIDTH / 2 - (text.get_size()[0] / 2), 0)) pygame.display.flip() pygame.quit()
def game_loop(): left_wall = Brick() left_wall.x = 0 left_wall.y = 0 left_wall.width = 10 left_wall.height = HEIGHT right_wall = Brick() right_wall.x = WIDTH - 10 right_wall.y = 0 right_wall.width = 10 right_wall.height = HEIGHT upper_wall = Brick() upper_wall.y = 0 upper_wall.x = 0 upper_wall.height = 10 upper_wall.width = WIDTH bottom_wall = Brick() bottom_wall.y = HEIGHT - 10 bottom_wall.x = 0 bottom_wall.height = 10 bottom_wall.width = WIDTH brick_li = [] bri_js_li = [] is_multiplayer = False running = True start_screen = True # Create snakes snake = Snake() snake_sec = Snake() snake_sec.dx = -5 snake_sec.elements = [[300, 400], [320, 400], [340, 400]] # Create food food = Food() while running: mil = clock.tick(FPS) while start_screen: welcome(screen, (0, 0, 0), (255, 255, 255)) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: pygame.quit() sys.exit() if event.key == pygame.K_n: # second Snake snake_sec.visible = False snake = Snake() brick_li.clear() bri_js_li.clear() st = json.dumps(brick_li) with open(r'brickcache.txt', 'w') as file: file.write(st) start_screen = False snake.visible = True if event.key == pygame.K_m: is_fir_score_assigned = False is_sec_score_assigned = False x_score_sec = 510 y_score_sec = 470 snake = Snake() snake_sec = Snake() # brick_li.clear() # reinitializing second snake snake_sec.dx = -5 snake_sec.elements = [[300, 400], [320, 400], [340, 400]] start_screen = False snake.visible = True snake_sec.visible = True if event.key == pygame.K_c: # second Snake snake_sec.visible = False # is_multiplayer = False brick_li.clear() snake = Snake() with open(r'cache.txt', 'r') as file: st = file.read() data = json.loads(st) snake.score = int(data["score"]) snake.visible = data["visible"] snake.is_add = data["is_add"] snake.dx = data["dx"] snake.dy = data["dy"] snake.size = data["size"] snake.thickness = data["thickness"] snake.level = int(data["level"]) snake.elements = data["elements"] with open(r'brickcache.txt', 'r') as bri_file: st = bri_file.read() bri_li_file = json.loads(st) for bri in bri_li_file: b = Brick() b.x = bri["x"] b.y = bri["y"] b.width = bri["width"] b.height = bri["height"] brick_li.append(b) start_screen = False snake.visible = True if event.type == pygame.QUIT: pygame.quit() sys.exit() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if snake.visible: if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: snake.dx = 5 snake.dy = 0 if event.key == pygame.K_LEFT: snake.dx = -5 snake.dy = 0 if event.key == pygame.K_UP: snake.dx = 0 snake.dy = -5 if event.key == pygame.K_DOWN: snake.dx = 0 snake.dy = 5 if snake_sec.visible: if event.type == pygame.KEYDOWN: if event.key == pygame.K_d: snake_sec.dx = 5 snake_sec.dy = 0 if event.key == pygame.K_a: snake_sec.dx = -5 snake_sec.dy = 0 if event.key == pygame.K_w: snake_sec.dx = 0 snake_sec.dy = -5 if event.key == pygame.K_s: snake_sec.dx = 0 snake_sec.dy = 5 collision(food, snake) if snake_sec.visible: collisionSec(food, snake_sec) if snake_sec.visible: if has_snakes_collided(snake, snake_sec): while collision_screen: game_over(screen, (0, 0, 0), (255, 255, 255)) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: game_loop() if event.key == pygame.K_q: pygame.quit() sys.exit() screen.fill((165, 206, 216)) left_wall.draw(screen) right_wall.draw(screen) upper_wall.draw(screen) bottom_wall.draw(screen) snake.move() snake.draw(screen) if snake_sec.visible: is_out = "OUT" snake_sec.move() snake_sec.draw(screen) show_score(x_score_sec, y_score_sec, snake_sec.score, screen) if wall_snake_collision(snake_sec, right_wall) or wall_snake_collision(snake_sec, left_wall) \ or wall_snake_collision(snake_sec, bottom_wall) or wall_snake_collision(snake_sec, upper_wall): if not is_fir_score_assigned: fir_score = snake.score is_fir_score_assigned = True snake_sec.score = is_out x_score_sec = 480 y_score_sec = 470 snake_sec.thickness = 0 if wall_snake_collision(snake, right_wall) or wall_snake_collision(snake, left_wall) \ or wall_snake_collision(snake, bottom_wall) or wall_snake_collision(snake, upper_wall): if not is_sec_score_assigned: sec_score = snake_sec.score is_sec_score_assigned = True snake.score = is_out snake.thickness = 0 if snake_sec.score == is_out and snake.score == is_out: copy_snake = snake copy_snake_sec = snake_sec copy_snake.score = fir_score copy_snake_sec.score = sec_score while collision_screen: game_over_multiplayer(screen, (0, 0, 0), (255, 255, 255), copy_snake, copy_snake_sec) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: game_loop() if event.key == pygame.K_q: pygame.quit() sys.exit() food.draw(screen) show_score(10, 15, snake.score, screen) if not snake_sec.visible: show_level(10, 45, snake.level, screen) if not snake_sec.visible: while len(brick_li) < snake.level - 1: b = Brick() if b not in brick_li: brick_li.append(b) print(brick_li) if not snake_sec.visible: for brick in brick_li: brick.draw(screen) if not snake_sec.visible: # Ооох, спагетти... if wall_snake_collision(snake, right_wall) or wall_snake_collision(snake, left_wall) \ or wall_snake_collision(snake, bottom_wall) or wall_snake_collision(snake, upper_wall): copy_snake = snake snake = Snake() brick_li.clear() bri_js_li.clear() st = json.dumps(brick_li) with open(r'brickcache.txt', 'w') as file: file.write(st) with open(r'cache.txt', 'w') as cache_file: cache_file.write(DEFAULT_SNAKE_PARAMS) while collision_screen: game_over(screen, (0, 0, 0), (255, 255, 255), copy_snake) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: game_loop() if event.key == pygame.K_q: pygame.quit() sys.exit() if not snake_sec.visible: if brick_snake_collision(snake, brick_li): copy_snake = snake snake = Snake() brick_li.clear() bri_js_li.clear() st = json.dumps(brick_li) with open(r'brickcache.txt', 'w') as file: file.write(st) with open(r'cache.txt', 'w') as cache_file: cache_file.write(DEFAULT_SNAKE_PARAMS) while collision_screen: game_over(screen, (0, 0, 0), (255, 255, 255), copy_snake) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: game_loop() if event.key == pygame.K_q: pygame.quit() sys.exit() keys = pygame.key.get_pressed() if keys[pygame.K_ESCAPE]: start_screen = True if not snake_sec.visible: cache = {} cache["size"] = snake.size cache["thickness"] = snake.thickness cache["dx"] = snake.dx cache["dy"] = snake.dy cache["is_add"] = snake.is_add cache["visible"] = snake.visible cache["score"] = snake.score cache["level"] = snake.level cache["elements"] = snake.elements for brick in brick_li: bri = {} bri["width"] = brick.width bri["height"] = brick.height bri["x"] = brick.x bri["y"] = brick.y if bri not in bri_js_li: bri_js_li.append(bri) jstring = json.dumps(cache) j_bri_string = json.dumps(bri_js_li) with open(r'cache.txt', 'w') as file: file.write(jstring) with open(r'brickcache.txt', 'w') as bri_file: bri_file.write(j_bri_string) pygame.display.flip()