#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 定义一种新的类型
typedef int BOOL;
// 为新类型设定两个可选值
const int YES = 1;
const int NO = 0;
int main() {
srand((unsigned)time(0)); //时间作为随机数种子
int money = 100; //玩家游戏筹码
do {
printf("你拥有%d元筹码!\n", money);
int debt; //押注
do {
printf("请下注: ");
scanf("%d", &debt);
} while (debt <= 0 || debt > money);
int face1 = rand() % 6 + 1;
int face2 = rand() % 6 + 1;
int firstPoint;
firstPoint = face1 + face2;
printf("你摇出了%d点\n", firstPoint);
BOOL gameOver = NO;
switch (firstPoint) {
case 7: case 11:
printf("你赢了!\n");
money += debt;
gameOver = YES;
break;
case 2: case 3: case 12:
printf("你输了!\n");
money -= debt;
gameOver = YES;
break;
}
while (!gameOver) {
face1 = rand() % 6 + 1;
face2 = rand() % 6 + 1;
int currentPoint = face1 + face2;
printf("你摇出了%d点\n", currentPoint);
if (currentPoint == 7) {
printf("你输了!\n");
money -= debt;
gameOver = YES;
}
else if (currentPoint == firstPoint) {
printf("你赢了!\n");
money += debt;
gameOver = YES;
}
}
} while (money > 0);
printf("你破产了!游戏结束!\n");
return 0;
}
可以在do-while里面,如果筹码大于0,则增加询问玩家是否继续游戏,如果是则继续游戏,否则则退出游戏,修改如下:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 定义一种新的类型
typedef int BOOL;
// 为新类型设定两个可选值
const int YES = 1;
const int NO = 0;
int main() {
srand((unsigned)time(0)); //时间作为随机数种子
int money = 100; //玩家游戏筹码
int continueGame=YES;
do {
printf("你拥有%d元筹码!\n", money);
int debt; //押注
do {
printf("请下注: ");
scanf("%d", &debt);
} while (debt <= 0 || debt > money);
int face1 = rand() % 6 + 1;
int face2 = rand() % 6 + 1;
int firstPoint;
firstPoint = face1 + face2;
printf("你摇出了%d点\n", firstPoint);
BOOL gameOver = NO;
switch (firstPoint) {
case 7:
case 11:
printf("你赢了!\n");
money += debt;
gameOver = YES;
break;
case 2:
case 3:
case 12:
printf("你输了!\n");
money -= debt;
gameOver = YES;
break;
}
while (!gameOver) {
face1 = rand() % 6 + 1;
face2 = rand() % 6 + 1;
int currentPoint = face1 + face2;
printf("你摇出了%d点\n", currentPoint);
if (currentPoint == 7) {
printf("你输了!\n");
money -= debt;
gameOver = YES;
}
else if (currentPoint == firstPoint) {
printf("你赢了!\n");
money += debt;
gameOver = YES;
}
}
// 如果筹码大于0,则询问玩家是否继续游戏
if(money>0){
printf("是否继续游戏(是-1,否-0)\n");
scanf("%d",&continueGame);
while(continueGame!=YES&&continueGame!=NO){
printf("是否继续游戏(是-1,否-0)\n");
scanf("%d",&continueGame);
}
}
} while (continueGame==YES&&money>0); // do-while的条件改为玩家选择继续游戏并且筹码大于0
printf("游戏结束,筹码剩余%d元。",money);
// printf("你破产了!游戏结束!\n");
return 0;
}