Undoubtedly this question has been asked before, except I completely lack the knowledge to find it.
I’m trying to write the classic snake (aka Nibbles) game and the logic is pretty straight forward. Direction is expressed by a delta coordinate pair. North is -1, 0; east is 0, 1; south is 1,0; and west is 0, -1.
It’s been a decade since I took a math course so I’m not exactly sure how to convert those pairs into something where North = 0 degree’s; east = 45, south = 90; and west = 135 in which case the problem is drastically simple and becomes a case of clock arithmetic then conversion back to delta pairs.
Also, this is not academic homework but self-education
Edit:
Got a working prototype thanks to the selected answer below.
http://ominian.com/examples/js/pinglib/snakes.html
If you really mean degrees then you want increments of 90 degrees rather than 45.
You need the
atan2function (which exists in various forms in many languages). Something likeangle = 180/pi * atan2(dy,dx)— the180/piis becauseatan2returns a value in radians. There will be numerous small mismatches between what this does and what you want:dywill be taken to increase upwards rather than downwards, 0 will be east rather than north, andatan2typically returns values between -pi and +pi rather than between 0 and 2pi. Untangling all these is left as an exercise for the reader :-).If you only need the 4 special cases you described then you could do something ugly and ad hoc. For instance,
angle = 180*(dy-dx>0)+90*(dx!=0)will do the job because S,W share the property thatdy-dx>0and E,W share the property thatdx!=0.You may well find it better to work with
dx,dyvalues everywhere and not use angles explicitly at all. For instance, rotation through 90 degrees is just(dx,dy)=(-dy,dx)(or(dy,-dx)for the other direction).