如何在c中为数组中的元素赋值?

时间:2014-12-09 03:50:06

标签: c arrays

我尝试过二维数组,改变了原型功能,而且我似乎无法为这个游戏实现一个得分系统。关于我能做什么的任何想法?我想从这段代码中获取输出,这些代码是来自1-6的6个不同的数字,并为它们分配一个我可以加起来得分的值。防爆。如果我掷1,那将值100分。什么是将点值分配给滚动值的最快最有效的方法?

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

int main() {

    int i, r, diceRoll;
    char player1[20];
    int temp, swapped;
    int roll1[6];

    srand(time(NULL));

    printf("Enter name for Player 1:\n");
    scanf(" %s", &player1);

    for(i = 0; i < 6; i ++) {
        r = ( rand() % 6 ) + 1;
        diceRoll= r; 
        roll1[i] = diceRoll;
    }

    while(1) {
        swapped = 0;
        for( i = 0; i < 6-1; i++ ) { 

            if( roll1[i] > roll1[i + 1] ) {

                temp = roll1[i];
                roll1[i  ] = roll1[i+1];
                roll1[i+1] = temp;
                swapped = 1;
            }
        }//for

        if( swapped == 0) {
            break; 
        }
    }//while
    printf("\n\n %s's Dice Roll:\n\n", player1); // prints out the dice rolls of player 1
    return 0;
}//main

1 个答案:

答案 0 :(得分:2)

为什么不对映射到相应点值的值进行直接聚合? (除非直接100 *滚动值,在这种情况下更容易。)

int score = 0;
for( i = 0; i < 6; ++i )
{
    switch( roll1[i] )
    {
    case 1: score += 100; break;
    case 2: score += 230; break;
    case 3: score += 540; break;
    case 4: score += 2320; break;
    case 5: score += 13130; break;
    case 6: score += 454260; break;  /* Of course, change to the score you want for each value. */
    }
}
printf("\n\n %s's Dice Roll:%d\n\n", player1, score);

&#34;我最初的想法是让游戏像Farkle一样,其中1是100分,5是50分,其他一切都是0,直到你得到3分(三分三分= 300分,三分1分)是1000等)。任何意见都将非常感谢&#34;有很多方法。您可以轻松地执行此操作,并使用Chux映射方法作为基础和三种类型。

int score = 0;
int face_score = 0;
int base_points[6] = { 100, 0, 0, 0, 50, 0 };
int three_of_a_kind_points[6] = { 300, 200, 300, 400, 500, 600 };
int four_of_a_kind_points[6] = { 
int repeat_counter[6] = { 0, 0, 0, 0, 0, 0 }; 
int kind_mask = 0;
int pair_count = 0;
int three_of_a_kind_count = 0;
int four_of_a_kind_count = 0;
for( i = 0; i < 6; ++i ) 
{
    kind_mask |= 1 << ( roll1[i] - 1 );
    switch( ++repeat_counter[roll1[i] - 1] )
    {
    case 1: break;
    case 2: ++pair_count; break;
    case 3: score = three_of_a_kind_points[rolli[i] - 1]; ++three_of_a_kind_count; break;
    case 4: score = 1000; ++four_of_a_kind_count; break;
    case 5: score = 2000; break;
    case 6: score = 3000; break;
    }
}

if( pair_count == 3 ) /* Three pairs */
    score = 1500;
else if( three_of_a_kind_count == 2 ) /* Two three of a kinds */
    score = 2500;
else if( four_of_a_kind && ( pair_count == 2 ) ) /* A four of a kind and one pair (2 because four of a kind counted as a pair in the aggregation phase) */
    score = 1500;
else if( kind_mask = 0x2F ) /* One of each type */
    score = 1500; /* Straight */
else if( !score )  /* score only 1's and 5's */
    score = repeat_counter[0] * 100 + repeat_counter[4] * 50;
printf("\n\n %s's Dice Roll:%d\n\n", player1, score);

我没有编译或运行此代码,因此可能不是100%正确。