All pastes #824700 Raw Edit

Miscellany

public text v1 · immutable
#824700 ·published 2007-12-20 04:03 UTC
rendered paste body
a#include <iostream.h>
#include <stdlib.h>

// pegs game[11]
// game[10] = original code
// game[9-0] attempts and result

struct pegs{
	char peg[4];
	int white, black;
};

bool verify(char x[4]){
	bool valid = false;
	int i = 0;
	for(i; i < 4; i++){
		valid = false;

		if(x[i] == 'r')
			valid = true;
		if(x[i] == 'g')
			valid = true;
		if(x[i] == 'b')
			valid = true;
		if(x[i] == 'y')
			valid = true;
		if(x[i] == 'o')
			valid = true;
	}
	return valid;
}

void getcode(char peg[4]){
	cout << "(r)ed, (b)lue, (o)range, (y)ellow, (g)reen" << endl;
	do{
		cout << "type in your code, seperated by spaces: ";
		cin >> peg[0] >> peg[1] >> peg[2] >> peg[3];
	}
	while(!verify(peg));
		
}

void initialize(pegs game[11]){
	int i = 0, j = 0;
	
	cout << "Make sure the code breaker isnt looking!" << endl;
	getcode(game[10].peg);
	
	for(i = 0; i < 10; i++){

		for(j = 0; j < 4; j++)
			game[i].peg[j] = '.';
		
		game[i].black = 0;
		game[i].white = 0;
	}
}




void printmm(pegs game[11]){
    int i = 9, j = 0;
    for(i; i >= 0; i--){
        cout << "row " << i << " ";
		j = 0;
		for(j; j < 4; j++)
			cout << "| " << game[i].peg[j] << " ";
		
		cout << " :: " << game[i].black << " | " << game[i].white << endl;
	}
}



int indexof(char x, char *y){
	int size, i = 0;
	size = sizeof(y)/sizeof(*y) - 1;
	
	while(i < size && x != y[i])
		i++;
		
	return i;
}

// problems problems problems
// take out comments, it kinda works
void compare(pegs code, pegs &guess){
	int i = 0, c = 0;
	char ref[5] = {'r','b','o','y','g'};
	int colors[2][5] = {{0,0,0,0,0},{0,0,0,0,0}};
	// codes (0)red, (1)blue, (2)orange, (3)yellow, (4)green
	// users (0)red, (1)blue, (2)orange, (3)yellow, (4)green

	for(i = 0; i < 4; i++){
		if(code.peg[i] == guess.peg[i])
			guess.black++;
		else{
			colors[0][indexof(code.peg[i], ref)]++;
			colors[1][indexof(guess.peg[i], ref)]++;
		}
	}

	// count up each color
	// figure out how to do this without foreach
	for(i = 0; i < 5; i++){
		if(colors[0][i] + colors[1][i] != 0){
			
			if(colors[0][i] <= colors[1][i])
				guess.white += colors[0][i];
			else
				guess.white += colors[1][i];
		}
	}
}

void play(){
	pegs game[11];
	int turn = 0;
	bool victory = false;

	system("cls");
	initialize(game);
	

	while(!victory && turn < 10){
		system("cls");
		printmm(game);
		getcode(game[turn].peg);
		compare(game[10], game[turn]);
		if(game[turn].black == 4)
			victory = true;
		else
			turn++;
	}

	if(victory){
		cout << "congrats" << endl;
	}
	else{
		cout << "too bad" << endl;
	}
	
}

int menu(){
	bool repeat = true;
	do{
		int choice;

		cout << "1. play" << endl << "2. exit" << endl;
		cin >> choice;

		if(choice == 1)
			play();
		else
			repeat = false;

	}
	while(repeat);

	return 0;
}

int main(){
	menu();
	return 0;
}