输入格式: shape: (图形英文名)
direction: (w:向上; a:向左; s:向下; d:向右)
(输入 quit 退出)
以下代码实现了正方形,三角形,菱形的移动:
#include <stdio.h>
#include <string.h> // 仅用于识别图形英文名
// 打印正方形
void square(int space,int row) {
int i,j,k,a;
for(a=0; a<row; a++)
printf("\n");
for(i=0; i<5; i++)
{ for(j=0; j<space; j++)
printf(" ");
for(k=0; k<5; k++)
printf("* ");
printf("\n");
}
return ;
}
// 打印金字塔
void pyramid(int space,int row) {
int n,i,j,spaces;
for (i=1-row; i<=5; i++) {
spaces= 5-i;
for (j=1; j<=spaces+space; j++)
printf(" ");
for (j=1; j<=2*i-1; j++)
printf("*");
printf("\n");
}
return ;
}
// 打印菱形
void diamond(int space,int row) {
int i,j,spaces,stars;
for (i=-5-row; i<=5; i++) {
spaces = i;
if(spaces<0) spaces =-i;
stars=9 - 2*spaces;
for (j=0; j<spaces+space; j++)
printf(" ");
for (j=0; j<stars; j++)
printf("*");
printf("\n");
}
return ;
}
int main() {
int space = 0, row = 0;
char ch[10], direction;
char buffer[100]; // 输入缓冲区
printf("shape: ");
scanf("%9s", ch);
while (getchar() != '\n'); // 清除输入缓冲区的回车符
while (1) {
printf("direction: ");
scanf("%9s", buffer);
direction = buffer[0]; // 读取第一个字符
if (strcmp(buffer, "quit") == 0) {
break;
} else if (direction == 's') {
row++;
} else if (direction == 'w') {
if (row > 0) {
row--;
}// 到边界了row的值保持为0
} else if (direction == 'd') {
space++;
} else if (direction == 'a') {
if (space > 0) {
space--;
}// 到边界了space的值保持为0
}
if (strcmp(ch, "square") == 0) {
square(space, row);
} else if (strcmp(ch, "pyramid") == 0) {
pyramid(space, row);
} else if (strcmp(ch, "diamond") == 0) {
diamond(space, row);
}
}
return 0;
}