what am i doing with my life
This commit is contained in:
MallocNull 2014-09-03 17:38:57 -05:00
parent fbca902b90
commit e8b72fbdf8
8 changed files with 359 additions and 35 deletions

View file

@ -6,6 +6,6 @@ using System.Threading.Tasks;
namespace bot {
class Autonomous {
}
}

View file

@ -60,13 +60,24 @@ namespace bot {
}
static void Main(string[] args) {
Console.Write("Loading database info ... ");
_G.loadDatabaseInfo();
Console.WriteLine("OK");
Console.Write("Spawning database connections ... ");
_G.conn = _G.spawnNewConnection();
_G.errconn = _G.spawnNewConnection();
Console.WriteLine("OK");
Console.Write("Loading bot configuration ... ");
_G.loadConfig();
loadResponseList();
Console.WriteLine("OK");
Console.Write("Loading response list ... ");
loadResponseList();
Console.WriteLine("OK");
Console.Write("Updating response types on database ... ");
tmp = "DELETE FROM resptypes WHERE ";
foreach(Type t in ResponseCaller.getResponseTypes()) {
string[] typeInfo = (string[])t.GetMethod("getInfo").Invoke(null, null);
@ -78,7 +89,9 @@ namespace bot {
}
tmp = tmp.Substring(0, tmp.Length - 5);
Query.Quiet(tmp, _G.conn);
Console.WriteLine("OK");
Console.Write("Updating conditions on database ... ");
tmp = "DELETE FROM conditions WHERE ";
foreach(Type t in ConditionChecker.getConditions()) {
string[] typeInfo = (string[])t.GetMethod("getInfo").Invoke(null, null);
@ -90,11 +103,15 @@ namespace bot {
}
tmp = tmp.Substring(0, tmp.Length - 5);
Query.Quiet(tmp, _G.conn);
Console.WriteLine("OK");
Console.Write("Spawning web driver ... ");
_G.driver = new FirefoxDriver();
Console.WriteLine("OK");
while(true) {
try {
Console.Write("Navigating to chat ... ");
foreach(NavigationNode node in navigationList)
node.performNavigation(_G.driver);
try {
@ -102,6 +119,7 @@ namespace bot {
} catch(Exception e) {
_G.criticalError("Navigation to chat failed! Fix instructions.", true);
}
Console.WriteLine("OK");
_G.startThread(Pulse.pulseThread);

View file

@ -11,7 +11,7 @@ namespace bot {
static void loadConditionTypes() {
if(conditionTypes == null)
conditionTypes = Assembly.GetExecutingAssembly().GetTypes().Where(t => String.Equals(t.Namespace, "bot.conditions", StringComparison.Ordinal)).ToArray();
conditionTypes = Assembly.GetExecutingAssembly().GetTypes().Where(t => String.Equals(t.Namespace, "bot.conditions", StringComparison.Ordinal) && !t.FullName.Contains('+')).ToArray();
}
public static bool checkCondition(String conditionName, Message msg, string parameter) {

View file

@ -11,7 +11,7 @@ namespace bot {
static void loadResponseTypes() {
if(responseTypes == null)
responseTypes = Assembly.GetExecutingAssembly().GetTypes().Where(t => String.Equals(t.Namespace, "bot.responses", StringComparison.Ordinal)).ToArray();
responseTypes = Assembly.GetExecutingAssembly().GetTypes().Where(t => String.Equals(t.Namespace, "bot.responses", StringComparison.Ordinal) && !t.FullName.Contains('+')).ToArray();
}
public static void callResponse(String responseName, string parameters, Message msg) {

View file

@ -9,6 +9,7 @@ using OpenQA.Selenium.Internal;
using OpenQA.Selenium.Support.UI;
using MySql.Data.MySqlClient;
using System.Threading;
using System.Security.Cryptography;
namespace bot {
static class _G {

View file

@ -87,6 +87,7 @@
<Compile Include="Pulse.cs" />
<Compile Include="Query.cs" />
<Compile Include="responses\jumble.cs" />
<Compile Include="responses\poker.cs" />
<Compile Include="responses\replace.cs" />
<Compile Include="Sanitizer.cs" />
<Compile Include="_G.cs" />

220
bot/bot/responses/poker.cs Normal file
View file

@ -0,0 +1,220 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bot.responses {
class poker {
class PokerContext {
class Dice {
static private Random rng = new Random();
static public int[] Roll() {
return new int[] { rng.Next(6) + 1, rng.Next(6) + 1, rng.Next(6) + 1
, rng.Next(6) + 1, rng.Next(6) + 1};
}
}
public int playerMoney;
public int botMoney;
public int currentBet;
public PokerContext() {
playerMoney = botMoney = 1000;
currentBet = 1;
}
public int[] CheckHand(int[] hand) {
int i;
for(i = 1; i < 5; i++)
if(hand[i - 1] != hand[i] - 1) break;
if(i == 5) return new int[] { 4, hand.Sum() };
Dictionary<int, int> groupList = new Dictionary<int, int>();
for(i = 1; i < 5; i++) {
if(hand[i] == hand[i - 1]) {
if(groupList.ContainsKey(hand[i]))
groupList[hand[i]]++;
else
groupList.Add(hand[i], 2);
}
}
if(groupList.Keys.Count == 1) {
switch(groupList.Values.ElementAt(0)) {
case 2:
return new int[] { 1, groupList.Keys.ElementAt(0) };
case 3:
return new int[] { 3, groupList.Keys.ElementAt(0) };
case 4:
return new int[] { 6, groupList.Keys.ElementAt(0) };
case 5:
return new int[] { 7, groupList.Keys.ElementAt(0) };
}
} else if(groupList.Keys.Count == 2) {
if(groupList.Values.ElementAt(0) == 2 && groupList.Values.ElementAt(1) == 2)
return new int[] { 2, groupList.Keys.ElementAt(0) + groupList.Keys.ElementAt(1) };
else
return new int[] { 5, groupList.Keys.ElementAt(0) + groupList.Keys.ElementAt(1) };
}
return new int[]{0, hand[4]};
}
public string GetDieFaceFromInt(int face) {
switch(face) {
case 1:
return "9";
case 2:
return "10";
case 3:
return "J";
case 4:
return "Q";
case 5:
return "K";
case 6:
return "A";
}
return "WHAT";
}
public string GetDiceRollAsString(int[] hand) {
string tmp = "";
for(int i = 0; i < 5; i++)
tmp += GetDieFaceFromInt(hand[i]) + ((i == 4) ? "" : " ");
return tmp;
}
public string GetHandNameFromInt(int handresult) {
switch(handresult) {
case 0:
return "High Card";
case 1:
return "Pair";
case 2:
return "Two Pair";
case 3:
return "Three of a Kind";
case 4:
return "Straight";
case 5:
return "Full House";
case 6:
return "Four of a Kind";
case 7:
return "Five of a Kind";
}
return "WHAT";
}
public void PlayerWins(string playerName) {
Chat.sendMessage(playerName + " wins! " + _G.propername + " loses " + pokerContexts[playerName].currentBet);
pokerContexts[playerName].botMoney -= pokerContexts[playerName].currentBet;
pokerContexts[playerName].playerMoney += pokerContexts[playerName].currentBet;
}
public void BotWins(string playerName) {
Chat.sendMessage(_G.propername + " wins! " + playerName + " loses " + pokerContexts[playerName].currentBet);
pokerContexts[playerName].playerMoney -= pokerContexts[playerName].currentBet;
pokerContexts[playerName].botMoney += pokerContexts[playerName].currentBet;
}
public void Tie(string playerName) {
Chat.sendMessage(_G.propername + " tied with " + playerName);
}
public void PerformTurn(string playerName) {
int[] yourHand = Dice.Roll();
Array.Sort(yourHand);
int[] yourResults = CheckHand(yourHand);
Chat.sendMessage(playerName + " rolled " + GetDiceRollAsString(yourHand) + " (" + GetHandNameFromInt(yourResults[0]) + ")");
int[] botHand = Dice.Roll();
Array.Sort(botHand);
int[] botResults = CheckHand(botHand);
Chat.sendMessage(_G.propername + " rolled " + GetDiceRollAsString(botHand) + " (" + GetHandNameFromInt(botResults[0]) + ")");
if(botResults[0] > yourResults[0])
BotWins(playerName);
else if(yourResults[0] > botResults[0])
PlayerWins(playerName);
else {
if(botResults[1] > yourResults[1])
BotWins(playerName);
else if(yourResults[1] > botResults[1])
PlayerWins(playerName);
else
Tie(playerName);
}
}
public void Raise(int amount) {
if(amount > 0)
currentBet += amount;
Chat.sendMessage("Bet raised to " + currentBet);
}
public void Bet(int amount) {
if(amount > 0)
currentBet = amount;
Chat.sendMessage("Bet set at " + amount);
}
}
static private Random rng = new Random();
static private Dictionary<string, PokerContext> pokerContexts = new Dictionary<string,PokerContext>();
static public string[] getInfo() {
return new string[] {typeof(poker).Name, "Dice Poker",
"A sample module that allows a user to play against an AI in dice poker. Takes no arguments. Should accept the commands !register, !bet, !raise, !roll, !check, !help"};
}
static public void performOperation(string parameters, Message msg) {
try {
if(msg.msg.ToLower().Trim() == "!register") {
if(!pokerContexts.ContainsKey(msg.name)) {
pokerContexts.Add(msg.name, new PokerContext());
Chat.sendMessage("You are now registered, and have $1000. The default bet is $1. You can !raise #, !bet #, !roll, or !check the standings.");
} else {
Chat.sendMessage("You are already registered.");
}
} else {
if(pokerContexts.ContainsKey(msg.name)) {
PokerContext ctx = pokerContexts[msg.name];
switch(msg.msg.ToLower().Trim()) {
case "!help":
Chat.sendMessage("You can !raise #, !bet #, !roll, or !check the standings.");
break;
case "!check":
Chat.sendMessage(msg.name + " has $" + ctx.playerMoney + ". " + _G.propername + " has $" + ctx.botMoney + ". Both sides are currently betting $" + ctx.currentBet);
break;
case "!roll":
ctx.PerformTurn(msg.name);
break;
}
if(msg.msg.ToLower().Trim().StartsWith("!bet")) {
try {
ctx.Bet(Int32.Parse(msg.msg.Substring(msg.msg.IndexOf(' ') + 1)));
} catch(Exception e) { }
}
if(msg.msg.ToLower().Trim().StartsWith("!raise")) {
try {
ctx.Raise(Int32.Parse(msg.msg.Substring(msg.msg.IndexOf(' ') + 1)));
} catch(Exception e) { }
}
} else {
Chat.sendMessage("You are not registered. Register with !register.");
}
}
} catch(Exception e) {
Console.WriteLine(e.Message + " " + e.StackTrace);
}
}
}
}

View file

@ -13,15 +13,11 @@ if($_POST["editId"]) {
}
if($_POST["resptype"] && !$_POST["editId"]) {
$c = "";
for($i=1;;$i++) {
if(!isset($_POST["if". $i ."param"])) break;
$c .= $_POST['if'.$i.'lpar'].",".$_POST['if'.$i.'not'].",".$_POST['if'.$i.'cond'].",".$_POST['if'.$i.'param'].",".$_POST['if'.$i.'rpar'].";";
if(isset($_POST["op".$i])) $c .= $_POST["op".$i] .";";
}
mysql_query("INSERT INTO `responses` (`conditions`,`respid`,`parameters`,`cooldown`) VALUES ('". mysql_real_escape_string($c) ."',". $_POST['resptype'] .",'". mysql_real_escape_string($_POST['parameters']) ."',". (($_POST['ccd']==0)?-1:$_POST['cooldown']) .")") or die(mysql_error());
mysql_query("UPDATE `updater` SET `responses`=1 WHERE `id`=1");
if($_POST["autolink"] == -1)
mysql_query("INSERT INTO `autonomous` (`conditions`,`respid`,`parameters`,`cooldown`) VALUES ('". mysql_real_escape_string($c) ."',". $_POST['resptype'] .",'". mysql_real_escape_string($_POST['parameters']) ."',". (($_POST['ccd']==0)?-1:$_POST['cooldown']) .")") or die(mysql_error());
else
// do query
mysql_query("UPDATE `updater` SET `autonomous`=1 WHERE `id`=1");
header("Location: auto.php");
}
@ -32,13 +28,57 @@ include("header.php");
function confirmDeletion(id) {
var q = confirm("Are you sure you want to delete this response?");
if(q) window.location.href = "resp.php?del="+id;
if(q) window.location.href = "auto.php?del="+id;
}
function handleRespChange() {
document.getElementById("respDesc").innerHTML = document.getElementById(""+document.getElementById("resptype").selectedIndex).innerHTML;
}
function doTimeTest(fieldname, fieldtext, canbezero) {
if(!isNaN(parseInt(fieldtext.trim())) && isFinite(parseInt(fieldtext.trim()))) {
if(parseInt(fieldtext) > ((canbezero)?-1:0)) {
return true;
} else {
alert(fieldname +" must be positive and nonzero integer!");
return false;
}
} else {
alert(fieldname +" must be a finite integer!");
return false;
}
}
function evaluateCondition() {
if(document.getElementById("arname").value.trim() != "") {
if(doTimeTest("Periodicity",document.getElementById("period").value)) {
if(doTimeTest("Randomness",document.getElementById("randomness").value)) {
if(document.getElementById("autolink").selectedIndex != 0) {
if(doTimeTest("Link timeout",document.getElementById("timeout").value)) {
if(doTimeTest("Link randomness",document.getElementById("torandom").value)) {
document.getElementById("auto").submit();
}
}
} else {
document.getElementById("auto").submit();
}
}
}
} else {
alert("Friendly name cannot be blank!");
}
}
function handleAutolinkChange() {
if(document.getElementById("autolink").selectedIndex != 0) {
for(i = 1; i <= 3; i++)
document.getElementById("linktable").getElementsByTagName("tr")[i].style.display = "table-row";
} else {
for(i = 1; i <= 3; i++)
document.getElementById("linktable").getElementsByTagName("tr")[i].style.display = "none";
}
}
/*function coolChange() {
if(document.getElementById("cdd").selectedIndex == 0) {
document.getElementById("cooldown").disabled = true;
@ -75,6 +115,9 @@ include("header.php");
<?php } else if($_GET["do"]=="new") { ?>
<legend>Create New Autonomous Routine</legend>
<form method="post" action="" id="auto">
<p>
Friendly name: <input type="text" name="arname" id="arname" /> (for future reference)
</p>
<p>
Trigger first routine on
<select name="startday">
@ -91,7 +134,7 @@ include("header.php");
<select name="starttimehour">
<?php
echo "<option value='-1'></option>";
for($i = 1; $i <= 12; $i++) {
for($i = 1; $i <= 24; $i++) {
echo "<option value='$i'>". (($i<10)?"0":"") ."$i</option>";
}
?>
@ -105,11 +148,14 @@ include("header.php");
}
?>
</select>
<select name="timepredicate">
<option value="-1"></option>
<option value="0">AM</option>
<option value="1">PM</option>
</select>
</p>
<p>
After first trigger,
<table border="0">
<tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td>continue triggering every</td><td></td><td><input type="text" name="period" id="period" /> seconds</td></tr>
<tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td>with a randomness of<td>&plusmn;</td></td><td><input type="text" name="randomness" id="randomness" /> seconds.</td></tr>
</table>
</p>
<p>
On trigger,
@ -134,26 +180,64 @@ include("header.php");
?>
</p>
<p>
<span class="block" id="respDesc">
<?php echo $descarr[0]; ?>
</span>
<span class="block">Parameters:
<center>
<textarea name="parameters" rows="8" style="width:95%;"></textarea>
</center></span>
<span class="block" id="respDesc">
<?php echo $descarr[0]; ?>
</span>
<span class="block">Parameters:
<center>
<textarea name="parameters" rows="8" style="width:95%;"></textarea>
</center></span>
</p>
<p>
Cooldown:
<select name="cdd" id="cdd" onchange="coolChange();">
<option value="0">Default</option>
<option value="1">Custom</option>
</select>
<input type="textbox" name="cooldown" id="cooldown" size="6" value="<?php echo $config->cooldown; ?>" disabled="disabled" /> seconds
After triggering,
<table border="0" id="linktable">
<tr>
<td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
<td>Force routine to trigger</td>
<td></td>
<td><select name="autolink" id="autolink" onchange="handleAutolinkChange();">
<option value="-1">&nbsp;&nbsp;&nbsp;&nbsp;</option>
<?php
$q = mysql_query("SELECT * FROM `autonomous`");
while($auto = mysql_fetch_object($q)) {
echo "<option value='". $auto->id ."'>". $auto->name ."</option>";
}
?>
</select></td>
</tr>
<tr style="display: none;">
<td></td>
<td>after</td>
<td></td>
<td>
<input type="text" name="timeout" id="timeout" /> seconds
</td>
</tr>
<tr style="display: none;">
<td></td>
<td>with a randomness of</td>
<td>&plusmn;</td>
<td>
<input type="text" name="torandom" id="torandom" /> seconds.
</td>
</tr>
<tr style="display: none;">
<td></td>
<td>While waiting to trigger, </td>
<td></td>
<td>
<select name="respond" id="respond">
<option value="0">do not respond to messages</option>
<option value="1">do respond to messages</option>
</select>.
</td>
</tr>
</table>
</p>
<p>
<input type="button" name="addResponse" value="Add Response" onclick="evaluateCondition();" />
<input type="button" name="addResponse" value="Add Autonomous Routine" onclick="evaluateCondition();" />
&nbsp;&nbsp;&nbsp;&nbsp;
<input type="button" value="Cancel" onclick="window.location.href = 'resp.php';" />
<input type="button" value="Cancel" onclick="window.location.href = 'auto.php';" />
</p>
</form>
<?php } else if($_GET["do"]=="edit") {