我正在制作一个程序,我想让我的蛇朝着它前进的方向前进,但是当我尝试这个代码时:
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度之间吗?
答案 0 :(得分:2)
更改turn_left
和turn_right
以使用模运算符。
def turn_left(self):
self.dire = (self.dire + 90) % 360
def turn_right(self):
self.dire = (self.dire - 90) % 360
当a % b
除以a
时, b
运算符会返回余数,因此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)))
在这种情况下,你甚至不需要模运算符,但保留它可能会很好。
答案 1 :(得分:1)
这是基于@Pavlus建议使用modulo %
运算符,以及一些格式修复程序,以便于查看。
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()