0
\$\begingroup\$

I've begun my journey with game development a little while ago, thought recreating snake would be cool, except I plan on adding other cool mechanics and stuff to it later. The player controller script utilizes a looot of if statements, I'm sure there's a much better and cleaner way to do this, any tips or help is greatly appreciated, thank you :)

Snake Class Script:

class Snake:
    def __init__(self, screen):
        self.screen = screen
        self.rect = pygame.rect.Rect(self.screen.get_rect().center, (16, 16))
        self.vel = 5
        self.x_vel = 0
        self.y_vel = 0

    def draw(self):
        pygame.draw.rect(self.screen, "orange", self.rect)

    def move(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            if self.rect.x >= 0:
                self.x_vel = -self.vel
                self.y_vel = 0
            else:
                self.x_vel = self.vel
                self.y_vel = 0
        elif keys[pygame.K_RIGHT]:
            if self.rect.x <= 0:
                self.x_vel -= self.vel
                self.y_vel = 0
            else:
                self.x_vel = self.vel
                self.y_vel = 0
        elif keys[pygame.K_UP]:
            if self.rect.y >= 0:
                self.x_vel = 0
                self.y_vel = -self.vel
            else:
                self.x_vel = 0
                self.y_vel = self.vel
        elif keys[pygame.K_DOWN]:
            if self.rect.y <= self.screen.get_width():
                self.x_vel = 0
                self.y_vel = self.vel
            else:
                self.x_vel = 0
                self.y_vel = -self.vel

        #Teleports player to other side of window if they go out of frame
        if self.rect.x <= 0:
            self.rect.x = self.screen.get_width()
        elif self.rect.x >= self.screen.get_width():
            self.rect.x = 0
        elif self.rect.y <= 0:
            self.rect.y = self.screen.get_height()
        elif self.rect.y >= self.screen.get_height():
            self.rect.y = 0

        self.rect.x += self.x_vel
        self.rect.y += self.y_vel
\$\endgroup\$
1
  • \$\begingroup\$ Can you show how this class is instantiated and run? You're missing your pygame imports. \$\endgroup\$
    – Reinderien
    Commented Aug 23, 2023 at 21:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.