+#include "car.h"
+
+#define COEFF 1
+
+void move_car(struct _car *car,int keys,SDL_Surface *fun)
+{
+ int c,r,g,b;
+
+ /* reset flags */
+ car->lapflag=0;
+ car->crashflag=0;
+
+ /* get the pixel color under the center of car in the function map */
+ c=getpixel(fun,car->x,car->y);
+ /* red layer (checkpoints) */
+ r=(c )&0xff;
+ /* green layer (road quality) */
+ g=(c>>8 )&0xff;
+ /* blue layer (unused) */
+ b=(c>>16)&0xff;
+
+ if (keys & 8) /* up */
+ car->speed+=0.01*2*COEFF;
+ if (keys & 4) /* down */
+ car->speed-=0.01*COEFF;
+ if (keys & 2) /* left */
+ {
+ if (car->speed<0)
+ car->angle+=0.01*(255-b)/255*COEFF;
+ else
+ car->angle-=0.01*(255-b)/255*COEFF;
+ }
+ if (keys & 1) /* right */
+ {
+ if (car->speed<0)
+ car->angle-=0.01*(255-b)/255*COEFF;
+ else
+ car->angle+=0.01*(255-b)/255*COEFF;
+ }
+
+ /* limit angle between 0 and 2*pi */
+ if (car->angle<0) car->angle+=2*M_PI;
+ if (car->angle>2*M_PI) car->angle-=2*M_PI;
+
+ /* update the speed depending on the road quality */
+ car->speed-=car->speed*(255-g)/1000;
+
+ /* if it is a wall we move back to the last position */
+ if (g==0)
+ {
+ car->x=car->ox;
+ car->y=car->oy;
+ car->crashflag=1;
+ }
+
+ /* save the old position and compute the new one */
+ car->ox=car->x;
+ car->oy=car->y;
+ car->speed*=0.995;
+ car->x-=cos(car->angle)*car->speed;
+ car->y-=sin(car->angle)*car->speed;
+
+ /* collision with the border of the screen */
+ if (car->x<car->w/2 || car->x>fun->w-car->w/2 || car->y<car->h/2 || car->y>fun->h-car->h/2)
+ {
+ car->x=car->ox;
+ car->y=car->oy;
+ car->speed=0;
+ car->crashflag=1;
+ }
+
+ /* if we are on the next checkpoint, validate it (no missing allowed) */
+ if (r/8==car->lastcheck+1) car->lastcheck++;
+ /* if we validate all and start over, we complete a turn */
+ if (r/8==0 && car->lastcheck==31)
+ {
+ /* reset turn variables */
+ car->lastcheck=0;
+ car->lap++;
+ car->lapflag=1;
+ }
+
+ return;
+}