This repository has been archived on 2024-01-06. You can view files and clone it, but cannot push or open issues or pull requests.
justhomework/MCU/Final_Design_FAIL/snake.c

104 lines
1.4 KiB
C
Raw Normal View History

2022-05-07 05:56:47 +00:00
#include "snake.h"
2022-05-07 11:39:50 +00:00
#include "display.h"
2022-05-07 05:56:47 +00:00
2022-05-07 11:39:50 +00:00
unsigned char len = 0;
Body snake[40] = {{0, 0}, 0};
2022-05-07 06:48:25 +00:00
2022-05-07 05:56:47 +00:00
void snake_init()
{
2022-05-07 06:48:25 +00:00
// Initialize snake
2022-05-07 11:39:50 +00:00
snake[len].d.x = XXX/2;
snake[len].d.y = YYY/2;
2022-05-07 06:25:22 +00:00
snake[len].m = R;
2022-05-07 11:39:50 +00:00
2022-05-07 06:25:22 +00:00
}
void body_move(Body b)
{
switch(b.m)
{
case R:
b.d.x++;
break;
case L:
b.d.x--;
break;
case U:
b.d.y--;
break;
case D:
b.d.y++;
break;
}
}
void snake_move()
{
int i = 0;
for(; i <= len; i++)
{
2022-05-07 06:48:25 +00:00
//All body parts move
2022-05-07 06:25:22 +00:00
body_move(snake[i]);
}
for(i = 1; i <= len; i++)
{
2022-05-07 06:48:25 +00:00
//Sync move direction for next move
2022-05-07 06:25:22 +00:00
snake[i].m = snake[i - 1].m;
}
}
void body_add()
{
2022-05-07 06:48:25 +00:00
// Copy last body part to new body part
2022-05-07 11:39:50 +00:00
len++;
2022-05-07 06:25:22 +00:00
snake[len].m = snake[len - 1].m;
snake[len].d.x = snake[len - 1].d.x;
2022-05-07 06:48:25 +00:00
snake[len].d.y = snake[len - 1].d.y;
// Judge the direction of new body part
2022-05-07 06:25:22 +00:00
switch(snake[len].m)
{
case R:
snake[len].d.x--;
break;
case L:
snake[len].d.x++;
break;
case U:
snake[len].d.y++;
break;
case D:
snake[len].d.y--;
break;
}
}
2022-05-07 06:48:25 +00:00
void snake_draw()
{
int i=1;
2022-05-07 11:39:50 +00:00
sAddDot(snake[0].d.x,snake[0].d.y);
sAddDot(snake[0].d.x+1,snake[0].d.y);
sAddDot(snake[0].d.x,snake[0].d.y+1);
sAddDot(snake[0].d.x-1,snake[0].d.y);
sAddDot(snake[0].d.x,snake[0].d.y-1);
2022-05-07 06:48:25 +00:00
for(;i<=len;i++)
{
2022-05-07 11:39:50 +00:00
sAddDot(snake[i].d.x,snake[i].d.y);
2022-05-07 06:48:25 +00:00
}
}
2022-05-07 06:25:22 +00:00
2022-05-07 06:48:25 +00:00
void snake_test()
2022-05-07 06:25:22 +00:00
{
2022-05-07 11:39:50 +00:00
//Add Body to test
2022-05-07 06:25:22 +00:00
int i = 0;
2022-05-07 11:39:50 +00:00
for(; i < 2; i++)
2022-05-07 06:25:22 +00:00
body_add();
2022-05-07 05:56:47 +00:00
}