May-06-2020, 03:01 AM
1. You code is hard to read. You also have repeat code. You need rewrite. Don't use time. pygame has it own time module.
2. Import pygame.locals. Instead of using 'Right' use K_RIGHT for direction movement. Definitely don't use ord('d'). Use K_d. Never update direction in event loop. Because the next event can make a collision with self. All because snake didn't get to move.
2. Import pygame.locals. Instead of using 'Right' use K_RIGHT for direction movement. Definitely don't use ord('d'). Use K_d. Never update direction in event loop. Because the next event can make a collision with self. All because snake didn't get to move.
# Event loop if event.key in [K_RIGHT, K_d] and direction != K_LEFT: new_direction = K_RIGHT if new_direction: direction = new_direction new_direction = None if direction == K_RIGHT: x, y = snakebody[0] snake_head = (x + m, y) # etc snakebody.insert(0, snake_head) if snake_head == foodpos: score += 1 # Generate next food position else: snakebody.pop()3. Never use pygame.time.delay to control snake speed. You use delta, ticks, or timer. Ticks example.
# Varaibles snake_interval = 200 snake_next_tick = snake_interval # Main loop ticks = pygame.time.get_ticks(): if ticks > snake_next_tick: snake_next_tick += snake_interval if new_direction: direction = new_direction new_direction = None if direction == K_RIGHT: x, y = snakebody[0] snake_head = (x + m, y) # etc snakebody.insert(0, snake_head) if snake_head == foodpos: score += 1 # Update score text # Generate next food position else: snakebody.pop()4. You want pygame.time.Clock to idle program.
# Variable clock = pygame.time.Clock() fps = 60 # In Main loop clock.tick(fps)5. You can have all body position at the start be the same position. When snake move. Then you only check the snake head if it collide. Not the body. Using tuples because list are reference and mutable.
snakebody = [(60, 60)] * 36 Food position has to match snake position. So you can not multiply it by 10. It has to be multiply by m. You can also offset it when you draw it. Otherwise snake might never be able to collide with food.
99 percent of computer problems exists between chair and keyboard.