【问题标题】:This is my idea on roll dice in functions, is it good?这是我在函数中掷骰子的想法,好吗?
【发布时间】:2021-03-02 02:57:50
【问题描述】:

为一个名为双骰子的游戏编写代码。

每位玩家轮流掷两个骰子。 (所以,玩家一掷 2 个骰子,然后玩家 2 掷两个骰子)。掷骰子时,玩家 1 按数字 1,玩家 2 按数字 2。骰子数从 1 到 6。如果两个骰子的总和 = 12,则该玩家是赢家 如果两个骰子的总和 = 10,则玩家获得一个金色令牌 2 个金色令牌,而任何玩家的总和未达到 12 将自动使该玩家获胜。创建一个模块来检查获胜者并输出获胜者是谁。

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define Roll 2

// Function Declarition
void winner(int [], int []);

int main()
{
    int player1[Roll], player2[Roll], p1sum=0, p2sum=0;
    int i, j, dice, p1[0], p2[0];
    
    srand(time(0));
    
    // Prompts Player 1 to press enter.
    printf("\n  Player 1: Press Enter to roll your dice!!!\n");
    getc(stdin);// collects the propmt.
    
    // 
    for(i = 0; i < Roll; i++)
    {
        player1[i] = (rand() % 6) + 1;
        p1sum += player1[i];
    }
    printf("\t Player 1 rolled %d dice\n\t The Sum of the two rolls are: %d\n", i + 0, p1sum);
    
    printf("\n  Player 2: Press Enter to roll your dice!!!\n");
    getc(stdin);
    for(j = 0; j < Roll; j++)
    {
        player2[j] = (rand() % 6) + 1;
        p2sum += player2[j];
    }
    printf("\t Player 2 rolled %d dice\n\t The Sum of the two rolls are: %d\n", j + 0, p2sum);
    
    // initializing an array to variable p1sum.
    
    
    // Function Call.
    winner(p1sum, p2sum);
    
    return 0;
}



void winner(int p1sum [], int p2sum [])
{
    int x, w;
    //int p1sum = p1[0];
    //int p2sum = p2[0];
    
    p1sum[0];
    p2sum[0];
    
    for (w=0; w < Roll; w++)
    {
        if (p1sum == 12)
        {
            printf("\nPlayer 1, You've Won the prize");
        }
        else if (p2sum == 12)
        {
            printf("\nPlayer 2, You've Won the prize");
        }
        else if (p1sum == 10)
        {
            printf("\nPlayer 1 gets a golden token");
        }
        else if (p2sum == 10)
        {
            printf("\nPlayer 2 gets a golden token");
        }
    }
    
}

【问题讨论】:

  • 制作掷骰子的方法int rollDice(int rollCount)。当两个玩家都得到 12 时,为什么 1 是赢家?不是领带吗? 10 岁也是如此。
  • 哦,因为第一个到 12 的人获胜,玩家可以滚动两次,我意识到会有平局的可能性
  • 我知道如何回滚但不知道语法。
  • 您可以通过运行它并查看它是否有效来判断它是否良好。 好不好?不是我们可以在这里回答的问题。本网站是针对您在代码或编程工具方面遇到的具体问题的问题。 我写了这段代码。好不好?不是问题的问题。
  • 您可以使用这个 stackexchange 站点 - codereview.stackexchange.com 进行代码审查。当您陷入编程困境时,Stack Overflow 可以提供帮助。但这个网站可能有更好的代码审查员。

标签: arrays c function


【解决方案1】:

制作方法如:

int rollDice(int rollCount);
boolean findWinner(int score1, int score2);

然后编写如下代码:

int sum1,sum2;
do {
   sum1 = rollDice(2);
   sum2 = rollDice(2);
}while(!findWinner(sum1, sum2))

【讨论】:

  • 哦,我明白你的意思了,谢谢你的提示。
  • IMO,获胜者不能是布尔值。有 3 种可能性 - 玩家 1 获胜,玩家 2 获胜,平局。
猜你喜欢
  • 1970-01-01
  • 2021-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-08
  • 2015-12-09
  • 2023-03-28
  • 2014-10-07
相关资源
最近更新 更多