使用 srand()和rand() 函数,一个简单但有趣的游戏。这个游戏叫做“猜猜游戏”。
null
游戏规则:
- 有三个洞。一只老鼠藏在这三个洞中的一个洞里。
- 老鼠每次都变换姿势。
- 你得猜出老鼠藏在三个洞中间的那个洞。
- 老鼠所在的洞被命名为“R”,其余两个洞被命名为“N”。
- 你带了一些现金。
- 每次猜谜时,你都要为玩这个游戏下注。
- 如果你猜错了,你就从你的现金中损失了赌注。
- 如果你猜对了,你赢的钱是你的现金的两倍。
- 继续比赛,继续赢球,直到你的现金用完。
下面是这个简单有趣的游戏的C代码:
注: 由于这个游戏需要玩家输入他们的现金、赌注金额和猜测的老鼠位置,所以它不会在在线编译器中运行。
// Cpp program for guessing game // using rand() and srand() #include <stdio.h> #include <stdlib.h> #include <time.h> void GuessGame( int amount_bet, int * inhand_cash) { char Hole[3] = { 'N' , 'R' , 'N' }; printf ( "Wait !! Rat is shuffling its position..." ); srand (( time (NULL))); int i, x, y, temp; /*Swapping the Rat's (R's) position five times using the random number for random index*/ for (i = 0; i < 5; i++) { x = rand () % 3; y = rand () % 3; temp = Hole[x]; Hole[x] = Hole[y]; Hole[y] = temp; } int PlayerGuess; printf ( "You may now guess the hole in which Rat is present: " ); scanf ( "%d" , &PlayerGuess); if (Hole[PlayerGuess - 1] == 'R' ) { (*inhand_cash) += 2 * amount_bet; printf ( "You win ! The holes are as follows: " ); printf ( ""%c %c %c" " , Hole[0], Hole[1], Hole[2]); printf ( "Your inhand_cash is now = %d " , *inhand_cash); } else { (*inhand_cash) -= amount_bet; printf ( "You Loose ! The holes are as follows: " ); printf ( ""%c %c %c" " , Hole[0], Hole[1], Hole[2]); printf ( "Your inhand_cash is now = %d " , *inhand_cash); } } int main() { int amount_bet, inhand_cash; /* You have to guess the hole in which the Rat is hidden among three holes The hole in which Rat is present is named as 'R' and rest two are named as 'N' If your guess is wrong, you loose the amount_bet from your inhand_cash If you guess it right, you win twice the amount_bet in your inhand_cash Keep playing and keep winning until you go out of cash */ printf ( "----Enter the inhand_cash you have right now---- : " ); scanf ( "%d" , &inhand_cash); while (inhand_cash > 0) { printf ( "Enter the amount_bet you want to play for : " ); scanf ( "%d" , &amount_bet); if (inhand_cash == 0 || amount_bet > inhand_cash) break ; GuessGame(amount_bet, &inhand_cash); } if (inhand_cash == 0 || amount_bet > inhand_cash) { printf ( """ " :slightly_frowning_face: Sorry you don't have enough cash to play more, " ); printf ( "Do come next time"" "" ); printf ( "Thank You for playing :slightly_smiling_face: " ); } return 0; } |
注: 此输出不是从联机编译器获取的 输出:
----Enter the inhand_cash you have right now---- : 1 Enter the amount_bet you want to play for : 1 Wait !! Rat is shuffling its position... You may now guess the hole in which Rat is present: 1 You Loose ! The holes are as follows: "N N R" Your inhand_cash is now = 0 " :-( Sorry you don't have enough cash to play more, Do come next time" Thank You for playing :-)
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END