## Posted By

iloveitaly on 12/02/10

# Basic Implementation of Game Theory's Minimax

/ Published in: JavaScript

`// pure strategy: [[2,4],[6,5]]// mixed strategy: [[3,1],[2,4]] var gameMatrix = [[2,4],[6,5]];var rowCount = gameMatrix.length;var columnCount = gameMatrix[0].length; // an accuracy measure; anymore than 1000 will crash modern browsersvar steps = 1000; // mutual payoff function function M(u, s) {	var expectedPayoff = 0; 	for(var i = 0; i < rowCount; i++) {		for(var j = 0; j < columnCount; j++) {			expectedPayoff += u[i] * s[j] * gameMatrix[i][j];		}	} 	return expectedPayoff} var insideMin = 100000, outsideMax = -100000;var nashEquilibrium = [[], []]; // minimax implementation (i.e. finding security value) for(x = 0; x < steps + 1; x++) {	for(y = 0; y < steps; y++) {		var prevMin = insideMin;		var payoff = M([x/steps, 1-x/steps], [y/steps, 1-y/steps])		insideMin = Math.min(insideMin, payoff); 		// this is for recording the nash equilibrium value		// a new local min != a global maximum; must check both		if(prevMin != insideMin && outsideMax != Math.max(insideMin, outsideMax)) {			nashEquilibrium[1] = [y/steps, 1-y/steps];		}	} 	var prevMax = outsideMax;	outsideMax = Math.max(insideMin, outsideMax); 	if(prevMax != outsideMax || outsideMax == insideMin) {		nashEquilibrium[0] = [x/steps, 1-x/steps];	} 	// reset the local minimum	insideMin = 100000;} document.write('minimax: ' + outsideMax + "<br/>" +  'nash eq: ((' +	nashEquilibrium[0][0] + ", " + nashEquilibrium[0][1] + "), (" +	nashEquilibrium[1][0] + ", " + nashEquilibrium[1][1] + "))");`