All pastes #826028 Raw Edit

mastermind

public cpp v1 · immutable
#826028 ·published 2007-12-20 23:18 UTC
rendered paste body
#include <iostream.h>#include <stdlib.h>#include <time.h>// pegs game[11]// game[10] = original code// game[9-0] attempts and resultstruct pegs{	char peg[4];	int white, black;};int indexof(char x, char *y){	int size, i = 0;	size = sizeof(y)/sizeof(*y);		while(i < size && x != y[i])		i++;			return i;}bool verify(char x[4]){	bool valid = true;	char ref[5] = {'r','b','o','y','g'};	int i = 0;	while(i < 4 && valid == true){		if(ref[indexof(x[i], ref)] != x[i])			valid = false;		i++;	}	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], bool ai){	int i = 0, j = 0;	char ref[5] = {'r','b','o','y','g'};		if(ai){	srand(time(NULL));	for(i = 0; i < 4; i++)		game[10].peg[i] = ref[rand() % 5];	}	else{		cout << "Make sure the codebreaker 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;		system("cls");    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;	}}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}};	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)]++;		}	}	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(bool ai){	pegs game[11];	int turn = 0;	bool victory = false;	system("cls");	initialize(game, ai);		while(!victory && turn < 10){		printmm(game);		getcode(game[turn].peg);		compare(game[10], game[turn]);		if(game[turn].black == 4)			victory = true;		else			turn++;					printmm(game);	}	if(victory){		cout << "congrats" << endl;	}	else{		cout << "too bad" << endl;	}	}void rules(){	system("cls");	cout << "how to play: " << endl		 << "coming to a theatre near you" << endl;}int menu(){	bool repeat = true;	do{		int choice;		cout << "1. player vs player" << endl			 << "2. player vs computer" << endl			 << "3. rules" << endl			 << "4. exit" << endl;		cin >> choice;		switch(choice){			case 2:				play(true);				break;			case 3:				rules();				break;			case 4:				repeat = false;				break;			default:				play(false);				break;		}	}	while(repeat);	return 0;}int main(){	menu();	return 0;}