1. 程式人生 > 實用技巧 >C - 一個C語言猜字遊戲

C - 一個C語言猜字遊戲

下面是一個簡陋的猜字遊戲,玩了一會兒,發現自己打不過自己寫的遊戲,除非贏了就跑,最高分沒有過1000。

說明:srand(time(NULL))和rand(),srand,time和rand都是函式,其中srand和rand配對使用,srand是start random,也就是隨機數的初始化,time函式中的NULL表示獲取系統時間,所以整個意思是:以系統時間開始初始化,然後獲取隨機數。隨機數結果是一個整數。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int cash = 100;

void play(int bet) {

    char *C = (char *) malloc(sizeof(char) * 100);
    C[0] = 'J';
    C[1] = 'Q';
    C[2] = 'K';
    printf("Shuffling... \n");
    srand(time(NULL));

    int i;
    for (i = 0; i < 5; i++) {
        int x = rand() % 3;
        int y = rand() % 3;
        char temp = C[x];
        C[x] = C[y];
        C[y] = temp;
    }

    int playersGuess;
    printf("What's your guess for the Queen's position? 1, 2 or 3: ");
    scanf("%d", &playersGuess);

    if (C[playersGuess - 1] == 'Q') {
        cash = cash + bet * 3;
        printf("You win!, the result is: %c %c %c\n", C[0], C[1], C[2]);
        printf("Your money left is $ %d.\n", cash);
    } else {
        cash = cash - bet * 3;
        printf("You lose the bet, the result is: %c %c %c\n", C[0], C[1], C[2]);
        printf("Your money left is $ %d.\n", cash);
    }

    free(C);
}

void main(void) {
    int bet;
    printf("Welcome to the virtual Casino!\n");
    printf("The total cash you have from the start is $%d.\n", cash);

    while (cash > 0) {
        printf("Please enter your bet: $ ");
        scanf("%d", &bet);

        if (bet <= 0) break;
        else if (bet > cash) {
            printf("Error. The bet is bigger than your cash.");
            break;
        }

        play(bet);

    }
    printf("You lost the game. \n");

}

有時間加入一個重新開始的功能,可玩性會高一些。