this post was submitted on 06 Jun 2023
7 points (100.0% liked)

General Programming Discussion

7792 readers
8 users here now

A general programming discussion community.

Rules:

  1. Be civil.
  2. Please start discussions that spark conversation

Other communities

Systems

Functional Programming

Also related

founded 5 years ago
MODERATORS
 

I've been working on re-implementing a board game in C. However, when running the players positions don't increment.
Current output:

 6,  9,  7,  6,  5,  5,  8,  7
 6,  9,  7,  6,  5,  5,  8,  7

Expected output:

 6,  9,  7,  6,  5,  5,  8,  7
14, 15, 19, 16, 13, 13, 14, 17

Code:

#include <stdlib.h>
#include <stdio.h>

// Define types here:
typedef enum {false, true} bool;

// Define constants here:
const unsigned char MAXPLAYERS = 7;	//Game has max of 8 players
const unsigned char SPACES = 40;	//Board has 40 spaces
const unsigned int SEED = 51732;	//Seed for random numbers
const unsigned int DIE = 6;		//Number of sides of die

// Define variables here:
unsigned char player = 0;
unsigned char player_position [] = {0, 0, 0, 0, 0, 0, 0, 0};
unsigned char die = 0;

// Define functions here:
// Moves player Input spaces.
void move_player (char moves) {

player_position [player] += moves;
if (player_position [player] > SPACES) {

	player_position [player] -= SPACES;

}

}

// Switches active player in order.
void increment_player () {

player ++;

if (player > MAXPLAYERS) {

player = 0;

}

}

// Returns random number between 1 - Input.
unsigned char rand_num (unsigned char max) {

unsigned char i;

i = rand () % max + 1;

return (i);

}

// Sets dice variable && returns 1 if double.
bool roll_dice () {

unsigned char a = rand_num (DIE);
unsigned char b = rand_num (DIE);

die = a + b;

return (0);

}

// Main logic
int main () {

char input = 0;

srand (SEED);
printf ("Game client started.\n",
	"Press enter to iterate turns.\n");

while (1) {

scanf ("%c", &input);

for (unsigned char i; i <= MAXPLAYERS; i++) {

	roll_dice ();
	move_player (die);

	increment_player ();

}

printf ("%2i, %2i, %2i, %2i, %2i, %2i, %2i, %2i\n",
	player_position [0], player_position [1], player_position [2],
	player_position [3], player_position [4], player_position [5],
	player_position [6], player_position [7]);

}

return (0);

}
top 2 comments
sorted by: hot top controversial new old
[–] OsrsNeedsF2P@lemmy.ml 4 points 1 year ago (1 children)

You're not resetting your loop counter on for (unsigned char i; i <= MAXPLAYERS; i++)

[–] sparkingcircuit@lemmygrad.ml 2 points 1 year ago* (last edited 1 year ago)

That fixed it! Thank you! I had forgotten that counter was persistent.

load more comments
view more: next ›