【发布时间】:2021-05-06 21:40:49
【问题描述】:
我正在制作一个石头剪刀布游戏,在玩家玩够之前有重赛选项,如果玩家想停止玩,他只需键入“N”退出循环,但我的似乎不会工作,无论玩家输入如何,它都会不断重新匹配
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int regles(char joueur, char cpu) // rules of rock paper scissor "p" = rock, "f" = paper, c = scissor
{
if (joueur == cpu) // if player == cpu its a draw
{
return 2;
}
if ((joueur == 'p' && cpu == 'c') || (joueur == 'f' && cpu == 'p') || (joueur == 'c' && cpu == 'f')) // player victory case
{
return 0;
}
if ((joueur == 'p' && cpu == 'f') || (joueur == 'f' && cpu == 'c') || (joueur == 'c' && cpu == 'p')) // player defeat case
{
return 1;
}
}
int f_random(int max) // using s_rand and time to have a random number each time for the cpu to use to play
{
time_t seconds;
int result;
seconds = time(0);
srand(seconds);
result = rand() % max;
return result;
}
char f_jeu_cpu() // cpu "choosing" his move
{
int n;
char cpu;
n = f_random(100);
if (n < 33)
{
cpu = 'p';
}
else if (n > 33 && n < 66)
{
cpu = 'f';
}
else
{
cpu = 'c';
}
return cpu;
}
char f_jeu_joueur() // player input
{
while ( getchar ( ) != '\n' );
char joueur;
printf("Entrez p pour PIERRE, f pour FEUILLE, c pour CISEAUX ");
scanf("%c", &joueur);
return joueur;
}
int f_affichage(int resultat, char joueur, char cpu) // result display
{
if (resultat == 2)
{
printf("egalité\n"); // draw
}
else if (resultat == 0)
{
printf("vous remportez la partie\n"); // player win
}
else
{
printf("Vous perdez la partie\n"); // player defeat
}
printf("Vous avez choisi %c et l'ordi a choisi %c \n", joueur, cpu); // display player and cpu choice
return 0;
}
int main()
{
char joueur, cpu;
int resultat;
int affichage;
char choix;
while(1) // while loop for a rematch
{
printf("Voulez vous rejouer?\n"); // ask for a rematch
scanf("%c", &choix);
if (&choix == "N")
{
break;
}
joueur = f_jeu_joueur();
cpu = f_jeu_cpu();
resultat = regles(joueur, cpu);
affichage = f_affichage(resultat, joueur, cpu);
}
}
知道为什么会这样吗?
【问题讨论】:
-
if (&choix == "N")->if (choix == 'N')您可能还想使用" %c"作为格式字符串来读取字符,假设您希望它跳过前导空格。 -
您应该只调用一次
srand(),而不是每次需要随机数时。您的游戏解决方案很奇怪; CPU 将为值 33 和 67 到 99 选择“Ciseaux”(34% 的机会);显然人类每次都应该选择“皮埃尔”!除此之外,这个游戏还有一个简单得多的解决方案。 stackoverflow.com/questions/60309066/…,其中如果用值 0、1、2 表示游戏,则结果为battle = ((human - computer) + 3) % 3 ;,其中battle= 0 到 2 分别代表平局、人类获胜、计算机获胜。
标签: c if-statement comparison break