- #include <stdio.h>
- #define COL 64
- #define ROW 20
- #define BGCOLOR ' '
- #define FGCOLOR '*'
- #define X 10
- #define Y 10
- #define W 6
- #define H 3
- #define X_INC 1
- #define Y_INC 1
- static int color = 0;
- void init(int *bg, int row, int col, char color);
- void draw(int *bg, int row, int col,
- int x, int y, int w, int h, int color);
- void move(int *x, int *y, int w, int h,
- int *x_inc, int *y_inc);
- //void show(int *bg, int row, int col);
- //void show(int (*arr)[COL], int row);
- void show(int arr[][COL], int row);
- int main(void)
- {
- int background[ROW][COL];
- int x, y, w, h;
- int x_inc, y_inc;
- x = X;
- y = Y;
- w = W;
- h = H;
- x_inc = X_INC;
- y_inc = Y_INC;
- while (1)
- {
- init((int *)background, ROW, COL, BGCOLOR);
- draw((int *)background, ROW, COL,
- x, y, w, h, FGCOLOR);
- //show((int *)background, ROW, COL);
- show(background, ROW);
- move(&x, &y, w, h, &x_inc, &y_inc);
- usleep(100000);
- }
- return 0;
- }
- void init(int *bg, int row, int col, char color)
- {
- int i, j;
- for (i = 0; i < row; ++i)
- {
- for (j = 0; j < col; ++j)
- {
- bg[i * col + j] = color;
- }
- }
- }
- void draw(int *bg, int row, int col,
- int x, int y, int w, int h, int color)
- {
- int i, j;
- for (i = y; i < y + h; ++i)
- {
- for (j = x; j < x + w; ++j)
- {
- bg[i * col + j] = color;
- }
- }
- }
- void show(int bg[][COL], int row)
- {
- int i, j;
- for (i = 0; i < row; ++i)
- {
- for (j = 0; j < COL; ++j)
- {
- if (*(bg[i] + j) == FGCOLOR)
- {
- printf("\033[3%dm%c\033[0m", color, *(bg[i] + j));
- }
- else
- {
- printf("%c", *(bg[i] + j));
- }
- }
- }
- fflush(stdout);
- }
- void move(int *x, int *y, int w, int h,
- int *x_inc, int *y_inc)
- {
- if (*x + *x_inc < 0 || *x + w + *x_inc > COL)
- {
- color += 1;
- color %= 8;
- *x_inc = -(*x_inc);
- }
- if (*y + *y_inc < 0 || *y + h + *y_inc > ROW)
- {
- color += 1;
- color %= 8;
- *y_inc = -(*y_inc);
- }
- *x += *x_inc;
- *y += *y_inc;
- }
基本思路:
1. 初始化二维数组BG 和 FG
2. 设置移动点 x 和 y 对移动点进行操作:
(1) “+”法移动
(2)如果“—”移动超过边界,并进行“—”操作, 就是对内存进行变化,一变到底