Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help to fix PYTHON CODES
#3
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.
    # 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)] * 3
6 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.
Reply


Messages In This Thread
Help to fix PYTHON CODES - by LLNT13 - May-05-2020, 09:47 AM
RE: Help to fix PYTHON CODES - by michael1789 - May-05-2020, 07:16 PM
RE: Help to fix PYTHON CODES - by Windspar - May-06-2020, 03:01 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020