Featured image of post C語言小遊戲-圈圈叉叉

C語言小遊戲-圈圈叉叉

C語言小遊戲-圈圈叉叉

一、程式碼

程式碼先上再說(●ˇ∀ˇ●)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <stdio.h>

char box[10] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

void board();
void marking(int, char); //標記OX
int chkwin();           //是否有贏
int main() {
  int choice, player = 1, i;
  char mark;
  do {
    board();
    player = (player % 2) ? 1 : 2; //當前玩家

    printf(" %d 號玩家,請輸入空格數字:", player);
    scanf("%d", &choice);
    mark = (player == 1) ? 'o' : 'x';
    marking(choice, mark);
    i = chkwin();
    player++;
  } while (i == -1);

  board();

  if (i == 1)
    printf(" %d 號玩家獲勝", --player);
  return 0;
}

void board() {
  printf("\n\n圈圈叉叉\n");
  printf("一號玩家為o -- 二號玩家為x\n\n");

  printf(" %c   | %c   | %c   \n", box[1], box[2], box[3]);

  printf("-----|-----|----- \n");
  printf(" %c   | %c   | %c   \n", box[4], box[5], box[6]);

  printf("-----|-----|----- \n");
  printf(" %c   | %c   | %c   \n", box[7], box[8], box[9]);
  printf("\n");
}

void marking(int choice, char mark) {
  if (choice == 1 && box[1] == '1')
    box[1] = mark;
  else if (choice == 2 && box[2] == '2')
    box[2] = mark;
  else if (choice == 3 && box[3] == '3')
    box[3] = mark;
  else if (choice == 4 && box[4] == '4')
    box[4] = mark;
  else if (choice == 5 && box[5] == '5')
    box[5] = mark;
  else if (choice == 6 && box[6] == '6')
    box[6] = mark;
  else if (choice == 7 && box[7] == '7')
    box[7] = mark;
  else if (choice == 8 && box[8] == '8')
    box[8] = mark;
  else if (choice == 9 && box[9] == '9')
    box[9] = mark;
  else {
    printf("\n犯規,這個地方不能放(╬▔皿▔)╯\n\n");
  }
}

int chkwin() { //訪問所有可能性
  if (box[1] == box[2] && box[2] == box[3])
    return 1;
  else if (box[4] == box[5] && box[5] == box[6])
    return 1;
  else if (box[7] == box[8] && box[8] == box[9])
    return 1;
  else if (box[1] == box[4] && box[4] == box[7])
    return 1;
  else if (box[2] == box[5] && box[5] == box[8])
    return 1;
  else if (box[3] == box[6] && box[6] == box[9])
    return 1;
  else if (box[1] == box[5] && box[5] == box[9])
    return 1;
  else if (box[3] == box[5] && box[5] == box[7])
    return 1;
  else if (box[1] != '1' && box[2] != '2' && box[3] != '3' && box[4] != '4' &&
           box[5] != '5' && box[6] != '6' && box[7] != '7' && box[8] != '8' &&
           box[9] != '9')
    return 0;
  else
    return -1;
}

二、程式解釋

唉嘿,之後再上(〃` 3′〃)

三、實際執行

正常執行

玩家輸入同一格

玩家贏得遊戲

四、結語

以上是我學習C語言一段時間後寫出來的小程式,如果有任何可以優化或需要修改的地方,歡迎讀者在下方留言。 最後附上這個程式Replit的專案 Links

Cover Image by PIRO from Pixabay

Built with Hugo
Theme Stack designed by Jimmy