0

i just copy this code for reference i just want to know how to solve the problem with self eating snake

class snake(object):
    body = []
    turns = {}
    def _init_(self, color, pos):
        self.color = color
        self.head = cube(pos)
        self.body.append(self.head)
        self.dirnx = 0
        self.dirny = 1
        pass

        def move(self):
            for event in pygame.event.get():
               if event.type == pygame.QUIT:
                    pygame.quit()

                    keys = pygame.key.get_presseed()
                    for key in keys:
                        if keys[pygame.K_LEFT]:
                            self.dirnx = -1
                            self.dirny = 0

                            self.truns[self.head.pos[:]] = [self.dirnx, self.dirny]
                        elif keys[pygame.K_RIGHT]:
                                self.dirnx = 1
                                self.dirny = 0

                                self.truns[self.head.pos[:]] = [self.dirnx, self.dirny]
                        elif keys[pygame.K_UP]:
                                self.dirnx = 0
                                self.dirny = -1

                        elif keys[pygame.K_DOWN]:
                                self.dirnx = 0
                                self.dirny = 1
                                self.truns[self.head.pos[:]] = [self.dirnx, self.dirny]

            for i, c in enumeration(self.body):
                    P = c.pos[:]
                    if p in self.turns:
                            turns = self.turns[p]
                            c.move(turns[0],turns[1])
                            if i == len(self.body)-1:
                                    self.turns.pop(p)
                    else:
                            if c.dirnx == -1 and c.pos[0] <= 0: c.pos = (c.rows-1, c.pos[1])
                            elif c.dirnx == 1 and c.pos[0] >= c.rows-1: c.pos = (0,c.pos[1])
                            elif c.dirnx == 1 and c.pos[1] >= c.rows-1: c.pos = (c.pos[0], 0)
                            elif c.dirnx == -1 and c.pos[1] <= 0: c.pos = (c.pos[0],c.rows-1)
                            else: c.move(c.dirnx,c.dirny)
eyllanesc
  • 221,139
  • 17
  • 121
  • 189
CodeNoobie
  • 11
  • 4

1 Answers1

0

I think the simplest solution is just to ignore that keypress if the snake is going in the opposite direction of where the user told the snake to go. If I understand your code above, you are keeping track of the snake direction with self.dirnx and self.dirny within the different conditional statements.

As an example of how you could skip a left key press when the snake is going right you could update your conditional from if keys[pygame.K_LEFT], to instead be if keys[pygame.K_LEFT] and self.dirnx != 1 (making sure you aren't currently going right).

Jenner Felton
  • 767
  • 1
  • 10
  • 18