python - How to set degrees to a maximum of 360? -
i'm making program , want let snake go in same direction heading, when try code:
def move(self): if pressed_keys[self.ctrls[0]]and self.dire == 0: self.y -= 10 if pressed_keys[self.ctrls[0]]and self.dire == 90: self.x -= 10 if pressed_keys[self.ctrls[0]]and self.dire == 180: self.y += 10 if pressed_keys[self.ctrls[0]]and self.dire == -90: self.x += 10 def turn_left(self): self.dire += 90 def turn_right(self): self.dire -= 90 . . . while 1: clock.tick(60) event in pygame.event.get(): if event.type == quit: sys.exit() if event.type == keydown , event.key == k_left: snake.turn_left() if event.type == keydown , event.key == k_right: snake.turn_right() pressed_keys = pygame.key.get_pressed()
there problem: can turn twice right arrow-key can't go in direction anymore. because did was: pressed arrow twice -> self.dire - 90 - 90. self.dire -180. change values: change
if pressed_keys[self.ctrls[0]]and self.dire == 180: self.y += 10
to
if pressed_keys[self.ctrls[0]]and self.dire == 180 or -180: self.y += 10
but if press right arrow 4 times, must add value -540 , on. know better solution? or can self.dire must between -360 , 360 degrees?
this based off @pavlus suggestion use modulo %
operator, along few formatting fixes make viewing easier.
def move(self): self.dire = self.dire % 360 if pressed_keys[self.ctrls[0]]: if self.dire == 0: self.y -= 10 if self.dire == 90: self.x -= 10 if self.dire == 180: self.y += 10 if self.dire == 270: self.x += 10 def turn_left(self): self.dire = (self.dire + 90) % 360 def turn_right(self): self.dire = (self.dire - 90) % 360 . . . while 1: clock.tick(60) event in pygame.event.get(): if event.type == quit: sys.exit() if event.type == keydown , event.key == k_left: snake.turn_left() if event.type == keydown , event.key == k_right: snake.turn_right() pressed_keys = pygame.key.get_pressed()
Comments
Post a Comment