<commit_before>//
// Transam specific javascript
//
var transam = new function() {

	// disable an element
	this.disable_element = function(id) {
		$('#' + id).attr('disabled', 'disabled');
	};
	// enable an element
	this.enable_element = function(id) {
		$('#' + id).removeAttr('disabled');
	};
	// test if an element is blank
	this.is_blank = function(elem_id) {
		var len = actual_string_length(elem_id);
		return len == 0;
	};

	// Fix the page footer to the bottom of the page
	this.fix_page_footer = function(footer_div) {

		var docHeight = $(window).height();
   		var footerHeight = $(footer_div).height();
   		var footerTop = $(footer_div).position().top + footerHeight;
   		//alert(docHeight + "," + footerHeight + "," + footerTop);
   		if (footerTop < docHeight) {
    		$(footer_div).css('margin-top', (docHeight - footerTop) + 'px');
   			//alert("Adjusted: " + docHeight + "," + footerHeight + "," + footerTop);
   		}
	};

	// validate a file size
	this.validate_file_size = function(inputFile, max_file_size_mb) {
		var warning_message = "This file exceeds the maximum allowed file size (" + max_file_size_mb + " MB). Please select a smaller file.";
		var max_bytes = max_file_size_mb * 1048576;
	  	$.each(inputFile.files, function() {
	  		// alert('File Size = ' + this.size + ' Max File Size = ' + max_file_size);
	  		if (this.size && max_bytes && this.size > parseInt(max_bytes)) {
	  			// Show a warning message using the popup message provider
		    	show_popup_message('Warning', warning_message, 'warning');
		    	$(inputFile).val('');
	  		}
	  	});
	};
	// Show a popup message in the UI
	var show_popup_message = function(title, message, type) {
		var class_name = 'alert alert-info';
		if (type == 'error') {
			class_name = 'alert alert-danger';
		} else if (type == 'warning') {
			class_name = 'alert alert-warning';
		}
		$.gritter.add({
			title: title,
			class_name: class_name,
			text: message
		});
	};

	// Converts a table to a datatable
	this.render_data_table = function(div_id, filter) {
		$("#" + div_id).dataTable( {
			"bFilter" : filter,
			"bLengthChange" : true,
			"bProcessing" : true,
			"sDom": "<'row'<'col-xs-6'l><'col-xs-6'f>r>t<'row'<'col-xs-6'i><'col-xs-6'p>>",
			"sPaginationType": "bootstrap",
			"oLanguage": {
				"sLengthMenu": "_MENU_ records per page"
			},
			"fnDrawCallback": function( oSettings ) {
	      		transam.install_quick_link_handlers();
	    	}
		} );
	};

	// Draws a google char based on the chart data and chart options passed in
	this.draw_chart = function(div_id, chart_type, chart_options, chart_data) {

		var container = document.getElementById(div_id);
		if (container == null) {
			return;
		}
		var chart = null;
		if (chart_type === 'area') {
			chart = new google.visualization.AreaChart(container);
		} else if (chart_type === 'bar') {
			chart = new google.visualization.BarChart(container);
		} else if (chart_type === 'column') {
			chart = new google.visualization.ColumnChart(container);
		} else if (chart_type === 'combo') {
			chart = new google.visualization.ComboChart(document.getElementById(div_id));
		} else if (chart_type === 'histogram') {
			chart = new google.visualization.Histogram(document.getElementById(div_id));
		} else if (chart_type === 'line') {
			chart = new google.visualization.LineChart(document.getElementById(div_id));
		} else if (chart_type === 'pie') {
			chart = new google.visualization.PieChart(document.getElementById(div_id));
		} else if (chart_type === 'scatter') {
			chart = new google.visualization.ScatterChart(document.getElementById(div_id));
		}
		if (chart) {
			chart.draw(chart_data, chart_options);
		}
	};

  	// Load a block of html in the background
  	this.load_ajax_panel = function(div_id, url, method, loader_panel) {
    	$.ajax({
	    	type: method,
        	url: url,
        	cache: false,
        	beforeSend:function() {
          		if (loader_panel) {
            		$("#" + div_id).html(loader_panel);
          		}
        	},
        	//success: function(html) {
          	//	$("#" + div_id).empty();
          	//	$("#" + div_id).append(html);
        	//},
			error: function (data) {
	      		show_error_message(div_id, "We are sorry but something went wrong. Please try again.");
	      	}
    	});
  	};

	this.ajax_render_action = function(url, method) {
		$.ajax({
	    	type: method,
	      	url: url,
	      	beforeSend:function(){
	        	// this is where we append a loading image
	    		//$('#ajax-panel').html('

');
	  		},
	  		success:function(data){
			    // successful request; do something with the data
			    //$('#ajax-panel').empty();
			    //$(data).find('item').each(function(i){
			    //  $('#ajax-panel').append('
' + $(this).find('title').text() + '

' + $(this).find('link').text() + '
');
			    //});
			},
			error: function (data) {
	      		show_alert("We are sorry but something went wrong. Please try again.");
	      	}
	   	});
	};

	//
	// session based variable storage for UI key/value pairs
	//
	// get a key value, if the key does not exist the default value is returned
	this.get_ui_key_value = function(key, default_val) {
	    var value;
	    try {
	        value = window.sessionStorage.getItem(key);
	    } catch(e) {
	        value = default_val;
	    }
		//alert('getting value for ' + key + '; val = ' + value);
	    return value;
	};

	// Set a key value. Keys must be unique strings
	this.set_ui_key_value = function(key, value) {
		//alert('setting value for ' + key + ' to ' + value);
	    window.sessionStorage.setItem(key, value);
	};

	// Used to remove any existing banner messages
	this.remove_messages = function() {
		$('.alert').alert('close');
	};

	this.enable_date_pickers = function() {
		// Use jquery to render date pickers for all datepicker input classes
		$('.datepicker').datepicker({
			 format: 'mm-dd-yyyy'
		});
	};

	// Finds all the class elements on a page and sets the min-height css variable
	// to the maximum height of all the containers
	this.make_same_height = function(class_name) {

		// remove any existing min-height attributes
		$(class_name).css({'height' : ''});

		// Set the form parts to equal height
		var max = -1;
		$(class_name).each(function() {
			var h = $(this).height();
			//alert(h);
			max = h > max ? h : max;
		});
		max += 10;
		$(class_name).css({'height': max});
	};

	// Finds all elements marked as info icons and turns them into popups
	this.enable_info_popups = function(class_name) {
		$(class_name).popover({
			trigger: 'hover',
			container: 'body',
    		animation: 'true',
    		html: 'true'
		});
	};

	this.install_quick_link_handlers = function() {
		// Enable the quick links
		$('[data-action-path]').click(function() {
			var url = $(this).data('action-path');
			document.location.href = url;
		});
	};

	// Hides dropdown button if the dropdown is empty
	this.hide_empty_dropdown = function () {
		var btn = $("button.btn[data-toggle='dropdown']");
		var dropdown = btn.siblings("ul");
		if (dropdown.children().length === 0) {
			btn.hide();
		}
	}

	// Internal functions
	var show_error_message = function(div_id, message) {
		$("#" + div_id).empty();
        $("#" + div_id).append('
' + message + '
');
	};
	var actual_string_length = function(elem_id) {
		var val = $("#" + elem_id).val();
		var len = $.trim(val).length;
		return len;
	};
};

<commit_msg>renames parameter for transam.make_same_height to reflect behavior<commit_after>//
// Transam specific javascript
//
var transam = new function() {

	// disable an element
	this.disable_element = function(id) {
		$('#' + id).attr('disabled', 'disabled');
	};
	// enable an element
	this.enable_element = function(id) {
		$('#' + id).removeAttr('disabled');
	};
	// test if an element is blank
	this.is_blank = function(elem_id) {
		var len = actual_string_length(elem_id);
		return len == 0;
	};

	// Fix the page footer to the bottom of the page
	this.fix_page_footer = function(footer_div) {

		var docHeight = $(window).height();
   		var footerHeight = $(footer_div).height();
   		var footerTop = $(footer_div).position().top + footerHeight;
   		//alert(docHeight + "," + footerHeight + "," + footerTop);
   		if (footerTop < docHeight) {
    		$(footer_div).css('margin-top', (docHeight - footerTop) + 'px');
   			//alert("Adjusted: " + docHeight + "," + footerHeight + "," + footerTop);
   		}
	};

	// validate a file size
	this.validate_file_size = function(inputFile, max_file_size_mb) {
		var warning_message = "This file exceeds the maximum allowed file size (" + max_file_size_mb + " MB). Please select a smaller file.";
		var max_bytes = max_file_size_mb * 1048576;
	  	$.each(inputFile.files, function() {
	  		// alert('File Size = ' + this.size + ' Max File Size = ' + max_file_size);
	  		if (this.size && max_bytes && this.size > parseInt(max_bytes)) {
	  			// Show a warning message using the popup message provider
		    	show_popup_message('Warning', warning_message, 'warning');
		    	$(inputFile).val('');
	  		}
	  	});
	};
	// Show a popup message in the UI
	var show_popup_message = function(title, message, type) {
		var class_name = 'alert alert-info';
		if (type == 'error') {
			class_name = 'alert alert-danger';
		} else if (type == 'warning') {
			class_name = 'alert alert-warning';
		}
		$.gritter.add({
			title: title,
			class_name: class_name,
			text: message
		});
	};

	// Converts a table to a datatable
	this.render_data_table = function(div_id, filter) {
		$("#" + div_id).dataTable( {
			"bFilter" : filter,
			"bLengthChange" : true,
			"bProcessing" : true,
			"sDom": "<'row'<'col-xs-6'l><'col-xs-6'f>r>t<'row'<'col-xs-6'i><'col-xs-6'p>>",
			"sPaginationType": "bootstrap",
			"oLanguage": {
				"sLengthMenu": "_MENU_ records per page"
			},
			"fnDrawCallback": function( oSettings ) {
	      		transam.install_quick_link_handlers();
	    	}
		} );
	};

	// Draws a google char based on the chart data and chart options passed in
	this.draw_chart = function(div_id, chart_type, chart_options, chart_data) {

		var container = document.getElementById(div_id);
		if (container == null) {
			return;
		}
		var chart = null;
		if (chart_type === 'area') {
			chart = new google.visualization.AreaChart(container);
		} else if (chart_type === 'bar') {
			chart = new google.visualization.BarChart(container);
		} else if (chart_type === 'column') {
			chart = new google.visualization.ColumnChart(container);
		} else if (chart_type === 'combo') {
			chart = new google.visualization.ComboChart(document.getElementById(div_id));
		} else if (chart_type === 'histogram') {
			chart = new google.visualization.Histogram(document.getElementById(div_id));
		} else if (chart_type === 'line') {
			chart = new google.visualization.LineChart(document.getElementById(div_id));
		} else if (chart_type === 'pie') {
			chart = new google.visualization.PieChart(document.getElementById(div_id));
		} else if (chart_type === 'scatter') {
			chart = new google.visualization.ScatterChart(document.getElementById(div_id));
		}
		if (chart) {
			chart.draw(chart_data, chart_options);
		}
	};

  	// Load a block of html in the background
  	this.load_ajax_panel = function(div_id, url, method, loader_panel) {
    	$.ajax({
	    	type: method,
        	url: url,
        	cache: false,
        	beforeSend:function() {
          		if (loader_panel) {
            		$("#" + div_id).html(loader_panel);
          		}
        	},
        	//success: function(html) {
          	//	$("#" + div_id).empty();
          	//	$("#" + div_id).append(html);
        	//},
			error: function (data) {
	      		show_error_message(div_id, "We are sorry but something went wrong. Please try again.");
	      	}
    	});
  	};

	this.ajax_render_action = function(url, method) {
		$.ajax({
	    	type: method,
	      	url: url,
	      	beforeSend:function(){
	        	// this is where we append a loading image
	    		//$('#ajax-panel').html('

');
	  		},
	  		success:function(data){
			    // successful request; do something with the data
			    //$('#ajax-panel').empty();
			    //$(data).find('item').each(function(i){
			    //  $('#ajax-panel').append('
' + $(this).find('title').text() + '

' + $(this).find('link').text() + '
');
			    //});
			},
			error: function (data) {
	      		show_alert("We are sorry but something went wrong. Please try again.");
	      	}
	   	});
	};

	//
	// session based variable storage for UI key/value pairs
	//
	// get a key value, if the key does not exist the default value is returned
	this.get_ui_key_value = function(key, default_val) {
	    var value;
	    try {
	        value = window.sessionStorage.getItem(key);
	    } catch(e) {
	        value = default_val;
	    }
		//alert('getting value for ' + key + '; val = ' + value);
	    return value;
	};

	// Set a key value. Keys must be unique strings
	this.set_ui_key_value = function(key, value) {
		//alert('setting value for ' + key + ' to ' + value);
	    window.sessionStorage.setItem(key, value);
	};

	// Used to remove any existing banner messages
	this.remove_messages = function() {
		$('.alert').alert('close');
	};

	this.enable_date_pickers = function() {
		// Use jquery to render date pickers for all datepicker input classes
		$('.datepicker').datepicker({
			 format: 'mm-dd-yyyy'
		});
	};

	// Finds all the class elements on a page and sets the min-height css variable
	// to the maximum height of all the containers
	this.make_same_height = function(jquery_selector) {

		// remove any existing min-height attributes
		$(jquery_selector).css({'height' : ''});

		// Set the form parts to equal height
		var max = -1;
		$(jquery_selector).each(function() {
			var h = $(this).height();
			//alert(h);
			max = h > max ? h : max;
		});
		max += 10;
		$(jquery_selector).css({'height': max});
	};

	// Finds all elements marked as info icons and turns them into popups
	this.enable_info_popups = function(class_name) {
		$(class_name).popover({
			trigger: 'hover',
			container: 'body',
    		animation: 'true',
    		html: 'true'
		});
	};

	this.install_quick_link_handlers = function() {
		// Enable the quick links
		$('[data-action-path]').click(function() {
			var url = $(this).data('action-path');
			document.location.href = url;
		});
	};

	// Hides dropdown button if the dropdown is empty
	this.hide_empty_dropdown = function () {
		var btn = $("button.btn[data-toggle='dropdown']");
		var dropdown = btn.siblings("ul");
		if (dropdown.children().length === 0) {
			btn.hide();
		}
	}

	// Internal functions
	var show_error_message = function(div_id, message) {
		$("#" + div_id).empty();
        $("#" + div_id).append('
' + message + '
');
	};
	var actual_string_length = function(elem_id) {
		var val = $("#" + elem_id).val();
		var len = $.trim(val).length;
		return len;
	};
};

<|endoftext|>


<commit_before>module.exports = {

    VERSION: "Please JS, please STAPHHH",

    bet_request: function(game_state, bet) {

        try {

            var cards = getMyCards(game_state),
                player = getMyPlayer(game_state),
                myBet = 1,
                trans = {
                    "1": 1,
                    "2": 2,
                    "3": 3,
                    "4": 4,
                    "5": 5,
                    "6": 6,
                    "7": 7,
                    "8": 8,
                    "9": 9,
                    "10": 10,
                    "J": 11,
                    "Q": 12,
                    "K": 13,
                    "A": 14
                },
                x = trans[cards[0].rank],
                y = trans[cards[1].rank],
                c1 = cards[0].suit,
                c2 = cards[1].suit,
                cardsDown = game_state.community_cards,
                ranks = {
                    "NIMNIC": 0,
                    "PAIR": 1,
                    "TWO_PAIRS": 2,
                    "THREE_OF_A_KIND": 3,
                    "STRAIGHT": 4,
                    "FLUSH": 5,
                    "FULL_HOUSE": 6,
                    "FOUR_OF_A_KIND": 7,
                    "ROYAL_FLUSH": 8
                };

            // OPENING HAND
            // The cards are equal
            myBet = 0;
            if (cardsDown.length === 0) {
                if (x === y) {
                    if (x > 8) {
                        myBet = player.stack;
                    }
                }
            }
            if (cardsDown.length >= 3) {
                var rank = getRanks(cardsDown, cards, ranks);
                if (rank >= 2) {
                    myBet = player.stack;
                }
            }
           /* if (cardsDown.length === 0) {
                if (x === y) {
                    myBet = bid(game_state, 4);
                    if (x > 9) {
                        myBet = player.stack;
                    }
                } else if (c2 === c1) {
                    if (otherPLayerbet < player.stack / 9) {
                        myBet = call(game_state) ;
                    }
                    if (Math.abs(x - y) < 4) {
                        myBet = bid(game_state, 10);
                    }
                }
                if (Math.abs(x - y) < 4 &&
                    x + y > 13 ) {
                    if (otherPLayerbet < player.stack / 9) {
                        myBet = call(game_state) ;
                    }
                }

            } else if (cardsDown.length >= 3) {
                var rank = getRanks(cardsDown, cards, ranks);
                console.log('RANK: ', rank);
                console.log('CARDS: ', cards);
                console.log('CARDSDown: ', cardsDown);
                myBet = call(game_state);
                switch (rank) {
                    case 8:
                        myBet = player.stack -1;
                        break;
                    case 7:
                        myBet = player.stack -1 ;
                        break;
                    case 6:
                        myBet = player.stack -1 ;
                        break;
                    case 5:
                        myBet = player.stack - 1;
                        break;
                    case 4:
                        myBet = player.stack -1 ;
                        break;
                    case 3:
                        myBet = player.stack -1;
                        break;
                    case 2:
                        myBet = bid(game_state, 4);
                        break;
                    case 1:
                        if (x > 11) {
                            myBet = bid(game_state, 10);
                        } else {
                            myBet = call(game_state);
                        }
                        break;
                    default:
                       myBet = minRaise(game_state);
                }

            }

            console.log(cards[0]);
            console.log(cards[1]);
            console.log("My bet is : " + myBet);*/
            bet(parseInt(myBet));

        } catch (ex) {
            console.log("Caught exception: " + ex);
        }

        function getMyCards(game_state) {

            var cards_down = game_state.community_cards;
            var players = game_state.players;

            var nrOfPlayers = players.length;
            for (var i = 0; i < nrOfPlayers; i++) {
                if (players[i].name == 'Comfortable Pugs') {
                    return players[i].hole_cards;
                }
            }

        };

        function getMyPlayer(game_state) {
            var players = game_state.players;

            var nrOfPlayers = players.length;
            for (var i = 0; i < nrOfPlayers; i++) {
                if (players[i].name == 'Comfortable Pugs') {
                    return players[i];
                }
            }
        }

        function bid(gameState, raise) {
            var call = gameState.current_buy_in - gameState.players[gameState.in_action]['bet'],
                minRaise = call + gameState.minimum_raise + player.stack / raise;
            console.log("CALL IS : ", call);
            console.log("Raise : ", minRaise);
            console.log("minraise : ", gameState.minimum_raise);
            console.log("Current By IN", gameState.current_buy_in);
            console.log("The fuck is this", gameState.players[gameState.in_action]['bet']);
            return minRaise > player.stack ? player.stack : minRaise ;
        }

        function minRaise(gameState) {
            var call = gameState.current_buy_in - gameState.players[gameState.in_action]['bet'],
                minRaise = call + gameState.minimum_raise;
            return minRaise;
        }

        function call(gameState) {
            var call = gameState.current_buy_in - gameState.players[gameState.in_action]['bet'];
            return call;
        }

        function getRanks(cardsDown, hand, ranks) {
            var cards = cardsDown.concat(hand),
                cardsDownNr = cards.length,
                numbers = {
                    "1":  0,
                    "2":  0,
                    "3":  0,
                    "4":  0,
                    "5":  0,
                    "6":  0,
                    "7":  0,
                    "8":  0,
                    "9":  0,
                    "10": 0,
                    "J":  0,
                    "Q":  0,
                    "K":  0,
                    "A":  0
                },
                color = {
                    "diamonds": 0,
                    "spades":   0,
                    "hearts":   0,
                    "clubs":    0
                },
                card = null;

            for (var i = 0; i < cardsDownNr; i++) {
                card = cards[i];
                numbers[card.rank] = numbers[card.rank] + 1;
                color[card.suit] = color[card.suit] + 1;
            }

            for (var key in numbers) {
                if (numbers[key] == 4) {
                    return ranks["FOUR_OF_A_KIND"];
                }
            }

            for (var key in color) {
                if (color[key] > 4) {
                    return ranks["FLUSH"];
                }
            }
             console.log("Numbers ",numbers);
            console.log("Colors ",color);
            var threeOfAKind = false;
            for (var key in numbers) {
                if (numbers[key] == 3) {
                    threeOfAKind = true;
                }
            }
            var pairs = 0;
            for (var key in numbers) {
                if (numbers[key] > 1) {
                    pairs++;
                }
            }
            if (threeOfAKind) {
                if (pairs > 1) {
                    return ranks["FULL_HOUSE"];
                }

                return ranks["THREE_OF_A_KIND"];
            }

            if (pairs > 1) {
                return ranks["TWO_PAIRS"];
            }
            if (pairs == 1) {
                return ranks["PAIR"];
            }

            return 0;
        }

    },

    showdown: function(game_state) {

    }

};<commit_msg>Easy win 3<commit_after>module.exports = {

    VERSION: "Please JS, please STAPHHH",

    bet_request: function(game_state, bet) {

        try {

            var cards = getMyCards(game_state),
                player = getMyPlayer(game_state),
                myBet = 1,
                trans = {
                    "1": 1,
                    "2": 2,
                    "3": 3,
                    "4": 4,
                    "5": 5,
                    "6": 6,
                    "7": 7,
                    "8": 8,
                    "9": 9,
                    "10": 10,
                    "J": 11,
                    "Q": 12,
                    "K": 13,
                    "A": 14
                },
                x = trans[cards[0].rank],
                y = trans[cards[1].rank],
                c1 = cards[0].suit,
                c2 = cards[1].suit,
                cardsDown = game_state.community_cards,
                ranks = {
                    "NIMNIC": 0,
                    "PAIR": 1,
                    "TWO_PAIRS": 2,
                    "THREE_OF_A_KIND": 3,
                    "STRAIGHT": 4,
                    "FLUSH": 5,
                    "FULL_HOUSE": 6,
                    "FOUR_OF_A_KIND": 7,
                    "ROYAL_FLUSH": 8
                };

            // OPENING HAND
            // The cards are equal
            myBet = 0;
            if (cardsDown.length === 0) {
                if (x === y) {
                    if (x > 8) {
                        myBet = player.stack;
                    }
                }
                if (x + y > 24) {
                    myBet = player.stack / 4;
                }
            }
            if (cardsDown.length >= 3) {
                var rank = getRanks(cardsDown, cards, ranks);
                if (rank >= 2) {
                    myBet = player.stack;
                }
                if (x + y > 24) {
                    myBet = player.stack;
                }
            }
           /* if (cardsDown.length === 0) {
                if (x === y) {
                    myBet = bid(game_state, 4);
                    if (x > 9) {
                        myBet = player.stack;
                    }
                } else if (c2 === c1) {
                    if (otherPLayerbet < player.stack / 9) {
                        myBet = call(game_state) ;
                    }
                    if (Math.abs(x - y) < 4) {
                        myBet = bid(game_state, 10);
                    }
                }
                if (Math.abs(x - y) < 4 &&
                    x + y > 13 ) {
                    if (otherPLayerbet < player.stack / 9) {
                        myBet = call(game_state) ;
                    }
                }

            } else if (cardsDown.length >= 3) {
                var rank = getRanks(cardsDown, cards, ranks);
                console.log('RANK: ', rank);
                console.log('CARDS: ', cards);
                console.log('CARDSDown: ', cardsDown);
                myBet = call(game_state);
                switch (rank) {
                    case 8:
                        myBet = player.stack -1;
                        break;
                    case 7:
                        myBet = player.stack -1 ;
                        break;
                    case 6:
                        myBet = player.stack -1 ;
                        break;
                    case 5:
                        myBet = player.stack - 1;
                        break;
                    case 4:
                        myBet = player.stack -1 ;
                        break;
                    case 3:
                        myBet = player.stack -1;
                        break;
                    case 2:
                        myBet = bid(game_state, 4);
                        break;
                    case 1:
                        if (x > 11) {
                            myBet = bid(game_state, 10);
                        } else {
                            myBet = call(game_state);
                        }
                        break;
                    default:
                       myBet = minRaise(game_state);
                }

            }

            console.log(cards[0]);
            console.log(cards[1]);
            console.log("My bet is : " + myBet);*/
            bet(parseInt(myBet));

        } catch (ex) {
            console.log("Caught exception: " + ex);
        }

        function getMyCards(game_state) {

            var cards_down = game_state.community_cards;
            var players = game_state.players;

            var nrOfPlayers = players.length;
            for (var i = 0; i < nrOfPlayers; i++) {
                if (players[i].name == 'Comfortable Pugs') {
                    return players[i].hole_cards;
                }
            }

        };

        function getMyPlayer(game_state) {
            var players = game_state.players;

            var nrOfPlayers = players.length;
            for (var i = 0; i < nrOfPlayers; i++) {
                if (players[i].name == 'Comfortable Pugs') {
                    return players[i];
                }
            }
        }

        function bid(gameState, raise) {
            var call = gameState.current_buy_in - gameState.players[gameState.in_action]['bet'],
                minRaise = call + gameState.minimum_raise + player.stack / raise;
            console.log("CALL IS : ", call);
            console.log("Raise : ", minRaise);
            console.log("minraise : ", gameState.minimum_raise);
            console.log("Current By IN", gameState.current_buy_in);
            console.log("The fuck is this", gameState.players[gameState.in_action]['bet']);
            return minRaise > player.stack ? player.stack : minRaise ;
        }

        function minRaise(gameState) {
            var call = gameState.current_buy_in - gameState.players[gameState.in_action]['bet'],
                minRaise = call + gameState.minimum_raise;
            return minRaise;
        }

        function call(gameState) {
            var call = gameState.current_buy_in - gameState.players[gameState.in_action]['bet'];
            return call;
        }

        function getRanks(cardsDown, hand, ranks) {
            var cards = cardsDown.concat(hand),
                cardsDownNr = cards.length,
                numbers = {
                    "1":  0,
                    "2":  0,
                    "3":  0,
                    "4":  0,
                    "5":  0,
                    "6":  0,
                    "7":  0,
                    "8":  0,
                    "9":  0,
                    "10": 0,
                    "J":  0,
                    "Q":  0,
                    "K":  0,
                    "A":  0
                },
                color = {
                    "diamonds": 0,
                    "spades":   0,
                    "hearts":   0,
                    "clubs":    0
                },
                card = null;

            for (var i = 0; i < cardsDownNr; i++) {
                card = cards[i];
                numbers[card.rank] = numbers[card.rank] + 1;
                color[card.suit] = color[card.suit] + 1;
            }

            for (var key in numbers) {
                if (numbers[key] == 4) {
                    return ranks["FOUR_OF_A_KIND"];
                }
            }

            for (var key in color) {
                if (color[key] > 4) {
                    return ranks["FLUSH"];
                }
            }
             console.log("Numbers ",numbers);
            console.log("Colors ",color);
            var threeOfAKind = false;
            for (var key in numbers) {
                if (numbers[key] == 3) {
                    threeOfAKind = true;
                }
            }
            var pairs = 0;
            for (var key in numbers) {
                if (numbers[key] > 1) {
                    pairs++;
                }
            }
            if (threeOfAKind) {
                if (pairs > 1) {
                    return ranks["FULL_HOUSE"];
                }

                return ranks["THREE_OF_A_KIND"];
            }

            if (pairs > 1) {
                return ranks["TWO_PAIRS"];
            }
            if (pairs == 1) {
                return ranks["PAIR"];
            }

            return 0;
        }

    },

    showdown: function(game_state) {

    }

};<|endoftext|>


<commit_before>gPlayer = {
  x: 0,
  y: 0,
  xVel: 0,
  yVel: 0,
  rad: 0,
  size: 20,
  speed: PLAYER_SPEED,
  allowFire: true,
  projectiles: [],
  life: PLAYER_LIFE,
  fire: function() {
    if (this.allowFire) {
      this.projectiles.push(new Bolt(this));
      this.allowFire = false;
      gAudio.startBolt();
      setTimeout(function() { this.allowFire = true }.bind(this), Bolt.delay);
    }
  },
  collide: function(other) {
    var rayToCenter = Math.sqrt(Math.pow(other.x - this.x, 2) + Math.pow(other.y - this.y, 2));
    var collide = rayToCenter < this.size;

    if (!collide) {
      var lastX = this.x - this.xVel;
      var lastY = this.y - this.yVel;
      var lastRay = Math.sqrt(Math.pow(this.x - lastX, 2) + Math.pow(this.y - lastY, 2));
      collide = Math.sqrt(Math.pow(rayToCenter, 2) + Math.pow(lastRay)) < other.size;
    }

    return collide;
  },
  update: function() {
    if (this.life >= PLAYER_LIFE) {
      var xAcc = 0;
      var yAcc = 0;
      this.xVel *= FRICTION;
      this.yVel *= FRICTION;
      if (gInput.isActive('thrust')) {
        this.speed = THRUSTER_SPEED;
        xAcc = Math.cos(this.rad);
        yAcc = Math.sin(this.rad);
      }
      else {
        this.speed = PLAYER_SPEED;
        if (gInput.isActive('left')) xAcc--;
        if (gInput.isActive('right')) xAcc++;
        if (gInput.isActive('up')) yAcc--;
        if (gInput.isActive('down')) yAcc++;
      }
      this.xVel += xAcc;
      this.yVel += yAcc;

      var collision;
      for (var i in gScene.targets) {
        collision = this.collide(gScene.targets[i]);
        if (collision) {
          this.xVel *= -1;
          this.yVel *= -1;
          break;
        }
      }

      if (Math.abs(this.xVel) < 0.01) this.xVel = 0;
      if (Math.abs(this.yVel) < 0.01) this.yVel = 0;

      this.x = Math.min(Math.min(gCamera.x + SCREEN_WIDTH, gScene.bounds.r) - 20, Math.max(Math.max(gCamera.x, gScene.bounds.l) + 20, this.x + this.xVel * this.speed));
      this.y = Math.min(Math.min(gCamera.y + SCREEN_HEIGHT, gScene.bounds.b) - 20, Math.max(Math.max(gCamera.y, gScene.bounds.t) + 20, this.y + this.yVel * this.speed));

      this.rad = Math.atan2(gInput.mouseY - (this.y - gCamera.y), gInput.mouseX - (this.x - gCamera.x));

      if (gInput.isActive('fire')) this.fire();
    }
    else this.life--;
    // Loop through projectiles and only keep the ones still in the level bounds
    var liveProjectiles = [];
    this.projectiles.forEach(function(p) {
      var collision;
      for (var i in gScene.targets) {
        collision = p.collide(gScene.targets[i]);
        if (collision) break;
      }
      if (!collision && gScene.bounds.collide(p)) p.dying = true;
      p.update();
      if (p.life > 0) liveProjectiles.push(p);
    });
    this.projectiles = liveProjectiles;
  },
  render: function() {
    var opacity = decToHex(255 * (this.life / PLAYER_LIFE));
    renderPath([
      ['moveTo', PLAYER_RADIUS * Math.cos(this.rad), PLAYER_RADIUS * Math.sin(this.rad)],
      ['lineTo', (PLAYER_RADIUS / 2) * Math.cos(this.rad + (Math.PI / 4)), (PLAYER_RADIUS / 2) * Math.sin(this.rad + (Math.PI / 4))],
      ['lineTo', PLAYER_RADIUS * Math.cos(this.rad + (Math.PI / 2)), PLAYER_RADIUS * Math.sin(this.rad + (Math.PI / 2))],
      ['lineTo', (PLAYER_RADIUS * 1.25) * Math.cos(this.rad + (Math.PI * 3 / 4)), (PLAYER_RADIUS * 1.25) * Math.sin(this.rad + (Math.PI * 3 / 4))],
      ['lineTo', (PLAYER_RADIUS / 2) * Math.cos(this.rad + Math.PI), (PLAYER_RADIUS / 2) * Math.sin(this.rad + Math.PI)],
      ['lineTo', (PLAYER_RADIUS * 1.25) * Math.cos(this.rad - (Math.PI * 3 / 4)), (PLAYER_RADIUS * 1.25) * Math.sin(this.rad - (Math.PI * 3 / 4))],
      ['lineTo', PLAYER_RADIUS * Math.cos(this.rad - (Math.PI / 2)), PLAYER_RADIUS * Math.sin(this.rad - (Math.PI / 2))],
      ['lineTo', (PLAYER_RADIUS / 2) * Math.cos(this.rad - (Math.PI / 4)), (PLAYER_RADIUS / 2) * Math.sin(this.rad - (Math.PI / 4))],
    ], true, this.x - gCamera.x, this.y - gCamera.y);

    fill('#4499DD' + opacity);
    stroke('#FFBB77' + opacity, 3);

    if (this.life < PLAYER_LIFE) {
      var radius = Math.log10(Math.max(1, 10 * (1 - (this.life / PLAYER_LIFE)))) * PLAYER_LIFE;
      renderPath([
        ['moveTo', 0, radius],
        ['arc', 0, 0, radius, 0, 2 * Math.PI],
        ['moveTo', 3, 7 + (2 * radius / 3)],
        ['arc', 3, 7, 2 * radius / 3, 0, 2 * Math.PI],
        ['moveTo', -12, -3 + (2 * radius / 3)],
        ['arc', -12, -3, 2 * radius / 3, 0, 2 * Math.PI],
        ['moveTo', 10, -6 + (2 * radius / 3)],
        ['arc', 10, -6, 2 * radius / 3, 0, 2 * Math.PI],
      ], true, this.x - gCamera.x, this.y - gCamera.y);
      fill(this.life < PLAYER_LIFE / 2 ? '#CCCCCC' + decToHex(255 * (this.life / (PLAYER_LIFE / 2))) : '#EEE');
    }
  }
}
<commit_msg>Kill Shard on collision with player projectile<commit_after>gPlayer = {
  x: 0,
  y: 0,
  xVel: 0,
  yVel: 0,
  rad: 0,
  size: 20,
  speed: PLAYER_SPEED,
  allowFire: true,
  projectiles: [],
  life: PLAYER_LIFE,
  fire: function() {
    if (this.allowFire) {
      this.projectiles.push(new Bolt(this));
      this.allowFire = false;
      gAudio.startBolt();
      setTimeout(function() { this.allowFire = true }.bind(this), Bolt.delay);
    }
  },
  collide: function(other) {
    var rayToCenter = Math.sqrt(Math.pow(other.x - this.x, 2) + Math.pow(other.y - this.y, 2));
    var collide = rayToCenter < this.size;

    if (!collide) {
      var lastX = this.x - this.xVel;
      var lastY = this.y - this.yVel;
      var lastRay = Math.sqrt(Math.pow(this.x - lastX, 2) + Math.pow(this.y - lastY, 2));
      collide = Math.sqrt(Math.pow(rayToCenter, 2) + Math.pow(lastRay)) < other.size;
    }

    return collide;
  },
  update: function() {
    if (this.life >= PLAYER_LIFE) {
      var xAcc = 0;
      var yAcc = 0;
      this.xVel *= FRICTION;
      this.yVel *= FRICTION;
      if (gInput.isActive('thrust')) {
        this.speed = THRUSTER_SPEED;
        xAcc = Math.cos(this.rad);
        yAcc = Math.sin(this.rad);
      }
      else {
        this.speed = PLAYER_SPEED;
        if (gInput.isActive('left')) xAcc--;
        if (gInput.isActive('right')) xAcc++;
        if (gInput.isActive('up')) yAcc--;
        if (gInput.isActive('down')) yAcc++;
      }
      this.xVel += xAcc;
      this.yVel += yAcc;

      var collision;
      for (var i in gScene.targets) {
        collision = this.collide(gScene.targets[i]);
        if (collision) {
          this.xVel *= -1;
          this.yVel *= -1;
          break;
        }
      }

      if (Math.abs(this.xVel) < 0.01) this.xVel = 0;
      if (Math.abs(this.yVel) < 0.01) this.yVel = 0;

      this.x = Math.min(Math.min(gCamera.x + SCREEN_WIDTH, gScene.bounds.r) - 20, Math.max(Math.max(gCamera.x, gScene.bounds.l) + 20, this.x + this.xVel * this.speed));
      this.y = Math.min(Math.min(gCamera.y + SCREEN_HEIGHT, gScene.bounds.b) - 20, Math.max(Math.max(gCamera.y, gScene.bounds.t) + 20, this.y + this.yVel * this.speed));

      this.rad = Math.atan2(gInput.mouseY - (this.y - gCamera.y), gInput.mouseX - (this.x - gCamera.x));

      if (gInput.isActive('fire')) this.fire();
    }
    else this.life--;
    // Loop through projectiles and only keep the ones still in the level bounds
    var liveProjectiles = [];
    this.projectiles.forEach(function(p) {
      var collision;
      for (var i in gScene.targets) {
        collision = p.collide(gScene.targets[i]);
        if (collision) break;
      }
      if (!collision) {
        for (var i in gScene.shards) {
          if (p.collide(gScene.shards[i])) {
            if (gScene.shards[i].life == SHARD_LIFE) gScene.shards[i].life--;
            collision = true;
            break;
          }
        }
      }
      if (!collision && gScene.bounds.collide(p)) p.dying = true;
      p.update();
      if (p.life > 0) liveProjectiles.push(p);
    });
    this.projectiles = liveProjectiles;
  },
  render: function() {
    var opacity = decToHex(255 * (this.life / PLAYER_LIFE));
    renderPath([
      ['moveTo', PLAYER_RADIUS * Math.cos(this.rad), PLAYER_RADIUS * Math.sin(this.rad)],
      ['lineTo', (PLAYER_RADIUS / 2) * Math.cos(this.rad + (Math.PI / 4)), (PLAYER_RADIUS / 2) * Math.sin(this.rad + (Math.PI / 4))],
      ['lineTo', PLAYER_RADIUS * Math.cos(this.rad + (Math.PI / 2)), PLAYER_RADIUS * Math.sin(this.rad + (Math.PI / 2))],
      ['lineTo', (PLAYER_RADIUS * 1.25) * Math.cos(this.rad + (Math.PI * 3 / 4)), (PLAYER_RADIUS * 1.25) * Math.sin(this.rad + (Math.PI * 3 / 4))],
      ['lineTo', (PLAYER_RADIUS / 2) * Math.cos(this.rad + Math.PI), (PLAYER_RADIUS / 2) * Math.sin(this.rad + Math.PI)],
      ['lineTo', (PLAYER_RADIUS * 1.25) * Math.cos(this.rad - (Math.PI * 3 / 4)), (PLAYER_RADIUS * 1.25) * Math.sin(this.rad - (Math.PI * 3 / 4))],
      ['lineTo', PLAYER_RADIUS * Math.cos(this.rad - (Math.PI / 2)), PLAYER_RADIUS * Math.sin(this.rad - (Math.PI / 2))],
      ['lineTo', (PLAYER_RADIUS / 2) * Math.cos(this.rad - (Math.PI / 4)), (PLAYER_RADIUS / 2) * Math.sin(this.rad - (Math.PI / 4))],
    ], true, this.x - gCamera.x, this.y - gCamera.y);

    fill('#4499DD' + opacity);
    stroke('#FFBB77' + opacity, 3);

    if (this.life < PLAYER_LIFE) {
      var radius = Math.log10(Math.max(1, 10 * (1 - (this.life / PLAYER_LIFE)))) * PLAYER_LIFE;
      renderPath([
        ['moveTo', 0, radius],
        ['arc', 0, 0, radius, 0, 2 * Math.PI],
        ['moveTo', 3, 7 + (2 * radius / 3)],
        ['arc', 3, 7, 2 * radius / 3, 0, 2 * Math.PI],
        ['moveTo', -12, -3 + (2 * radius / 3)],
        ['arc', -12, -3, 2 * radius / 3, 0, 2 * Math.PI],
        ['moveTo', 10, -6 + (2 * radius / 3)],
        ['arc', 10, -6, 2 * radius / 3, 0, 2 * Math.PI],
      ], true, this.x - gCamera.x, this.y - gCamera.y);
      fill(this.life < PLAYER_LIFE / 2 ? '#CCCCCC' + decToHex(255 * (this.life / (PLAYER_LIFE / 2))) : '#EEE');
    }
  }
}
<|endoftext|>


<commit_before>/**
 * (C) Copyright 2012, 2013, 2014 Scott Jaderholm
 *
 * Use, modification, and distribution are subject to the terms
 * specified in the COPYING file.

 * Description: Conkeror page-mode for controlling media players on
 * websites like Youtube, Grooveshark, etc.

**/

require("content-buffer.js");

define_keymap("player_keymap", $display_name = "player");

var player_click_element = function(I, selector, error_message) {
    var elem = I.buffer.document.querySelector(selector);
    if (elem) {
        dom_node_click(elem, 1, 1);
    } else {
        I.minibuffer.message(error_message);
    }
};

var player_command = function(command, error_message) {
    return function (I) {
        var site = player_get_current_site(I);
        if (site) {
            var selector = player_button_selectors[site][command];
            if (selector) {
                if (selector instanceof Function) {
                    selector(I);
                } else {
                    player_click_element(I, selector, error_message);
                }
            } else {
                I.minibuffer.message("Command not implemented for this site.");
            }
        } else {
            I.minibuffer.message("Current url not recognized as a supported site.");
        }
    };
};

// test with:
// get_recent_conkeror_window().buffers.current.page.local.player_current_site
define_variable("player_current_site", null,
    "Name of the current site used to look up things like button ids.");

var player_site_from_url = function(url) {
    for (var site in player_url_tests) {
        var test = player_url_tests[site];
        if (test instanceof RegExp) {
            if (test.exec(url)) {
                return site;
            }
        } else if ((test instanceof Function) && (test(url))) {
            return site;
        }
    }
    return null;
};

var player_get_current_site = function(I) {
    var local = I.buffer.page.local;
    var uri = I.buffer.current_uri;
    if (local.player_current_site == null) {
        local.player_current_site = player_site_from_url(uri.spec);
    }
    return local.player_current_site;
};

// Map of site names to regexes or functions that match their url
// Ex: {"bandcamp": /bandcamp\.com/}
var player_url_tests = {};

// Map of site names to a map of commands to selectors/functions
// Ex: {"bandcamp": {"play": ".play-btn"}}
var player_button_selectors = {};

interactive("player-play-or-pause",
            "Click the play/pause button.",
            player_command("play",
                           "No play or pause button found"));

interactive("player-mute",
            "Click the mute button.",
            player_command("mute",
                           "No mute button found"));

interactive("player-previous",
            "Click the previous button.",
            player_command("previous",
                           "No previous button found"));

interactive("player-next",
            "Click the next button.",
            player_command("next",
                           "No next button found"));

interactive("player-fullscreen",
            "Click the fullscreen button.",
            player_command("fullscreen",
                           "No fullscreen button found"));

define_key(player_keymap, "C-c C-return", "player-play-or-pause");
define_key(player_keymap, "C-c C-m", "player-mute");
define_key(player_keymap, "C-c C-n", "player-next");
define_key(player_keymap, "C-c C-p", "player-previous");
define_key(player_keymap, "C-c C-f", "player-fullscreen");

define_keymaps_page_mode("player-mode",
    [],
    { normal: player_keymap },
    $display_name = "Player");

var def_player_site = function (site_name, site_url, button_selectors) {
    player_url_tests[site_name] = site_url;
    player_button_selectors[site_name] = button_selectors;
    player_mode.test.push(player_url_tests[site_name]);
};

/* ------------------------------
   8tracks
   Test url: http://8tracks.com/moose92/suits-stetsons
   ------------------------------ */

def_player_site("8tracks",
                build_url_regexp($domain = "8tracks", $allow_www = true),
                {"play": ".i-play, .i-pause",
                 "next": ".i-skip",
                 "mute": ".volume-mute"});

/* ------------------------------
   Amazon CloudPlayer and MP3 Store
   Test url: https://www.amazon.com/gp/dmusic/mp3/player
   Test url: http://www.amazon.com/Cove-Weather/dp/B001D5796O/
   ------------------------------ */

def_player_site("amazon-cloudplayer",
                build_url_regexp($domain = "amazon", $allow_www = true),
                {"play": ".a-icon-play-all, .a-icon-pause-all, .mp3MasterPlay",
                 "previous": ".mp3PlayPrevious",
                 "next": ".mp3PlayNext",
                 "mute": player_amazon_mute});

function player_amazon_mute(I) {
    var elem = I.buffer.document.querySelector(".volumeControl .ui-slider-range");
    if (elem && elem.style.width == "0%") {
        player_click_element(I, "#fullVolume",
                             "No 'full volume' button found");
    }
    else {
        player_click_element(I, "#noVolume",
                             "No 'no volume' button found");
    }
}

/* ------------------------------
   Bandcamp
   Test url: http://sabzi.bandcamp.com/album/rainier
   ------------------------------ */

def_player_site("bandcamp",
                /bandcamp\.com/,
                {"play": ".playbutton, .play-btn",
                 "previous": ".prevbutton",
                 "next": ".nextbutton"});

/* ------------------------------
   Grooveshark
   Test url: http://grooveshark.com/#!/album/Cove/1545589
   ------------------------------ */

def_player_site("grooveshark",
                build_url_regexp($domain = "grooveshark", $allow_www = true),
                {"play": "#play-pause",
                 "mute": "#volume",
                 "previous": "#play-prev",
                 "next": "#play-next"});

/* ------------------------------
   Last.fm
   Test url: http://www.last.fm/listen/artist/GodWolf/similarartists
 ------------------------------ */
function player_lastfm_play(I) {
    var elem = I.buffer.document.querySelector("#radioControlPlay");
    if (elem && elem.offsetHeight == 0) {
        player_click_element(I, "#radioControlPause",
                             "No pause button found");
    }
    else {
        player_click_element(I, "#radioControlPlay",
                             "No play button found");
    }
}

def_player_site("lastfm",
                /last\.fm/,
                {"play": player_lastfm_play,
                 // mute doesn't work yet because it is in an iframe
                 // "mute": ".ytp-button-volume",
                 "next": "#radioControlSkip"});

/* ------------------------------
   Pandora
   ------------------------------ */

def_player_site("pandora",
                build_url_regexp($domain = "pandora", $allow_www = true),
                {"next": ".skipButton",
                 "play": player_pandora_play,
                 "mute": player_pandora_mute});

function player_pandora_play_button_is_visible (I) {
    var elem = I.buffer.document.querySelector(".playButton");
    return (elem && elem.style.display !== "none");
}

function player_pandora_play (I) {
    if (pandora_play_button_is_visible(I)) {
        player_click_element(I, ".playButton",
                             "No play button found");
    }else {
        player_click_element(I, ".pauseButton",
                             "No pause button found");
    }
}

// TODO Unmute doesn't work, I couldn't figure out how to unmute
// manually via JS even in Chrome Console
function player_pandora_mute (I) {
    var knob = I.buffer.document.querySelector(".volumeKnob");
    var clicker = I.buffer.document.querySelector(".volumeBar");
    if (knob && knob.style.left == "20.00px") {
        dom_node_click(clicker, 146, 1);
    } else {
        dom_node_click(clicker, 64, 1);
    }
}

/* ------------------------------
   rdio
   Test url: http://www.rdio.com/
   ------------------------------ */

def_player_site("rdio",
                build_url_regexp($domain = "rdio", $allow_www = true),
                {"play": ".play_pause",
                 "mute": ".Volume",
                 "previous": ".prev",
                 "next": ".next"});

/* ------------------------------
   SoundCloud
   Test url: https://soundcloud.com/perabhjot-grewal
   ------------------------------ */

def_player_site("soundcloud",
                build_url_regexp($domain = "soundcloud", $allow_www = true),
                {"play": ".playing, .playButton",
                 "mute": ".volume__togglemute",
                 "previous": ".prevbutton, .skipControl__previous",
                 "next": ".nextbutton, .skipControl__next"});

/* ------------------------------
   Twitter Music
   Test url: https://music.twitter.com/i/chart/popular
   ------------------------------ */

def_player_site("twitter",
                build_url_regexp($domain = "music.twitter"),
                {"play": ".player-play-pause",
                 "next": ".player-next"});

/* ------------------------------
   Youtube HTML5 Player
   Test url: http://www.youtube.com/watch?v=pPWcX-16A9Y
   ------------------------------ */

def_player_site("youtube-html5",
                build_url_regexp($domain = "youtube", $allow_www = true),
                {"play": ".ytp-button-pause, .ytp-button-play, .ytp-button-replay",
                 "mute": ".ytp-button-volume",
                 "fullscreen": ".ytp-button-fullscreen-enter, .ytp-button-fullscreen-exit"});

page_mode_activate(player_mode);

provide("player");

<commit_msg>Fix COPYING typo<commit_after>/**
 * (C) Copyright 2012, 2013, 2014 Scott Jaderholm
 *
 * Use, modification, and distribution are subject to the terms
 * specified in the LICENSE file.

 * Description: Conkeror page-mode for controlling media players on
 * websites like Youtube, Grooveshark, etc.

**/

require("content-buffer.js");

define_keymap("player_keymap", $display_name = "player");

var player_click_element = function(I, selector, error_message) {
    var elem = I.buffer.document.querySelector(selector);
    if (elem) {
        dom_node_click(elem, 1, 1);
    } else {
        I.minibuffer.message(error_message);
    }
};

var player_command = function(command, error_message) {
    return function (I) {
        var site = player_get_current_site(I);
        if (site) {
            var selector = player_button_selectors[site][command];
            if (selector) {
                if (selector instanceof Function) {
                    selector(I);
                } else {
                    player_click_element(I, selector, error_message);
                }
            } else {
                I.minibuffer.message("Command not implemented for this site.");
            }
        } else {
            I.minibuffer.message("Current url not recognized as a supported site.");
        }
    };
};

// test with:
// get_recent_conkeror_window().buffers.current.page.local.player_current_site
define_variable("player_current_site", null,
    "Name of the current site used to look up things like button ids.");

var player_site_from_url = function(url) {
    for (var site in player_url_tests) {
        var test = player_url_tests[site];
        if (test instanceof RegExp) {
            if (test.exec(url)) {
                return site;
            }
        } else if ((test instanceof Function) && (test(url))) {
            return site;
        }
    }
    return null;
};

var player_get_current_site = function(I) {
    var local = I.buffer.page.local;
    var uri = I.buffer.current_uri;
    if (local.player_current_site == null) {
        local.player_current_site = player_site_from_url(uri.spec);
    }
    return local.player_current_site;
};

// Map of site names to regexes or functions that match their url
// Ex: {"bandcamp": /bandcamp\.com/}
var player_url_tests = {};

// Map of site names to a map of commands to selectors/functions
// Ex: {"bandcamp": {"play": ".play-btn"}}
var player_button_selectors = {};

interactive("player-play-or-pause",
            "Click the play/pause button.",
            player_command("play",
                           "No play or pause button found"));

interactive("player-mute",
            "Click the mute button.",
            player_command("mute",
                           "No mute button found"));

interactive("player-previous",
            "Click the previous button.",
            player_command("previous",
                           "No previous button found"));

interactive("player-next",
            "Click the next button.",
            player_command("next",
                           "No next button found"));

interactive("player-fullscreen",
            "Click the fullscreen button.",
            player_command("fullscreen",
                           "No fullscreen button found"));

define_key(player_keymap, "C-c C-return", "player-play-or-pause");
define_key(player_keymap, "C-c C-m", "player-mute");
define_key(player_keymap, "C-c C-n", "player-next");
define_key(player_keymap, "C-c C-p", "player-previous");
define_key(player_keymap, "C-c C-f", "player-fullscreen");

define_keymaps_page_mode("player-mode",
    [],
    { normal: player_keymap },
    $display_name = "Player");

var def_player_site = function (site_name, site_url, button_selectors) {
    player_url_tests[site_name] = site_url;
    player_button_selectors[site_name] = button_selectors;
    player_mode.test.push(player_url_tests[site_name]);
};

/* ------------------------------
   8tracks
   Test url: http://8tracks.com/moose92/suits-stetsons
   ------------------------------ */

def_player_site("8tracks",
                build_url_regexp($domain = "8tracks", $allow_www = true),
                {"play": ".i-play, .i-pause",
                 "next": ".i-skip",
                 "mute": ".volume-mute"});

/* ------------------------------
   Amazon CloudPlayer and MP3 Store
   Test url: https://www.amazon.com/gp/dmusic/mp3/player
   Test url: http://www.amazon.com/Cove-Weather/dp/B001D5796O/
   ------------------------------ */

def_player_site("amazon-cloudplayer",
                build_url_regexp($domain = "amazon", $allow_www = true),
                {"play": ".a-icon-play-all, .a-icon-pause-all, .mp3MasterPlay",
                 "previous": ".mp3PlayPrevious",
                 "next": ".mp3PlayNext",
                 "mute": player_amazon_mute});

function player_amazon_mute(I) {
    var elem = I.buffer.document.querySelector(".volumeControl .ui-slider-range");
    if (elem && elem.style.width == "0%") {
        player_click_element(I, "#fullVolume",
                             "No 'full volume' button found");
    }
    else {
        player_click_element(I, "#noVolume",
                             "No 'no volume' button found");
    }
}

/* ------------------------------
   Bandcamp
   Test url: http://sabzi.bandcamp.com/album/rainier
   ------------------------------ */

def_player_site("bandcamp",
                /bandcamp\.com/,
                {"play": ".playbutton, .play-btn",
                 "previous": ".prevbutton",
                 "next": ".nextbutton"});

/* ------------------------------
   Grooveshark
   Test url: http://grooveshark.com/#!/album/Cove/1545589
   ------------------------------ */

def_player_site("grooveshark",
                build_url_regexp($domain = "grooveshark", $allow_www = true),
                {"play": "#play-pause",
                 "mute": "#volume",
                 "previous": "#play-prev",
                 "next": "#play-next"});

/* ------------------------------
   Last.fm
   Test url: http://www.last.fm/listen/artist/GodWolf/similarartists
 ------------------------------ */
function player_lastfm_play(I) {
    var elem = I.buffer.document.querySelector("#radioControlPlay");
    if (elem && elem.offsetHeight == 0) {
        player_click_element(I, "#radioControlPause",
                             "No pause button found");
    }
    else {
        player_click_element(I, "#radioControlPlay",
                             "No play button found");
    }
}

def_player_site("lastfm",
                /last\.fm/,
                {"play": player_lastfm_play,
                 // mute doesn't work yet because it is in an iframe
                 // "mute": ".ytp-button-volume",
                 "next": "#radioControlSkip"});

/* ------------------------------
   Pandora
   ------------------------------ */

def_player_site("pandora",
                build_url_regexp($domain = "pandora", $allow_www = true),
                {"next": ".skipButton",
                 "play": player_pandora_play,
                 "mute": player_pandora_mute});

function player_pandora_play_button_is_visible (I) {
    var elem = I.buffer.document.querySelector(".playButton");
    return (elem && elem.style.display !== "none");
}

function player_pandora_play (I) {
    if (pandora_play_button_is_visible(I)) {
        player_click_element(I, ".playButton",
                             "No play button found");
    }else {
        player_click_element(I, ".pauseButton",
                             "No pause button found");
    }
}

// TODO Unmute doesn't work, I couldn't figure out how to unmute
// manually via JS even in Chrome Console
function player_pandora_mute (I) {
    var knob = I.buffer.document.querySelector(".volumeKnob");
    var clicker = I.buffer.document.querySelector(".volumeBar");
    if (knob && knob.style.left == "20.00px") {
        dom_node_click(clicker, 146, 1);
    } else {
        dom_node_click(clicker, 64, 1);
    }
}

/* ------------------------------
   rdio
   Test url: http://www.rdio.com/
   ------------------------------ */

def_player_site("rdio",
                build_url_regexp($domain = "rdio", $allow_www = true),
                {"play": ".play_pause",
                 "mute": ".Volume",
                 "previous": ".prev",
                 "next": ".next"});

/* ------------------------------
   SoundCloud
   Test url: https://soundcloud.com/perabhjot-grewal
   ------------------------------ */

def_player_site("soundcloud",
                build_url_regexp($domain = "soundcloud", $allow_www = true),
                {"play": ".playing, .playButton",
                 "mute": ".volume__togglemute",
                 "previous": ".prevbutton, .skipControl__previous",
                 "next": ".nextbutton, .skipControl__next"});

/* ------------------------------
   Twitter Music
   Test url: https://music.twitter.com/i/chart/popular
   ------------------------------ */

def_player_site("twitter",
                build_url_regexp($domain = "music.twitter"),
                {"play": ".player-play-pause",
                 "next": ".player-next"});

/* ------------------------------
   Youtube HTML5 Player
   Test url: http://www.youtube.com/watch?v=pPWcX-16A9Y
   ------------------------------ */

def_player_site("youtube-html5",
                build_url_regexp($domain = "youtube", $allow_www = true),
                {"play": ".ytp-button-pause, .ytp-button-play, .ytp-button-replay",
                 "mute": ".ytp-button-volume",
                 "fullscreen": ".ytp-button-fullscreen-enter, .ytp-button-fullscreen-exit"});

page_mode_activate(player_mode);

provide("player");

<|endoftext|>


<commit_before>var fs = require('fs');

module.exports = {

  VERSION: "Crazy All In Bot",

  bet_request: function(game_state) {
    //return 50;
    //return bet_plus_blind(game_state, 2);
    return bet_strategy_by_score(game_state);
  },

  showdown: function(game_state) {
    try {
      fs.writeFile(game_state.game_id + '.' + game_state.round + '.game_state.json', JSON.stringify(game_state, null, 2), function (err) {
        //pass;
      });
    } catch (e) {
      //pass;
    }
  }

};

function bet_plus_blind(game_state, blinds) {
  var maxBet = game_state.small_blind * 2;
  game_state.players.forEach(function (p) {
    maxBet = Math.max(p.bet, maxBet);
  });
  return maxBet + game_state.small_blind * blinds - maxBet % game_state.small_blind;
}

RANK_SCORE = {
  "2": 1,
  "3": 2,
  "4": 3,
  "5": 4,
  "6": 5,
  "7": 6,
  "8": 7,
  "9": 8,
  "10": 9,
  "J": 10,
  "Q": 11,
  "K": 12,
  "A": 13
};

function bet_strategy_by_score(game_state) {
  try {
    players = game_state.players;
    sevenbits_bot = players.filter(function (player) {
      return player.name == 'sevenbits';
    })[0];
    our_cards = sevenbits_bot.hole_cards;
    score = score_cards(our_cards[0], our_cards[1]);
    if (score > 95) {
      return calculate_allowed_bet(game_state, sevenbits_bot, score);
    } else {
      return 0;
    }
  } catch (e) {
    console.log(e);
    return 0;
  }
}

function players_count(players){
    players_q = 0;
    for(i = 0; i < players.length; i ++){
        if (players[i]['status'] != 'out'){
            players_q ++;
        }
    }
    return players_q;
}

function score_cards(card1, card2) {
  score = RANK_SCORE[card1['rank']] * RANK_SCORE[card2['rank']];
  if (card1['rank'] == card2['rank']) {
    score = Math.max(score, 100);
  }
  if (card1['rank'] == "A" || card2['rank'] == "A") {
    score = Math.max(score, 100);
  }
  return score;
}

function calculate_allowed_bet(game_state, our_player, cards_score) {
  suggested_bet = bet_plus_blind(game_state, 3);
  our_stack = our_player.stack;
  pot = game_state.pot;
  if ((((suggested_bet/our_stack) - (cards_score / 169)) > 0.05) && (pot < our_stack * 0.66)) {
    return 0;
  } else {
    return suggested_bet;
  }
}
<commit_msg>better algo<commit_after>var fs = require('fs');

module.exports = {

  VERSION: "Crazy All In Bot",

  bet_request: function(game_state) {
    //return 50;
    //return bet_plus_blind(game_state, 2);
    return bet_strategy_by_score(game_state);
  },

  showdown: function(game_state) {
    try {
      fs.writeFile(game_state.game_id + '.' + game_state.round + '.game_state.json', JSON.stringify(game_state, null, 2), function (err) {
        //pass;
      });
    } catch (e) {
      //pass;
    }
  }

};

function bet_plus_blind(game_state, blinds) {
  var maxBet = game_state.small_blind * 2;
  game_state.players.forEach(function (p) {
    maxBet = Math.max(p.bet, maxBet);
  });
  return maxBet + game_state.small_blind * blinds - maxBet % game_state.small_blind;
}

RANK_SCORE = {
  "2": 1,
  "3": 2,
  "4": 3,
  "5": 4,
  "6": 5,
  "7": 6,
  "8": 7,
  "9": 8,
  "10": 9,
  "J": 10,
  "Q": 11,
  "K": 12,
  "A": 13
};

function bet_strategy_by_score(game_state) {
  try {
    players = game_state.players;
    sevenbits_bot = players.filter(function (player) {
      return player.name == 'sevenbits';
    })[0];
    our_cards = sevenbits_bot.hole_cards;
    score = score_cards(our_cards[0], our_cards[1]);
    return calculate_allowed_bet(game_state, sevenbits_bot, score, players);
  } catch (e) {
    console.log(e);
    return 0;
  }
}

function players_count(players){
    players_q = 0;
    for(i = 0; i < players.length; i ++){
        if (players[i]['status'] != 'out'){
            players_q ++;
        }
    }
    return players_q;
}

function score_cards(card1, card2) {
  var suit_match = card1.suit == card2.suit;
  var rank1 = RANK_SCORE[card1['rank']];
  var rank2 = RANK_SCORE[card2['rank']];
  var rank;
  if (RANK_SCORE[card2['rank']] > RANK_SCORE[card1['rank']]) {
    rank = [rank2, rank1];
  } else {
    rank = [rank1, rank2];
  }
  var score;
  if ((rank[0] == rank[1] && rank[0] >= 8) || (rank[0] == 13 && rank[1] >= 11)) {
    score = 5;
  } else if ((rank[0] == 13 && rank[1] >= 9) ||(rank[0] == 13 && suit_match)) {
    score = 4;
  } else if (suit_match && rank[0] >= 9 && rank[1] >= 8 ) {
    score = 3;
  } else if ((rank[0] >= 10 && rank[1] >= 9) || (suit_match && rank[0] >= 12 && rank[1] >= 3) ||
      (suit_match && rank[0] >= 9 && rank[1] >= 8)) {
    score = 2;
  } else if (suit_match && rank[0] >= 5 && rank[1] >= 4) {
    score = 1;
  } else {
    score = 0;
  }

  return score;
}

function calculate_allowed_bet(game_state, our_player, cards_score, players) {
  suggested_bet = bet_plus_blind(game_state, 3);
  our_stack = our_player.stack;
  pot = game_state.pot;
  num_of_players = players_count(players);
  if (num_of_players - cards_score > 1) {
    return 0;
  } else {
    return suggested_bet;
  }
}
<|endoftext|>


<commit_before>
module.exports = {

  VERSION: "Default JavaScript folding player",

  bet_request: function(game_state) {
    return 0;
  },

  showdown: function(game_state) {

  }
};
<commit_msg>bet 1<commit_after>var pkg = require('./package.json');

module.exports = {

  VERSION: pkg.version,

  bet_request: function(game_state) {
    return 1;
  },

  showdown: function(game_state) {

  }
};
<|endoftext|>


<commit_before>/**
 * SyntaxHighlighter
 * http://alexgorbatchev.com/SyntaxHighlighter
 *
 * SyntaxHighlighter is donationware. If you are using it, please donate.
 * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
 *
 * @version
 * 3.0.83 (July 02 2010)
 *
 * @copyright
 * Copyright (C) 2004-2010 Alex Gorbatchev.
 *
 * @license
 * Dual licensed under the MIT and GPL licenses.
 */
;(function()
{
	// CommonJS
	typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;

	function Brush()
	{
		var keywords =	'break case catch continue ' +
						'default delete do else false  ' +
						'for function if in instanceof ' +
						'new null return super switch ' +
						'this throw true try typeof var while with'
						;

		var r = SyntaxHighlighter.regexLib;

		this.regexList = [
			{ regex: r.multiLineDoubleQuotedString,					css: 'string' },			// double quoted strings
			{ regex: r.multiLineSingleQuotedString,					css: 'string' },			// single quoted strings
			{ regex: r.singleLineCComments,							css: 'comments' },			// one line comments
			{ regex: r.multiLineCComments,							css: 'comments' },			// multiline comments
			{ regex: /\s*#.*/gm,									css: 'preprocessor' },		// preprocessor tags like #region and #endregion
			{ regex: new RegExp(this.getKeywords(keywords), 'gm'),	css: 'keyword' }			// keywords
			];

		this.forHtmlScript(r.scriptScriptTags);
	};

	Brush.prototype	= new SyntaxHighlighter.Highlighter();
	Brush.aliases	= ['js', 'jscript', 'javascript'];

	SyntaxHighlighter.brushes.JScript = Brush;

	// CommonJS
	typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
<commit_msg>Fixed Taiga issue 130 (GitHub issue #20).<commit_after>/**
 * SyntaxHighlighter
 * http://alexgorbatchev.com/SyntaxHighlighter
 *
 * SyntaxHighlighter is donationware. If you are using it, please donate.
 * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
 *
 * @version
 * 3.0.83 (July 02 2010)
 *
 * @copyright
 * Copyright (C) 2004-2010 Alex Gorbatchev.
 *
 * @license
 * Dual licensed under the MIT and GPL licenses.
 */
;(function()
{
	// CommonJS
	typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;

	function Brush()
	{
		var keywords =	'break case catch continue ' +
						'default delete do else false  ' +
						'for function if in instanceof ' +
						'new null return super switch ' +
						'this throw true try typeof var while with'
						;

		var r = SyntaxHighlighter.regexLib;

		this.regexList = [
			// The following two lines were causing issues with single quotes.
			// { regex: r.multiLineDoubleQuotedString,					css: 'string' },			// double quoted strings
			// { regex: r.multiLineSingleQuotedString,					css: 'string' },			// single quoted strings
			{ regex: r.doubleQuotedString,					css: 'string' },			// double quoted strings
			{ regex: r.singleQuotedString,					css: 'string' },			// single quoted strings
			{ regex: r.singleLineCComments,							css: 'comments' },			// one line comments
			{ regex: r.multiLineCComments,							css: 'comments' },			// multiline comments
			{ regex: /\s*#.*/gm,									css: 'preprocessor' },		// preprocessor tags like #region and #endregion
			{ regex: new RegExp(this.getKeywords(keywords), 'gm'),	css: 'keyword' }			// keywords
			];

		this.forHtmlScript(r.scriptScriptTags);
	};

	Brush.prototype	= new SyntaxHighlighter.Highlighter();
	Brush.aliases	= ['js', 'jscript', 'javascript'];

	SyntaxHighlighter.brushes.JScript = Brush;

	// CommonJS
	typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
<|endoftext|>


<commit_before>/**
 * @typedef {Object} Node
 */

/**
 * @typedef {Object} GraphItem
 * @property {Node} node
 * @property {Array<Node>} deps
 */

/**
 * @typedef {Array<GraphItem>} Graph
 */

/**
 * Resolves dependency graph. Graph nodes and deps could be represent as any js type
 */
class GraphResolver {

    /**
     * @param {Graph} graph
     */
    constructor(graph) {

        GraphResolver.validate(graph)

        /**
         * Input graph
         * @type {Graph}
         */
        this.graph = graph

        /**
         * Helper structure that maps nodes to its deps
         * @type {Map}
         */
        this.graphToDepsMap = GraphResolver.makeNodeToDepsMap(graph)

        /**
         * Stack of nodes
         * @type {Array<Node>}
         */
        this.stack = this.graph.map(item => item.node)

        /**
         * Storage of nodes that were successfully resolved
         * @type {Set}
         */
        this.resolvedNodes = new Set()

        /**
         * Storage of nodes that were visited but at that moment they were unresolvable
         * @type {Set}
         */
        this.visitedNodes = new Set()

    }

    /**
     * Trying to resolve dependency graph
     * @throws {Error} if graph has cycled dependencies
     * @returns {Array<Node>}
     */
    resolve() {

        const { stack, resolvedNodes, visitedNodes, graphToDepsMap } = this

        while (stack.length > 0) {

            const currentNode = stack[stack.length - 1]

            if (this.isNodeResolved(currentNode)) {

                stack.pop()

            } else if (this.isNodeResolvable(currentNode)) {

                stack.pop()
                resolvedNodes.add(currentNode)
                visitedNodes.delete(currentNode)

            } else {

                // Cycle detection
                if (visitedNodes.has(currentNode)) {

                    throw new Error(`Dependency cycle detected: ${this.extractCycle(currentNode).join(' -> ')}`)

                }

                // Add to .visitedNodes
                visitedNodes.add(currentNode)

                // Add its dependencies to .stack
                Array.prototype.push.apply(stack, graphToDepsMap.get(currentNode))

            }

        }

        return Array.from(resolvedNodes)

    }

    /**
     * Detects if node is resolved already
     * @param {Node} node
     * @returns {boolean}
     */
    isNodeResolved(node) {

        return this.resolvedNodes.has(node)

    }

    /**
     * Detects if node can be resolved right now (all dependencies are resolved)
     * @param {Node} node
     * @returns {boolean}
     */
    isNodeResolvable(node) {

        const { graphToDepsMap } = this

        return graphToDepsMap.get(node).every(depNode => this.isNodeResolved(depNode))

    }

    /**
     * Extracts nodes that forms the cycle from this.visitedNodes set
     * @param {Node} node
     * @returns {Array<Node>}
     */
    extractCycle(node) {

        const { visitedNodes } = this
        const result = []
        let isNodeFound = false

        for (const visitedNode of visitedNodes) {

            if (node === visitedNode) {

                isNodeFound = true

            }

            if (isNodeFound === true) {

                result.push(visitedNode)

            }

        }

        result.push(node)

        return result

    }

    /**
     * Builds a map of nodes to its dependencies
     * @param {Graph} graph
     * @returns {Map}
     */
    static makeNodeToDepsMap(graph) {

        const nodeToDepsMap = new Map()

        for (const item of graph) {

            nodeToDepsMap.set(item.node, item.deps)

        }

        return nodeToDepsMap

    }

    /**
     * Builds a map of nodes to its dependencies
     * @param {Graph} graph
     * @throws {Error} if graph is not an Array
     * @throws {Error} if any graph item is not valid
     * @throws {Error} if any node defined more than once
     * @returns {void}
     */
    static validate(graph) {

        if (Array.isArray(graph) === false) {

            throw new Error('Graph should be represented as an array')

        }

        const nodes = new Set()
        const allowedNodeTypes = [ 'object', 'function', 'string', 'number' ]

        for (const item of graph) {

            if (allowedNodeTypes.includes(typeof item.node) === false || Array.isArray(item.deps) === false) {

                throw new Error('Every graph item should have valid "node" and "deps" properties')

            }

            if (nodes.has(item.node)) {

                throw new Error(`Graph node ${item.node.toString()} defined more than once`)

            }

            nodes.add(item.node)

        }

    }

}

/**
 * It takes a graph of objects that represents dependencies between them and resolves it in a right order
 *
 * @param {Graph} graph Dependency graph that is needed to be resolved
 * @throws {Error} if graph has cycled dependencies
 * @returns {Array<Node>} Resolved graph in the form of array
 */
export function resolveDependencyGraph(graph) {

    const graphResolver = new GraphResolver(graph)

    return graphResolver.resolve()

}
<commit_msg>Fix jsDoc types in dependency-graph-resolver. Add GraphError class<commit_after>/**
 * @typedef {Object} Node
 */

/**
 * @typedef {Object} GraphItem
 * @property {Node} node
 * @property {Array.<Node>} deps
 */

/**
 * @typedef {Array.<GraphItem>} Graph
 */

/**
 * Class is used for grpah related errors
 * @extends Error
 */
class GraphError extends Error {

}

/**
 * Resolves dependency graph. Graph nodes and deps could be represent as any js type
 */
class GraphResolver {

    /**
     * @param {Graph} graph
     */
    constructor(graph) {

        GraphResolver.validate(graph)

        /**
         * Input graph
         * @type {Graph}
         */
        this.graph = graph

        /**
         * Helper structure that maps nodes to its deps
         * @type {Map}
         */
        this.graphToDepsMap = GraphResolver.makeNodeToDepsMap(graph)

        /**
         * Stack of nodes
         * @type {Array.<Node>}
         */
        this.stack = this.graph.map(item => item.node)

        /**
         * Storage of nodes that were successfully resolved
         * @type {Set}
         */
        this.resolvedNodes = new Set()

        /**
         * Storage of nodes that were visited but at that moment they were unresolvable
         * @type {Set}
         */
        this.visitedNodes = new Set()

    }

    /**
     * Trying to resolve dependency graph
     * @throws {GraphError} if graph has cycled dependencies
     * @returns {Array.<Node>}
     */
    resolve() {

        const { stack, resolvedNodes, visitedNodes, graphToDepsMap } = this

        while (stack.length > 0) {

            const currentNode = stack[stack.length - 1]

            if (this.isNodeResolved(currentNode)) {

                stack.pop()

            } else if (this.isNodeResolvable(currentNode)) {

                stack.pop()
                resolvedNodes.add(currentNode)
                visitedNodes.delete(currentNode)

            } else {

                // Cycle detection
                if (visitedNodes.has(currentNode)) {

                    throw new GraphError(`Dependency cycle detected: ${this.extractCycle(currentNode).join(' -> ')}`)

                }

                // Add to .visitedNodes
                visitedNodes.add(currentNode)

                // Add its dependencies to .stack
                Array.prototype.push.apply(stack, graphToDepsMap.get(currentNode))

            }

        }

        return Array.from(resolvedNodes)

    }

    /**
     * Detects if node is resolved already
     * @param {Node} node
     * @returns {boolean}
     */
    isNodeResolved(node) {

        return this.resolvedNodes.has(node)

    }

    /**
     * Detects if node can be resolved right now (all dependencies are resolved)
     * @param {Node} node
     * @returns {boolean}
     */
    isNodeResolvable(node) {

        const { graphToDepsMap } = this

        return graphToDepsMap.get(node).every(depNode => this.isNodeResolved(depNode))

    }

    /**
     * Extracts nodes that forms the cycle from this.visitedNodes set
     * @param {Node} node
     * @returns {Array.<Node>}
     */
    extractCycle(node) {

        const { visitedNodes } = this
        const result = []
        let isNodeFound = false

        for (const visitedNode of visitedNodes) {

            if (node === visitedNode) {

                isNodeFound = true

            }

            if (isNodeFound === true) {

                result.push(visitedNode)

            }

        }

        result.push(node)

        return result

    }

    /**
     * Builds a map of nodes to its dependencies
     * @param {Graph} graph
     * @returns {Map}
     */
    static makeNodeToDepsMap(graph) {

        const nodeToDepsMap = new Map()

        for (const item of graph) {

            nodeToDepsMap.set(item.node, item.deps)

        }

        return nodeToDepsMap

    }

    /**
     * Builds a map of nodes to its dependencies
     * @param {Graph} graph
     * @throws {GraphError} if graph is not an Array
     * @throws {GraphError} if any graph item is not valid
     * @throws {GraphError} if any node defined more than once
     * @returns {void}
     */
    static validate(graph) {

        if (Array.isArray(graph) === false) {

            throw new GraphError('Graph should be represented as an array')

        }

        const nodes = new Set()
        const allowedNodeTypes = [ 'object', 'function', 'string', 'number' ]

        for (const item of graph) {

            if (allowedNodeTypes.includes(typeof item.node) === false || Array.isArray(item.deps) === false) {

                throw new GraphError('Every graph item should have valid "node" and "deps" properties')

            }

            if (nodes.has(item.node)) {

                throw new GraphError(`Graph node ${item.node.toString()} defined more than once`)

            }

            nodes.add(item.node)

        }

    }

}

/**
 * It takes a graph of objects that represents dependencies between them and resolves it in a right order
 *
 * @param {Graph} graph Dependency graph that is needed to be resolved
 * @throws {GraphError} if graph has cycled dependencies
 * @returns {Array.<Node>} Resolved graph in the form of array
 */
export function resolveDependencyGraph(graph) {

    const graphResolver = new GraphResolver(graph)

    return graphResolver.resolve()

}
<|endoftext|>


<commit_before>module.exports = {

    VERSION: "Mr Bazinga version 0.1",

    bet_request: function (game_state) {
        console.log(game_state.players);

        return 500;
//	    var additional_raise = 100,
//		    us = game_state.players[game_state.in_action];
//
//	    console.log(game_state.players);
//        return (game_state.current_buy_in - us.bet + (game_state.minimum_raise + additional_raise));
    },

    showdown: function (game_state) {

    }
};
<commit_msg>Super AI for flop<commit_after>var cardsRankList = ['2','3','4','5','6','7','8','9','10','J','Q','K','A'],

    VERY_GOOD = 'GOOD AS HELL',
    GOOD = 'GOOD',
    BAD = 'TOO BAD';

var getOurPlayer = function(game_state) {
    return game_state.players[game_state.in_action];
};

var getHand = function(player) {
    return player.hole_cards;
};

var rateHand = function(hand) {
    var rate = 0;

    if (hand[0].rank === hand[1].rank) {
        rate += 20;
    }

    if (hand[0].suit === hand[1].suit) {
        rate += 10;
    }

    if (cardsRankList.indexOf(hand[0].rank) > 8) {
        rate += 6;
    } else if (cardsRankList.indexOf(hand[0].rank) > 5) {
        rate += 3;
    }

    if (cardsRankList.indexOf(hand[1].rank) > 8) {
        rate += 6;
    } else if (cardsRankList.indexOf(hand[1].rank) > 5) {
        rate += 3;
    }

    console.log('Rate: ', rate);

    if (rate >= 20) {
        return VERY_GOOD;
    }

    if (rate >= 12) {
        return GOOD;
    }

    return BAD;
};

module.exports = {

    VERSION: "Mr Bazinga PreFlop Version",

    bet_request: function (game_state) {
        game_state = JSON.parse(game_state);

        var MrBazinga = getOurPlayer(game_state),
            hand = getHand(MrBazinga),
            rate = rateHand(hand),

            minimumRaise = game_state.current_buy_in - MrBazinga.bet + game_state.minimum_raise;

        if (rate === VERY_GOOD) {
            return minimumRaise + 200;
        }

        if (rate === GOOD) {
            return minimumRaise + 50;
        }

        return 0;
    },

    showdown: function (game_state) {

    }
};
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');

var findPairs = require('./src/find_pairs');
var uniqueCards = require('./src/unique');
var rankToValue = require('./src/rank_to_value');

class Player {
  constructor(game_state) {
    this.VERSION = "iPlayer 2.4";
    this._gameState = game_state;

  }

  bet_request() {
    var currentPlayer = this._gameState.players[this._gameState.in_action];

    var cards = [].concat(currentPlayer.hole_cards).concat(uniqueCards(this._gameState.community_cards));

    var minimumBet = this._gameState.current_buy_in - currentPlayer.bet;

    var result = findPairs(cards);

    var ownPairs = [];
    Object.keys(result).forEach(function (key) {
      if (result[key] > 1) {
        ownPairs.push(key);
      }
    });

    if (this._gameState.community_cards.length === 0) {
      var maximumBet = Math.min(this._gameState.small_blind * 6, currentPlayer.stack * 0.1);

      if (currentPlayer.stack < 500) {
        maximumBet = 50;
      }

      if (minimumBet <= maximumBet) {
        return minimumBet;
      } else {
        return 0;
      }
    }

    var shouldAllIn = false;

    var maxPairRank = _.max(ownPairs.map(rankToValue));

    if (ownPairs.length > 1 || maxPairRank >= 10) {
      shouldAllIn = true;
    }

    //
    //
    //pairs.forEach(function(rank) {
    //  if (['10', 'J', 'Q', 'K', 'A'].indexOf(rank.toUpperCase()) >= 0) {
    //    shouldAllIn = true;
    //  }
    //});

    if (shouldAllIn) {
      return 5000;
    } else if (ownPairs.length > 0) {
      var betAmount = minimumBet + this._gameState.minimum_raise;
      if (maxPairRank <= 6 && currentPlayer.stack < betAmount / 2) {
        return 0;
      }

      return betAmount;
    }
    else {
      return 0;
    }
  }

  showdown() {
  }

}

module.exports = {
  VERSION: "Super iPlayer Unicorn 3.0",

  bet_request(game_state) {
      return new Player(game_state).bet_request();
  },

  showdown(game_state) {

  }

};
<commit_msg>unicorn 3.1<commit_after>'use strict';

var _ = require('lodash');

var findPairs = require('./src/find_pairs');
var uniqueCards = require('./src/unique');
var rankToValue = require('./src/rank_to_value');

class Player {
  constructor(game_state) {
    this.VERSION = "iPlayer 2.4";
    this._gameState = game_state;

  }

  bet_request() {
    var currentPlayer = this._gameState.players[this._gameState.in_action];

    var cards = [].concat(currentPlayer.hole_cards).concat(uniqueCards(this._gameState.community_cards));

    var minimumBet = this._gameState.current_buy_in - currentPlayer.bet;

    var result = findPairs(cards);

    var ownPairs = [];
    Object.keys(result).forEach(function (key) {
      if (result[key] > 1) {
        ownPairs.push(key);
      }
    });

    if (this._gameState.community_cards.length === 0) {
      var maximumBet = Math.min(this._gameState.small_blind * 6, currentPlayer.stack * 0.1);

      if (currentPlayer.stack < 500) {
        maximumBet = 50;
      }

      if (minimumBet <= maximumBet) {
        console.log('PREFLOP LOG: game_id: ' + this._gameState.game_id + ', round: ' + this._gameState.round + ', smapp_blind: ' + this._gameState.small_blind + ', stack: ' + currentPlayer.stack);
        return minimumBet;
      } else {
        return 0;
      }
    }

    var shouldAllIn = false;

    var maxPairRank = _.max(ownPairs.map(rankToValue));

    if (ownPairs.length > 1 || maxPairRank >= 10) {
      shouldAllIn = true;
    }

    //
    //
    //pairs.forEach(function(rank) {
    //  if (['10', 'J', 'Q', 'K', 'A'].indexOf(rank.toUpperCase()) >= 0) {
    //    shouldAllIn = true;
    //  }
    //});

    if (shouldAllIn) {
      return 5000;
    } else if (ownPairs.length > 0) {
      var betAmount = minimumBet + this._gameState.minimum_raise;
      if (maxPairRank <= 6 && currentPlayer.stack < betAmount / 2) {
        return 0;
      }

      return betAmount;
    }
    else {
      return 0;
    }
  }

  showdown() {
  }

}

module.exports = {
  VERSION: "Super iPlayer Unicorn 3.1",

  bet_request(game_state) {
      return new Player(game_state).bet_request();
  },

  showdown(game_state) {

  }

};
<|endoftext|>