2017-07-25 39 views
1

我做节目,我想让我的蛇在它朝一个方向走,但是当我尝试此代码:如何将度数设置为最大值360?

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) 
    for event in pygame.event.get(): 
     if event.type == QUIT: 
      sys.exit() 
     if event.type == KEYDOWN and event.key == K_LEFT: 
      snake.turn_left() 
     if event.type == KEYDOWN and event.key == K_RIGHT: 
      snake.turn_right() 
    pressed_keys = pygame.key.get_pressed() 

还有一个问题: 我可以用两次转右箭头键,但我不能再去那个方向了。这是因为我所做的是:我按了箭头两次 - > self.dire - 90 - 90.所以self.dire现在是-180。我可以改变的价值观:我可以改变

if pressed_keys[self.ctrls[0]]and self.dire == 180: 
    self.y += 10 

if pressed_keys[self.ctrls[0]]and self.dire == 180 or -180: 
    self.y += 10 

但如果我按右箭头另一四次,我必须再添加值-540等。有谁知道更好的解决方案?或者你可以说self.dire必须在-360和360度之间?

+1

你试过除模('%'运算符)吗? – Pavlus

+0

不,我应该如何使用它? – AV13

+2

它返回除法运算的其余部分,所以'450%360'返回'90' – Pavlus

回答

1

这是基于@Pavlus建议使用模%运算符,以及几个格式修复使浏览更容易。

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) 
    for event in pygame.event.get(): 
     if event.type == QUIT: 
      sys.exit() 
     if event.type == KEYDOWN and event.key == K_LEFT: 
      snake.turn_left() 
     if event.type == KEYDOWN and event.key == K_RIGHT: 
      snake.turn_right() 
    pressed_keys = pygame.key.get_pressed() 
2

turn_leftturn_right更改为使用模运算符。

def turn_left(self): 
    self.dire = (self.dire + 90) % 360 

def turn_right(self): 
    self.dire = (self.dire - 90) % 360 

a % b运算符返回时ab划分余数,所以self.dire将留[0,360)的范围内。

你也将不得不改变

if pressed_keys[self.ctrls[0]]and self.dire == -90: 

if pressed_keys[self.ctrls[0]]and self.dire == 270: 

,或者甚至更好,使用三角函数。

import math 

def move(self): 
    if pressed_keys[self.ctrls[0]]: 
     self.x += 10 * int(math.cos(math.radians(self.dire))) 
     self.y += 10 * int(math.sin(math.radians(self.dire))) 

在这种情况下,你甚至不需要模运算符,但它可能是很好的保持它。

相关问题