2007年9月30日 星期日

C 程式設計作業七,選擇邏輯、重複邏輯、輸出輸入、陣列應用:解題


/* C Programming, Project 7 */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define ROW 3
#define COL 3

int marked[ROW][COL]={0}, slot[ROW][COL] = {0};
int getMarked(void);
void display(void);
int getMarked(void);
void showIcon(int);
int oneLine(void);

int main(void)
{
/* 你的程式這裡要寫 */
int colNo, rowNo;
int cMove, mi, mj;

do {
printf("Input cmd: ------> ");
scanf("%d,%d", &rowNo, &colNo);
if ((colNo>=0&&colNo<=2)&&(rowNo>=0&&rowNo<=2)&&(marked[rowNo][colNo]!=1)) {
/* printf("Your input ------> %d,%d\n", rowNo, colNo); */
marked[rowNo][colNo] = 1;
slot[rowNo][colNo] = 1;
display();

/* 回應玩家的動作 */
if (oneLine())
{
printf(" ---------------You win----------------\n");
break;
}
if (getMarked()==9)
break;
do {
cMove = rand()%9;
mi = cMove/3;
mj = cMove%3;
} while (marked[mi][mj] == 1);
marked[mi][mj] = 1;
slot[mi][mj] = -1;
display();
if (oneLine())
{
printf(" -------------Computer win--------------\n");
break;
}
} else {
printf("---------------Error input----------------\n");
}
} while (getMarked() < 9);
system("pause");
return 0;
}

int getMarked(void)
{
int i, j, total=0;
for (i=0;i<3;i++)
for (j=0;j<3;j++)
total += marked[i][j];
return total;
}

void display(void)
{
int i, j;
for (i=0;i<ROW;i++)
{
for (j=0;j<COL;j++) {
showIcon(slot[i][j]);
if (j<2)
printf("|");
else
printf("\n");
}
if (i<2)
printf("─┼─┼─\n");
else
printf("\n");
}
}

void showIcon(int a)
{
if (a==1)
printf("O");
else if (a==-1)
printf("x");
else if (a==0)
printf(" ");
}
int oneLine(void)
{
int i, j, total;
for (i=0;i<3;i++)
{
total = 0;
for (j=0;j<3;j++)
total += slot[i][j];
if (total==3 || total==-3)
return 1;
total = 0;
for (j=0;j<3;j++)
total += slot[j][i];
if (total==3 || total==-3)
return 1;
}
total = slot[0][0]+slot[1][1]+slot[2][2];
if (total==3 || total==-3)
return 1;
total = slot[0][2]+slot[1][1]+slot[2][0];
if (total==3 || total==-3)
return 1;
return 0;

}

作業七題目
回到首頁

沒有留言: