Revision: 991b8cd34e
Author: Guy Van den Broeck <
guy...@gmail.com>
Date: Sun Nov 7 06:35:47 2010
Log: Added support for Prolog bots, with a network server and GUI
http://code.google.com/p/opentestbed/source/detail?r=991b8cd34e
Added:
/.hgignore
/build.xml
/data/bots/PrologBot.pd
/data/prologbot/WW10_protocol.proto
/data/prologbot/
bk.pl
/data/prologbot/cpp/
WW10_protocol.pb.cc
/data/prologbot/cpp/WW10_protocol.pb.h
/data/prologbot/java/ww10/WW10Protocol.java
/lib/protobuf-java-2.3.0.jar
/src/bots/prologbot/PrologBot.java
/src/game/NamedPlayer.java
/src/ww10/DummyClient.java
/src/ww10/PrologBotServer.java
/src/ww10/WW10Protocol.java
/src/ww10/WetenschapsweekStarter.java
/src/ww10/gui/ActionPanel.java
/src/ww10/gui/AverageProfitPanel.java
/src/ww10/gui/DataModel.java
/src/ww10/gui/SwingGUI.java
Modified:
/.classpath
/junit/bots/BotRepositoryTest.java
/junit/game/DealerTest.java
/junit/game/HandHistoryWriterTest.java
/junit/game/TableSeaterTest.java
/src/bots/BotMetaData.java
/src/bots/demobots/SimpleBot.java
/src/bots/mctsbot/ai/bots/bot/AbstractBot.java
/src/bots/mctsbot/ai/bots/bot/Bot.java
/src/bots/mctsbot/ai/bots/bot/gametree/action/BetAction.java
/src/bots/mctsbot/ai/bots/bot/gametree/action/CallAction.java
/src/bots/mctsbot/ai/bots/bot/gametree/action/CheckAction.java
/src/bots/mctsbot/ai/bots/bot/gametree/action/FoldAction.java
/src/bots/mctsbot/ai/bots/bot/gametree/action/ProbabilityAction.java
/src/bots/mctsbot/ai/bots/bot/gametree/action/RaiseAction.java
/src/bots/mctsbot/ai/bots/bot/gametree/action/SearchBotAction.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/FixedSampleMCTSBot.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/FixedSampleMCTSBotFactory.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/MCTSBotFactory.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/MCTSMeerkatBot.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/listeners/MCTSListener.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/AbstractNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/Config.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/ConstantLeafNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/DecisionNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/INode.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/InnerNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/LeafNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/MCTSBucketShowdownNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/MCTSShowdownRollOutNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/OpponentNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/RootNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/ShowdownNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/strategies/backpropagation/BackPropagationStrategy.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/strategies/backpropagation/MaxDistributionBackPropStrategy.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/strategies/backpropagation/MaxDistributionPlusBackPropStrategy.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/strategies/backpropagation/MixedBackPropStrategy.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/strategies/backpropagation/MixtureBackPropStrategy.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/strategies/backpropagation/SampleWeightedBackPropStrategy.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/strategies/selection/MaxFunctionSelector.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/strategies/selection/MaxUnderValueSelector.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/strategies/selection/MixedSelectionStrategy.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/strategies/selection/SampleProportionateSelector.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/strategies/selection/SamplingToFunctionSelector.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/strategies/selection/SquareSampleProportionateSelector.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/strategies/selection/UCTPlusPlusSelector.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/strategies/selection/UCTPlusSelector.java
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/strategies/selection/UCTSelector.java
/src/bots/mctsbot/ai/bots/bot/gametree/rollout/BucketRollOut.java
/src/bots/mctsbot/ai/bots/bot/gametree/rollout/DistributionRollout1.java
/src/bots/mctsbot/ai/bots/bot/gametree/rollout/DistributionRollout2.java
/src/bots/mctsbot/ai/bots/bot/gametree/rollout/DistributionRollout4.java
/src/bots/mctsbot/ai/bots/bot/gametree/rollout/RollOutStrategy.java
/src/bots/mctsbot/ai/bots/bot/gametree/rollout/RolloutResult.java
/src/bots/mctsbot/ai/bots/bot/gametree/rollout/UniformRollout.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/ActionNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/BotActionNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/ConstantLeafNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/Distribution.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/GameTreeNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/LeafNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/OpponentActionNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/SearchBot.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/SearchBotFactory.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/SearchConfiguration.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/ShowdownBucketRolloutNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/ShowdownNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/ShowdownRolloutNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/expander/CompleteExpander.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/expander/Expander.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/expander/SamplingExpander.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/expander/TokenExpander.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/expander/WeightedNode.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/expander/sampling/RandomSampler.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/expander/sampling/RelativeBetDistribution.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/expander/sampling/RouletteWheelSampler.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/expander/sampling/SmartSampler.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/expander/sampling/StochasticSampler.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/expander/sampling/StochasticUniversalSampler.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/nodevisitor/Log4JOutputVisitor.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/nodevisitor/NodeVisitor.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/nodevisitor/StatisticsVisitor.java
/src/bots/mctsbot/ai/bots/bot/gametree/search/nodevisitor/TextOutputVisitor.java
/src/bots/mctsbot/ai/bots/util/Gaussian.java
/src/bots/mctsbot/ai/bots/util/PropositionalDataSetGenerator.java
/src/bots/mctsbot/ai/bots/util/RunPropositionalDataSetGenerator.java
/src/bots/mctsbot/ai/bots/util/RunningStats.java
/src/bots/mctsbot/ai/opponentmodels/OpponentModel.java
/src/bots/mctsbot/ai/opponentmodels/simple/HistogramModel.java
/src/bots/mctsbot/ai/opponentmodels/simple/HistogramModelFactory.java
/src/bots/mctsbot/ai/opponentmodels/simple/PlayerRoundHistogram.java
/src/bots/mctsbot/ai/opponentmodels/weka/ARFFPropositionalizer.java
/src/bots/mctsbot/ai/opponentmodels/weka/ActionTrackingVisitor.java
/src/bots/mctsbot/ai/opponentmodels/weka/BetStatistics.java
/src/bots/mctsbot/ai/opponentmodels/weka/PlayerData.java
/src/bots/mctsbot/ai/opponentmodels/weka/PlayerTrackingVisitor.java
/src/bots/mctsbot/ai/opponentmodels/weka/WekaOptions.java
/src/bots/mctsbot/ai/opponentmodels/weka/WekaRegressionModel.java
/src/bots/mctsbot/ai/opponentmodels/weka/WekaRegressionModelFactory.java
/src/bots/mctsbot/ai/opponentmodels/weka/instances/EmptyInstance.java
/src/bots/mctsbot/ai/opponentmodels/weka/instances/InstancesBuilder.java
/src/bots/mctsbot/ai/opponentmodels/weka/instances/PostCheckBetInstances.java
/src/bots/mctsbot/ai/opponentmodels/weka/instances/PostFoldCallRaiseInstances.java
/src/bots/mctsbot/ai/opponentmodels/weka/instances/PreCheckBetInstances.java
/src/bots/mctsbot/ai/opponentmodels/weka/instances/PreFoldCallRaiseInstances.java
/src/bots/mctsbot/ai/opponentmodels/weka/instances/ShowdownInstances.java
/src/bots/mctsbot/client/common/GameStateContainer.java
/src/bots/mctsbot/client/common/gamestate/AbstractGameState.java
/src/bots/mctsbot/client/common/gamestate/CachingNode.java
/src/bots/mctsbot/client/common/gamestate/DetailedHoldemTableState.java
/src/bots/mctsbot/client/common/gamestate/ForwardingGameState.java
/src/bots/mctsbot/client/common/gamestate/GameState.java
/src/bots/mctsbot/client/common/gamestate/GameStateVisitor.java
/src/bots/mctsbot/client/common/gamestate/modifiers/AllInState.java
/src/bots/mctsbot/client/common/gamestate/modifiers/BetState.java
/src/bots/mctsbot/client/common/gamestate/modifiers/BlindState.java
/src/bots/mctsbot/client/common/gamestate/modifiers/CallState.java
/src/bots/mctsbot/client/common/gamestate/modifiers/CheckState.java
/src/bots/mctsbot/client/common/gamestate/modifiers/ConfigChangeState.java
/src/bots/mctsbot/client/common/gamestate/modifiers/FoldState.java
/src/bots/mctsbot/client/common/gamestate/modifiers/JoinTableState.java
/src/bots/mctsbot/client/common/gamestate/modifiers/LeaveTableState.java
/src/bots/mctsbot/client/common/gamestate/modifiers/NewCommunityCardsState.java
/src/bots/mctsbot/client/common/gamestate/modifiers/NewDealState.java
/src/bots/mctsbot/client/common/gamestate/modifiers/NewPocketCardsState.java
/src/bots/mctsbot/client/common/gamestate/modifiers/NewRoundState.java
/src/bots/mctsbot/client/common/gamestate/modifiers/NextPlayerState.java
/src/bots/mctsbot/client/common/gamestate/modifiers/RaiseState.java
/src/bots/mctsbot/client/common/gamestate/modifiers/ShowHandState.java
/src/bots/mctsbot/client/common/gamestate/modifiers/SitInState.java
/src/bots/mctsbot/client/common/gamestate/modifiers/SitOutState.java
/src/bots/mctsbot/client/common/gamestate/modifiers/WinnerState.java
/src/bots/mctsbot/client/common/playerstate/AbstractPlayerState.java
/src/bots/mctsbot/client/common/playerstate/ForwardingPlayerState.java
/src/bots/mctsbot/client/common/playerstate/PlayerState.java
/src/bots/mctsbot/client/common/playerstate/SeatedPlayerState.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/AllInEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/BetEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/BlindEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/CallEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/CheckEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/ConfigChangeEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/FoldEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/HoldemTableEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/HoldemTableTreeEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/JoinTableEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/LeaveTableEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/NewCommunityCardsEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/NewDealEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/NewRoundEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/NextPlayerEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/RaiseEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/ShowHandEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/SitInEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/SitOutEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/event/package-info.java
/src/bots/mctsbot/common/api/lobby/holdemtable/holdemplayer/context/RemoteHoldemPlayerContext.java
/src/bots/mctsbot/common/api/lobby/holdemtable/holdemplayer/event/HoldemPlayerEvent.java
/src/bots/mctsbot/common/api/lobby/holdemtable/holdemplayer/event/package-info.java
/src/bots/mctsbot/common/api/lobby/holdemtable/holdemplayer/listener/HoldemPlayerListener.java
/src/bots/mctsbot/common/api/lobby/holdemtable/holdemplayer/listener/RemoteHoldemPlayerListener.java
/src/bots/mctsbot/common/elements/chips/Pots.java
/src/bots/mctsbot/common/elements/player/Player.java
/src/bots/mctsbot/common/elements/player/SeatedPlayer.java
/src/bots/mctsbot/common/elements/player/ShowdownPlayer.java
/src/bots/mctsbot/common/elements/table/DetailedHoldemTable.java
/src/bots/mctsbot/common/elements/table/Round.java
/src/bots/mctsbot/common/elements/table/SeatId.java
/src/bots/mctsbot/common/elements/table/Table.java
/src/bots/mctsbot/common/elements/table/TableConfiguration.java
/src/bots/mctsbot/common/elements/table/TableId.java
/src/bots/mctsbot/common/handeval/spears2p2/Flushes.java
/src/bots/mctsbot/common/handeval/spears2p2/Products.java
/src/bots/mctsbot/common/handeval/spears2p2/StateTableEvaluator.java
/src/bots/mctsbot/common/handeval/spears2p2/Unique.java
/src/bots/mctsbot/common/handeval/spears2p2/Values.java
/src/bots/mctsbot/common/util/Log4JPropertiesLoader.java
/src/bots/mctsbot/common/util/MutableDouble.java
/src/bots/mctsbot/common/util/Pair.java
/src/bots/mctsbot/common/util/Triple.java
/src/bots/mctsbot/common/util/Util.java
/src/common/handeval/klaatu/BulkTests.java
/src/common/handeval/klaatu/Deck.java
/src/common/handeval/klaatu/FastEval.java
/src/common/handeval/klaatu/HandFST.java
/src/common/handeval/klaatu/PartialStageFastEval.java
/src/common/handeval/klaatu/Test.java
/src/common/handeval/stevebrecher/Card.java
/src/common/handeval/stevebrecher/CardSet.java
/src/common/handeval/stevebrecher/HandEval.java
/src/game/CashGameRunner.java
/src/game/GameRunner.java
/src/game/HandEvalImpl.java
/src/game/HandHistoryWriter.java
/src/game/Pot.java
/src/game/PotManager.java
/src/game/PublicGameInfo.java
/src/game/PublicPlayerInfo.java
/src/game/RandomDeckTest.java
/src/game/TableSeater.java
/src/game/deck/RandomDeck.java
/src/game/stats/BankrollGraphUI.java
/src/util/CardConverter.java
=======================================
--- /dev/null
+++ /.hgignore Sun Nov 7 06:35:47 2010
@@ -0,0 +1,2 @@
+bin
+junitclasses
=======================================
--- /dev/null
+++ /build.xml Sun Nov 7 06:35:47 2010
@@ -0,0 +1,95 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!-- WARNING: Eclipse auto-generated file.
+ Any modifications will be overwritten.
+ To include a user specific buildfile here, simply create one
in the same
+ directory with the processing instruction
<?eclipse.ant.import?>
+ as the first entry and export the buildfile again. -->
+<project basedir="." default="build" name="Opentestbed">
+ <property environment="env"/>
+ <property name="debuglevel" value="source,lines,vars"/>
+ <property name="target" value="1.6"/>
+ <property name="source" value="1.6"/>
+ <path id="JUnit 4.libraryclasspath">
+ <pathelement
location="../../../bin/eclipse-3.6/plugins/org.junit_4.8.1.v4_8_1_v20100427-1100/junit.jar"/>
+ <pathelement
location="../../../bin/eclipse-3.6/plugins/org.hamcrest.core_1.1.0.v20090501071000.jar"/>
+ </path>
+ <path id="Opentestbed.classpath">
+ <pathelement location="bin"/>
+ <pathelement location="junitclasses"/>
+ <pathelement location="lib/meerkat-api.jar"/>
+ <pathelement location="lib/commons-io-1.4-sources.jar"/>
+ <pathelement location="lib/protobuf-java-2.3.0.jar"/>
+ <path refid="JUnit 4.libraryclasspath"/>
+ <pathelement location="lib/commons-io-1.4.jar"/>
+ <pathelement location="lib/jfreechart-1.0.13.jar"/>
+ <pathelement location="lib/jcommon-1.0.16.jar"/>
+ <pathelement location="lib/google-collections-0.9.jar"/>
+ <pathelement location="lib/log4j-1.2.14.jar"/>
+ <pathelement location="lib/commons-math-1.2.jar"/>
+ <pathelement location="lib/weka-3.6.0.jar"/>
+ <pathelement location="lib/x86-3.3.0-v3346.jar"/>
+ </path>
+ <target name="init">
+ <mkdir dir="bin"/>
+ <mkdir dir="junitclasses"/>
+ <copy includeemptydirs="false" todir="bin">
+ <fileset dir="src">
+ <exclude name="**/*.launch"/>
+ <exclude name="**/*.java"/>
+ </fileset>
+ </copy>
+ <copy includeemptydirs="false" todir="junitclasses">
+ <fileset dir="junit">
+ <exclude name="**/*.launch"/>
+ <exclude name="**/*.java"/>
+ </fileset>
+ </copy>
+ </target>
+ <target name="clean">
+ <delete dir="bin"/>
+ <delete dir="junitclasses"/>
+ </target>
+ <target depends="clean" name="cleanall"/>
+ <target depends="build-subprojects,build-project" name="build"/>
+ <target name="build-subprojects"/>
+ <target depends="init" name="build-project">
+ <echo message="${
ant.project.name}: ${ant.file}"/>
+ <javac debug="true" debuglevel="${debuglevel}" destdir="bin"
source="${source}" target="${target}">
+ <src path="src"/>
+ <classpath refid="Opentestbed.classpath"/>
+ </javac>
+ <javac debug="true" debuglevel="${debuglevel}"
destdir="junitclasses" source="${source}" target="${target}">
+ <src path="junit"/>
+ <classpath refid="Opentestbed.classpath"/>
+ </javac>
+ </target>
+ <target description="Build all projects which reference this project.
Useful to propagate changes." name="build-refprojects"/>
+ <target description="copy Eclipse compiler jars to ant lib directory"
name="init-eclipse-compiler">
+ <copy todir="${ant.library.dir}">
+ <fileset dir="${ECLIPSE_HOME}/plugins"
includes="org.eclipse.jdt.core_*.jar"/>
+ </copy>
+ <unzip dest="${ant.library.dir}">
+ <patternset includes="jdtCompilerAdapter.jar"/>
+ <fileset dir="${ECLIPSE_HOME}/plugins"
includes="org.eclipse.jdt.core_*.jar"/>
+ </unzip>
+ </target>
+ <target description="compile project with Eclipse compiler"
name="build-eclipse-compiler">
+ <property name="build.compiler"
value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
+ <antcall target="build"/>
+ </target>
+ <target name="DummyClient">
+ <java classname="ww10.DummyClient" failonerror="true" fork="yes">
+ <classpath refid="Opentestbed.classpath"/>
+ </java>
+ </target>
+ <target name="CashGameConsoleStarter">
+ <java classname="CashGameConsoleStarter" failonerror="true"
fork="yes">
+ <classpath refid="Opentestbed.classpath"/>
+ </java>
+ </target>
+ <target name="WetenschapsweekStarter">
+ <java classname="ww10.WetenschapsweekStarter" failonerror="true"
fork="yes">
+ <classpath refid="Opentestbed.classpath"/>
+ </java>
+ </target>
+</project>
=======================================
--- /dev/null
+++ /data/bots/PrologBot.pd Sun Nov 7 06:35:47 2010
@@ -0,0 +1,14 @@
+# All plug-ins must run through the following class:
+PLAYER_CLASS=PlugInOpponent
+
+# put your bot's full class name here:
+BOT_PLAYER_CLASS=bots.prologbot.PrologBot
+
+# Your Bot's name:
+PLAYER_NAME=PrologBot
+
+# Your bot engine name:
+AI_NAME=PrologBot
+
+# Options for your Bot:
+DEBUG=true
=======================================
--- /dev/null
+++ /data/prologbot/WW10_protocol.proto Sun Nov 7 06:35:47 2010
@@ -0,0 +1,7 @@
+package ww10;
+
+message PrologBotDescription {
+ required int32 id = 1;
+ required string name = 2;
+ required string prolog = 3;
+}
=======================================
--- /dev/null
+++ /data/prologbot/
bk.pl Sun Nov 7 06:35:47 2010
@@ -0,0 +1,108 @@
+% ================
+% background knowledge for rule based poker bots
+% ================
+
+:- use_module(library(lists)).
+
+evaluate :- do(A), format('~w~n',[A]), flush_output, halt.
+evaluate :- format('~n',[]), flush_output, halt.
+
+round(postflop) :- round(flop).
+round(postflop) :- round(turn).
+round(postflop) :- round(river).
+
+allcards(C) :- handcards(C1), communitycards(C2), append(C1,C2,C).
+
+% ================
+% hand evaluation
+% ================
+pair(Cards) :- pair(Cards,_).
+pair(Cards, N) :-
+ member(card(N,C1),Cards),
+ member(card(N,C2),Cards),
+ C1 \== C2.
+
+doublepair(Cards) :- doublepair(Cards, _, _).
+doublepair(Cards, N, M) :-
+ pair(Cards, N),
+ pair(Cards, M),
+ N \== M.
+
+threeofakind(Cards) :- threeofakind(Cards, _).
+threeofakind(Cards, N) :-
+ member(card(N,C1),Cards),
+ member(card(N,C2),Cards),
+ C1 \== C2,
+ member(card(N,C3),Cards),
+ C1 \== C3,
+ C2 \== C3.
+
+straight(Cards) :- straight(Cards, _).
+straight(Cards, Start) :-
+ member(Start, [2,3,4,5,6,7,8,9,10]),
+ member(card(Start,_),Cards),
+ I2 is Start + 1,
+ member(card(I2,_),Cards),
+ I3 is Start + 2,
+ member(card(I3,_),Cards),
+ I4 is Start + 3,
+ member(card(I4,_),Cards),
+ I5 is Start + 4,
+ member(card(I5,_),Cards).
+
+flush(Cards) :-
+ member(card(N1,C),Cards),
+ member(card(N2,C),Cards),
+ N2 \== N1,
+ member(card(N3,C),Cards),
+ N3 \== N2,
+ N3 \== N1,
+ member(card(N4,C),Cards),
+ N4 \== N1,
+ N4 \== N2,
+ N4 \== N3,
+ member(card(N5,C),Cards),
+ N5 \== N1,
+ N5 \== N2,
+ N5 \== N3,
+ N5 \== N4.
+
+fullhouse(Cards) :-
+ threeofakind(Cards, N),
+ pair(Cards, M),
+ N \== M.
+
+fourofakind(Cards) :- fourofakind(Cards, _).
+fourofakind(Cards, N) :-
+ member(card(N,C1),Cards),
+ member(card(N,C2),Cards),
+ C1 \== C2,
+ member(card(N,C3),Cards),
+ C1 \== C3,
+ C2 \== C3,
+ member(card(N,C4),Cards),
+ C1 \== C4,
+ C2 \== C4,
+ C3 \== C4.
+
+straightflush(Cards) :-
+ member(Start, [2,3,4,5,6,7,8,9,10]),
+ member(card(Start,C),Cards),
+ I2 is Start + 1,
+ member(card(I2,C),Cards),
+ I3 is Start + 2,
+ member(card(I3,C),Cards),
+ I4 is Start + 3,
+ member(card(I4,C),Cards),
+ I5 is Start + 4,
+ member(card(I5,C),Cards).
+
+handeval(C,straightflush) :- straightflush(C), !.
+handeval(C,fourofakind) :- fourofakind(C), !.
+handeval(C,fullhouse) :- fullhouse(C), !.
+handeval(C,flush) :- flush(C), !.
+handeval(C,straight) :- straight(C), !.
+handeval(C,threeofakind) :- threeofakind(C), !.
+handeval(C,doublepair) :- doublepair(C), !.
+handeval(C,pair) :- pair(C), !.
+handeval(C,highcard) :- !.
=======================================
--- /dev/null
+++ /data/prologbot/cpp/
WW10_protocol.pb.cc Sun Nov 7 06:35:47 2010
@@ -0,0 +1,423 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+
+#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
+#include "WW10_protocol.pb.h"
+#include <google/protobuf/stubs/once.h>
+#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/wire_format_lite_inl.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/reflection_ops.h>
+#include <google/protobuf/wire_format.h>
+// @@protoc_insertion_point(includes)
+
+namespace ww10 {
+
+namespace {
+
+const ::google::protobuf::Descriptor* PrologBotDescription_descriptor_ =
NULL;
+const ::google::protobuf::internal::GeneratedMessageReflection*
+ PrologBotDescription_reflection_ = NULL;
+
+} // namespace
+
+
+void protobuf_AssignDesc_WW10_5fprotocol_2eproto() {
+ protobuf_AddDesc_WW10_5fprotocol_2eproto();
+ const ::google::protobuf::FileDescriptor* file =
+ ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
+ "WW10_protocol.proto");
+ GOOGLE_CHECK(file != NULL);
+ PrologBotDescription_descriptor_ = file->message_type(0);
+ static const int PrologBotDescription_offsets_[3] = {
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PrologBotDescription,
id_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PrologBotDescription,
name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PrologBotDescription,
prolog_),
+ };
+ PrologBotDescription_reflection_ =
+ new ::google::protobuf::internal::GeneratedMessageReflection(
+ PrologBotDescription_descriptor_,
+ PrologBotDescription::default_instance_,
+ PrologBotDescription_offsets_,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PrologBotDescription,
_has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PrologBotDescription,
_unknown_fields_),
+ -1,
+ ::google::protobuf::DescriptorPool::generated_pool(),
+ ::google::protobuf::MessageFactory::generated_factory(),
+ sizeof(PrologBotDescription));
+}
+
+namespace {
+
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
+inline void protobuf_AssignDescriptorsOnce() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
+ &protobuf_AssignDesc_WW10_5fprotocol_2eproto);
+}
+
+void protobuf_RegisterTypes(const ::std::string&) {
+ protobuf_AssignDescriptorsOnce();
+ ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
+ PrologBotDescription_descriptor_,
&PrologBotDescription::default_instance());
+}
+
+} // namespace
+
+void protobuf_ShutdownFile_WW10_5fprotocol_2eproto() {
+ delete PrologBotDescription::default_instance_;
+ delete PrologBotDescription_reflection_;
+}
+
+void protobuf_AddDesc_WW10_5fprotocol_2eproto() {
+ static bool already_here = false;
+ if (already_here) return;
+ already_here = true;
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+ ::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
+ "\n\023WW10_protocol.proto\022\004ww10\"@\n\024PrologBot"
+ "Description\022\n\n\002id\030\001 \002(\005\022\014\n\004name\030\002
\002(\t\022\016\n"
+ "\006prolog\030\003 \002(\t", 93);
+ ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
+ "WW10_protocol.proto", &protobuf_RegisterTypes);
+ PrologBotDescription::default_instance_ = new PrologBotDescription();
+ PrologBotDescription::default_instance_->InitAsDefaultInstance();
+ ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_WW10_5fprotocol_2eproto);
+}
+
+// Force AddDescriptors() to be called at static initialization time.
+struct StaticDescriptorInitializer_WW10_5fprotocol_2eproto {
+ StaticDescriptorInitializer_WW10_5fprotocol_2eproto() {
+ protobuf_AddDesc_WW10_5fprotocol_2eproto();
+ }
+} static_descriptor_initializer_WW10_5fprotocol_2eproto_;
+
+
+// ===================================================================
+
+const ::std::string PrologBotDescription::_default_name_;
+const ::std::string PrologBotDescription::_default_prolog_;
+#ifndef _MSC_VER
+const int PrologBotDescription::kIdFieldNumber;
+const int PrologBotDescription::kNameFieldNumber;
+const int PrologBotDescription::kPrologFieldNumber;
+#endif // !_MSC_VER
+
+PrologBotDescription::PrologBotDescription()
+ : ::google::protobuf::Message() {
+ SharedCtor();
+}
+
+void PrologBotDescription::InitAsDefaultInstance() {
+}
+
+PrologBotDescription::PrologBotDescription(const PrologBotDescription&
from)
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ MergeFrom(from);
+}
+
+void PrologBotDescription::SharedCtor() {
+ _cached_size_ = 0;
+ id_ = 0;
+ name_ = const_cast< ::std::string*>(&_default_name_);
+ prolog_ = const_cast< ::std::string*>(&_default_prolog_);
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+}
+
+PrologBotDescription::~PrologBotDescription() {
+ SharedDtor();
+}
+
+void PrologBotDescription::SharedDtor() {
+ if (name_ != &_default_name_) {
+ delete name_;
+ }
+ if (prolog_ != &_default_prolog_) {
+ delete prolog_;
+ }
+ if (this != default_instance_) {
+ }
+}
+
+void PrologBotDescription::SetCachedSize(int size) const {
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+}
+const ::google::protobuf::Descriptor* PrologBotDescription::descriptor() {
+ protobuf_AssignDescriptorsOnce();
+ return PrologBotDescription_descriptor_;
+}
+
+const PrologBotDescription& PrologBotDescription::default_instance() {
+ if (default_instance_ == NULL)
protobuf_AddDesc_WW10_5fprotocol_2eproto(); return *default_instance_;
+}
+
+PrologBotDescription* PrologBotDescription::default_instance_ = NULL;
+
+PrologBotDescription* PrologBotDescription::New() const {
+ return new PrologBotDescription;
+}
+
+void PrologBotDescription::Clear() {
+ if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ id_ = 0;
+ if (_has_bit(1)) {
+ if (name_ != &_default_name_) {
+ name_->clear();
+ }
+ }
+ if (_has_bit(2)) {
+ if (prolog_ != &_default_prolog_) {
+ prolog_->clear();
+ }
+ }
+ }
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ mutable_unknown_fields()->Clear();
+}
+
+bool PrologBotDescription::MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input) {
+#define DO_(EXPRESSION) if (!(EXPRESSION)) return false
+ ::google::protobuf::uint32 tag;
+ while ((tag = input->ReadTag()) != 0) {
+ switch
(::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
+ // required int32 id = 1;
+ case 1: {
+ if
(::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
+ ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT)
{
+ DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
+ ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
+ input, &id_)));
+ _set_bit(0);
+ } else {
+ goto handle_uninterpreted;
+ }
+ if (input->ExpectTag(18)) goto parse_name;
+ break;
+ }
+
+ // required string name = 2;
+ case 2: {
+ if
(::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
+ ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED)
{
+ parse_name:
+ DO_(::google::protobuf::internal::WireFormatLite::ReadString(
+ input, this->mutable_name()));
+ ::google::protobuf::internal::WireFormat::VerifyUTF8String(
+ this->name().data(), this->name().length(),
+ ::google::protobuf::internal::WireFormat::PARSE);
+ } else {
+ goto handle_uninterpreted;
+ }
+ if (input->ExpectTag(26)) goto parse_prolog;
+ break;
+ }
+
+ // required string prolog = 3;
+ case 3: {
+ if
(::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
+ ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED)
{
+ parse_prolog:
+ DO_(::google::protobuf::internal::WireFormatLite::ReadString(
+ input, this->mutable_prolog()));
+ ::google::protobuf::internal::WireFormat::VerifyUTF8String(
+ this->prolog().data(), this->prolog().length(),
+ ::google::protobuf::internal::WireFormat::PARSE);
+ } else {
+ goto handle_uninterpreted;
+ }
+ if (input->ExpectAtEnd()) return true;
+ break;
+ }
+
+ default: {
+ handle_uninterpreted:
+ if
(::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
+ ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP)
{
+ return true;
+ }
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, mutable_unknown_fields()));
+ break;
+ }
+ }
+ }
+ return true;
+#undef DO_
+}
+
+void PrologBotDescription::SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const {
+ // required int32 id = 1;
+ if (_has_bit(0)) {
+ ::google::protobuf::internal::WireFormatLite::WriteInt32(1,
this->id(), output);
+ }
+
+ // required string name = 2;
+ if (_has_bit(1)) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8String(
+ this->name().data(), this->name().length(),
+ ::google::protobuf::internal::WireFormat::SERIALIZE);
+ ::google::protobuf::internal::WireFormatLite::WriteString(
+ 2, this->name(), output);
+ }
+
+ // required string prolog = 3;
+ if (_has_bit(2)) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8String(
+ this->prolog().data(), this->prolog().length(),
+ ::google::protobuf::internal::WireFormat::SERIALIZE);
+ ::google::protobuf::internal::WireFormatLite::WriteString(
+ 3, this->prolog(), output);
+ }
+
+ if (!unknown_fields().empty()) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ unknown_fields(), output);
+ }
+}
+
+::google::protobuf::uint8*
PrologBotDescription::SerializeWithCachedSizesToArray(
+ ::google::protobuf::uint8* target) const {
+ // required int32 id = 1;
+ if (_has_bit(0)) {
+ target
= ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1,
this->id(), target);
+ }
+
+ // required string name = 2;
+ if (_has_bit(1)) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8String(
+ this->name().data(), this->name().length(),
+ ::google::protobuf::internal::WireFormat::SERIALIZE);
+ target =
+ ::google::protobuf::internal::WireFormatLite::WriteStringToArray(
+ 2, this->name(), target);
+ }
+
+ // required string prolog = 3;
+ if (_has_bit(2)) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8String(
+ this->prolog().data(), this->prolog().length(),
+ ::google::protobuf::internal::WireFormat::SERIALIZE);
+ target =
+ ::google::protobuf::internal::WireFormatLite::WriteStringToArray(
+ 3, this->prolog(), target);
+ }
+
+ if (!unknown_fields().empty()) {
+ target
= ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ unknown_fields(), target);
+ }
+ return target;
+}
+
+int PrologBotDescription::ByteSize() const {
+ int total_size = 0;
+
+ if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ // required int32 id = 1;
+ if (has_id()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::Int32Size(
+ this->id());
+ }
+
+ // required string name = 2;
+ if (has_name()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::StringSize(
+ this->name());
+ }
+
+ // required string prolog = 3;
+ if (has_prolog()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::StringSize(
+ this->prolog());
+ }
+
+ }
+ if (!unknown_fields().empty()) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ unknown_fields());
+ }
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = total_size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ return total_size;
+}
+
+void PrologBotDescription::MergeFrom(const ::google::protobuf::Message&
from) {
+ GOOGLE_CHECK_NE(&from, this);
+ const PrologBotDescription* source =
+ ::google::protobuf::internal::dynamic_cast_if_available<const
PrologBotDescription*>(
+ &from);
+ if (source == NULL) {
+ ::google::protobuf::internal::ReflectionOps::Merge(from, this);
+ } else {
+ MergeFrom(*source);
+ }
+}
+
+void PrologBotDescription::MergeFrom(const PrologBotDescription& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ if (from._has_bit(0)) {
+ set_id(
from.id());
+ }
+ if (from._has_bit(1)) {
+ set_name(
from.name());
+ }
+ if (from._has_bit(2)) {
+ set_prolog(from.prolog());
+ }
+ }
+ mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+}
+
+void PrologBotDescription::CopyFrom(const ::google::protobuf::Message&
from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+void PrologBotDescription::CopyFrom(const PrologBotDescription& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+bool PrologBotDescription::IsInitialized() const {
+ if ((_has_bits_[0] & 0x00000007) != 0x00000007) return false;
+
+ return true;
+}
+
+void PrologBotDescription::Swap(PrologBotDescription* other) {
+ if (other != this) {
+ std::swap(id_, other->id_);
+ std::swap(name_, other->name_);
+ std::swap(prolog_, other->prolog_);
+ std::swap(_has_bits_[0], other->_has_bits_[0]);
+ _unknown_fields_.Swap(&other->_unknown_fields_);
+ std::swap(_cached_size_, other->_cached_size_);
+ }
+}
+
+::google::protobuf::Metadata PrologBotDescription::GetMetadata() const {
+ protobuf_AssignDescriptorsOnce();
+ ::google::protobuf::Metadata metadata;
+ metadata.descriptor = PrologBotDescription_descriptor_;
+ metadata.reflection = PrologBotDescription_reflection_;
+ return metadata;
+}
+
+
+// @@protoc_insertion_point(namespace_scope)
+
+} // namespace ww10
+
+// @@protoc_insertion_point(global_scope)
=======================================
--- /dev/null
+++ /data/prologbot/cpp/WW10_protocol.pb.h Sun Nov 7 06:35:47 2010
@@ -0,0 +1,273 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: WW10_protocol.proto
+
+#ifndef PROTOBUF_WW10_5fprotocol_2eproto__INCLUDED
+#define PROTOBUF_WW10_5fprotocol_2eproto__INCLUDED
+
+#include <string>
+
+#include <google/protobuf/stubs/common.h>
+
+#if GOOGLE_PROTOBUF_VERSION < 2003000
+#error This file was generated by a newer version of protoc which is
+#error incompatible with your Protocol Buffer headers. Please update
+#error your headers.
+#endif
+#if 2003000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#error This file was generated by an older version of protoc which is
+#error incompatible with your Protocol Buffer headers. Please
+#error regenerate this file with a newer version of protoc.
+#endif
+
+#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/repeated_field.h>
+#include <google/protobuf/extension_set.h>
+#include <google/protobuf/generated_message_reflection.h>
+// @@protoc_insertion_point(includes)
+
+namespace ww10 {
+
+// Internal implementation detail -- do not call these.
+void protobuf_AddDesc_WW10_5fprotocol_2eproto();
+void protobuf_AssignDesc_WW10_5fprotocol_2eproto();
+void protobuf_ShutdownFile_WW10_5fprotocol_2eproto();
+
+class PrologBotDescription;
+
+// ===================================================================
+
+class PrologBotDescription : public ::google::protobuf::Message {
+ public:
+ PrologBotDescription();
+ virtual ~PrologBotDescription();
+
+ PrologBotDescription(const PrologBotDescription& from);
+
+ inline PrologBotDescription& operator=(const PrologBotDescription& from)
{
+ CopyFrom(from);
+ return *this;
+ }
+
+ inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const
{
+ return _unknown_fields_;
+ }
+
+ inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
+ return &_unknown_fields_;
+ }
+
+ static const ::google::protobuf::Descriptor* descriptor();
+ static const PrologBotDescription& default_instance();
+
+ void Swap(PrologBotDescription* other);
+
+ // implements Message ----------------------------------------------
+
+ PrologBotDescription* New() const;
+ void CopyFrom(const ::google::protobuf::Message& from);
+ void MergeFrom(const ::google::protobuf::Message& from);
+ void CopyFrom(const PrologBotDescription& from);
+ void MergeFrom(const PrologBotDescription& from);
+ void Clear();
+ bool IsInitialized() const;
+
+ int ByteSize() const;
+ bool MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input);
+ void SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const;
+ ::google::protobuf::uint8*
SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
+ int GetCachedSize() const { return _cached_size_; }
+ private:
+ void SharedCtor();
+ void SharedDtor();
+ void SetCachedSize(int size) const;
+ public:
+
+ ::google::protobuf::Metadata GetMetadata() const;
+
+ // nested types ----------------------------------------------------
+
+ // accessors -------------------------------------------------------
+
+ // required int32 id = 1;
+ inline bool has_id() const;
+ inline void clear_id();
+ static const int kIdFieldNumber = 1;
+ inline ::google::protobuf::int32 id() const;
+ inline void set_id(::google::protobuf::int32 value);
+
+ // required string name = 2;
+ inline bool has_name() const;
+ inline void clear_name();
+ static const int kNameFieldNumber = 2;
+ inline const ::std::string& name() const;
+ inline void set_name(const ::std::string& value);
+ inline void set_name(const char* value);
+ inline void set_name(const char* value, size_t size);
+ inline ::std::string* mutable_name();
+
+ // required string prolog = 3;
+ inline bool has_prolog() const;
+ inline void clear_prolog();
+ static const int kPrologFieldNumber = 3;
+ inline const ::std::string& prolog() const;
+ inline void set_prolog(const ::std::string& value);
+ inline void set_prolog(const char* value);
+ inline void set_prolog(const char* value, size_t size);
+ inline ::std::string* mutable_prolog();
+
+ // @@protoc_insertion_point(class_scope:ww10.PrologBotDescription)
+ private:
+ ::google::protobuf::UnknownFieldSet _unknown_fields_;
+ mutable int _cached_size_;
+
+ ::google::protobuf::int32 id_;
+ ::std::string* name_;
+ static const ::std::string _default_name_;
+ ::std::string* prolog_;
+ static const ::std::string _default_prolog_;
+ friend void protobuf_AddDesc_WW10_5fprotocol_2eproto();
+ friend void protobuf_AssignDesc_WW10_5fprotocol_2eproto();
+ friend void protobuf_ShutdownFile_WW10_5fprotocol_2eproto();
+
+ ::google::protobuf::uint32 _has_bits_[(3 + 31) / 32];
+
+ // WHY DOES & HAVE LOWER PRECEDENCE THAN != !?
+ inline bool _has_bit(int index) const {
+ return (_has_bits_[index / 32] & (1u << (index % 32))) != 0;
+ }
+ inline void _set_bit(int index) {
+ _has_bits_[index / 32] |= (1u << (index % 32));
+ }
+ inline void _clear_bit(int index) {
+ _has_bits_[index / 32] &= ~(1u << (index % 32));
+ }
+
+ void InitAsDefaultInstance();
+ static PrologBotDescription* default_instance_;
+};
+// ===================================================================
+
+
+// ===================================================================
+
+// PrologBotDescription
+
+// required int32 id = 1;
+inline bool PrologBotDescription::has_id() const {
+ return _has_bit(0);
+}
+inline void PrologBotDescription::clear_id() {
+ id_ = 0;
+ _clear_bit(0);
+}
+inline ::google::protobuf::int32 PrologBotDescription::id() const {
+ return id_;
+}
+inline void PrologBotDescription::set_id(::google::protobuf::int32 value) {
+ _set_bit(0);
+ id_ = value;
+}
+
+// required string name = 2;
+inline bool PrologBotDescription::has_name() const {
+ return _has_bit(1);
+}
+inline void PrologBotDescription::clear_name() {
+ if (name_ != &_default_name_) {
+ name_->clear();
+ }
+ _clear_bit(1);
+}
+inline const ::std::string& PrologBotDescription::name() const {
+ return *name_;
+}
+inline void PrologBotDescription::set_name(const ::std::string& value) {
+ _set_bit(1);
+ if (name_ == &_default_name_) {
+ name_ = new ::std::string;
+ }
+ name_->assign(value);
+}
+inline void PrologBotDescription::set_name(const char* value) {
+ _set_bit(1);
+ if (name_ == &_default_name_) {
+ name_ = new ::std::string;
+ }
+ name_->assign(value);
+}
+inline void PrologBotDescription::set_name(const char* value, size_t size)
{
+ _set_bit(1);
+ if (name_ == &_default_name_) {
+ name_ = new ::std::string;
+ }
+ name_->assign(reinterpret_cast<const char*>(value), size);
+}
+inline ::std::string* PrologBotDescription::mutable_name() {
+ _set_bit(1);
+ if (name_ == &_default_name_) {
+ name_ = new ::std::string;
+ }
+ return name_;
+}
+
+// required string prolog = 3;
+inline bool PrologBotDescription::has_prolog() const {
+ return _has_bit(2);
+}
+inline void PrologBotDescription::clear_prolog() {
+ if (prolog_ != &_default_prolog_) {
+ prolog_->clear();
+ }
+ _clear_bit(2);
+}
+inline const ::std::string& PrologBotDescription::prolog() const {
+ return *prolog_;
+}
+inline void PrologBotDescription::set_prolog(const ::std::string& value) {
+ _set_bit(2);
+ if (prolog_ == &_default_prolog_) {
+ prolog_ = new ::std::string;
+ }
+ prolog_->assign(value);
+}
+inline void PrologBotDescription::set_prolog(const char* value) {
+ _set_bit(2);
+ if (prolog_ == &_default_prolog_) {
+ prolog_ = new ::std::string;
+ }
+ prolog_->assign(value);
+}
+inline void PrologBotDescription::set_prolog(const char* value, size_t
size) {
+ _set_bit(2);
+ if (prolog_ == &_default_prolog_) {
+ prolog_ = new ::std::string;
+ }
+ prolog_->assign(reinterpret_cast<const char*>(value), size);
+}
+inline ::std::string* PrologBotDescription::mutable_prolog() {
+ _set_bit(2);
+ if (prolog_ == &_default_prolog_) {
+ prolog_ = new ::std::string;
+ }
+ return prolog_;
+}
+
+
+// @@protoc_insertion_point(namespace_scope)
+
+} // namespace ww10
+
+#ifndef SWIG
+namespace google {
+namespace protobuf {
+
+
+} // namespace google
+} // namespace protobuf
+#endif // SWIG
+
+// @@protoc_insertion_point(global_scope)
+
+#endif // PROTOBUF_WW10_5fprotocol_2eproto__INCLUDED
=======================================
--- /dev/null
+++ /data/prologbot/java/ww10/WW10Protocol.java Sun Nov 7 06:35:47 2010
@@ -0,0 +1,425 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: WW10_protocol.proto
+
+package ww10;
+
+public final class WW10Protocol {
+ private WW10Protocol() {}
+ public static void registerAllExtensions(
+ com.google.protobuf.ExtensionRegistry registry) {
+ }
+ public static final class PrologBotDescription extends
+ com.google.protobuf.GeneratedMessage {
+ // Use PrologBotDescription.newBuilder() to construct.
+ private PrologBotDescription() {
+ initFields();
+ }
+ private PrologBotDescription(boolean noInit) {}
+
+ private static final PrologBotDescription defaultInstance;
+ public static PrologBotDescription getDefaultInstance() {
+ return defaultInstance;
+ }
+
+ public PrologBotDescription getDefaultInstanceForType() {
+ return defaultInstance;
+ }
+
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return
ww10.WW10Protocol.internal_static_ww10_PrologBotDescription_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return
ww10.WW10Protocol.internal_static_ww10_PrologBotDescription_fieldAccessorTable;
+ }
+
+ // required int32 id = 1;
+ public static final int ID_FIELD_NUMBER = 1;
+ private boolean hasId;
+ private int id_ = 0;
+ public boolean hasId() { return hasId; }
+ public int getId() { return id_; }
+
+ // required string name = 2;
+ public static final int NAME_FIELD_NUMBER = 2;
+ private boolean hasName;
+ private java.lang.String name_ = "";
+ public boolean hasName() { return hasName; }
+ public java.lang.String getName() { return name_; }
+
+ // required string prolog = 3;
+ public static final int PROLOG_FIELD_NUMBER = 3;
+ private boolean hasProlog;
+ private java.lang.String prolog_ = "";
+ public boolean hasProlog() { return hasProlog; }
+ public java.lang.String getProlog() { return prolog_; }
+
+ private void initFields() {
+ }
+ public final boolean isInitialized() {
+ if (!hasId) return false;
+ if (!hasName) return false;
+ if (!hasProlog) return false;
+ return true;
+ }
+
+ public void writeTo(com.google.protobuf.CodedOutputStream output)
+ throws java.io.IOException {
+ getSerializedSize();
+ if (hasId()) {
+ output.writeInt32(1, getId());
+ }
+ if (hasName()) {
+ output.writeString(2, getName());
+ }
+ if (hasProlog()) {
+ output.writeString(3, getProlog());
+ }
+ getUnknownFields().writeTo(output);
+ }
+
+ private int memoizedSerializedSize = -1;
+ public int getSerializedSize() {
+ int size = memoizedSerializedSize;
+ if (size != -1) return size;
+
+ size = 0;
+ if (hasId()) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeInt32Size(1, getId());
+ }
+ if (hasName()) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeStringSize(2, getName());
+ }
+ if (hasProlog()) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeStringSize(3, getProlog());
+ }
+ size += getUnknownFields().getSerializedSize();
+ memoizedSerializedSize = size;
+ return size;
+ }
+
+ public static ww10.WW10Protocol.PrologBotDescription parseFrom(
+ com.google.protobuf.ByteString data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return newBuilder().mergeFrom(data).buildParsed();
+ }
+ public static ww10.WW10Protocol.PrologBotDescription parseFrom(
+ com.google.protobuf.ByteString data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return newBuilder().mergeFrom(data, extensionRegistry)
+ .buildParsed();
+ }
+ public static ww10.WW10Protocol.PrologBotDescription parseFrom(byte[]
data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return newBuilder().mergeFrom(data).buildParsed();
+ }
+ public static ww10.WW10Protocol.PrologBotDescription parseFrom(
+ byte[] data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return newBuilder().mergeFrom(data, extensionRegistry)
+ .buildParsed();
+ }
+ public static ww10.WW10Protocol.PrologBotDescription
parseFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return newBuilder().mergeFrom(input).buildParsed();
+ }
+ public static ww10.WW10Protocol.PrologBotDescription parseFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return newBuilder().mergeFrom(input, extensionRegistry)
+ .buildParsed();
+ }
+ public static ww10.WW10Protocol.PrologBotDescription
parseDelimitedFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ Builder builder = newBuilder();
+ if (builder.mergeDelimitedFrom(input)) {
+ return builder.buildParsed();
+ } else {
+ return null;
+ }
+ }
+ public static ww10.WW10Protocol.PrologBotDescription
parseDelimitedFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ Builder builder = newBuilder();
+ if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
+ return builder.buildParsed();
+ } else {
+ return null;
+ }
+ }
+ public static ww10.WW10Protocol.PrologBotDescription parseFrom(
+ com.google.protobuf.CodedInputStream input)
+ throws java.io.IOException {
+ return newBuilder().mergeFrom(input).buildParsed();
+ }
+ public static ww10.WW10Protocol.PrologBotDescription parseFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return newBuilder().mergeFrom(input, extensionRegistry)
+ .buildParsed();
+ }
+
+ public static Builder newBuilder() { return Builder.create(); }
+ public Builder newBuilderForType() { return newBuilder(); }
+ public static Builder
newBuilder(ww10.WW10Protocol.PrologBotDescription prototype) {
+ return newBuilder().mergeFrom(prototype);
+ }
+ public Builder toBuilder() { return newBuilder(this); }
+
+ public static final class Builder extends
+ com.google.protobuf.GeneratedMessage.Builder<Builder> {
+ private ww10.WW10Protocol.PrologBotDescription result;
+
+ // Construct using
ww10.WW10Protocol.PrologBotDescription.newBuilder()
+ private Builder() {}
+
+ private static Builder create() {
+ Builder builder = new Builder();
+ builder.result = new ww10.WW10Protocol.PrologBotDescription();
+ return builder;
+ }
+
+ protected ww10.WW10Protocol.PrologBotDescription internalGetResult()
{
+ return result;
+ }
+
+ public Builder clear() {
+ if (result == null) {
+ throw new IllegalStateException(
+ "Cannot call clear() after build().");
+ }
+ result = new ww10.WW10Protocol.PrologBotDescription();
+ return this;
+ }
+
+ public Builder clone() {
+ return create().mergeFrom(result);
+ }
+
+ public com.google.protobuf.Descriptors.Descriptor
+ getDescriptorForType() {
+ return ww10.WW10Protocol.PrologBotDescription.getDescriptor();
+ }
+
+ public ww10.WW10Protocol.PrologBotDescription
getDefaultInstanceForType() {
+ return ww10.WW10Protocol.PrologBotDescription.getDefaultInstance();
+ }
+
+ public boolean isInitialized() {
+ return result.isInitialized();
+ }
+ public ww10.WW10Protocol.PrologBotDescription build() {
+ if (result != null && !isInitialized()) {
+ throw newUninitializedMessageException(result);
+ }
+ return buildPartial();
+ }
+
+ private ww10.WW10Protocol.PrologBotDescription buildParsed()
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ if (!isInitialized()) {
+ throw newUninitializedMessageException(
+ result).asInvalidProtocolBufferException();
+ }
+ return buildPartial();
+ }
+
+ public ww10.WW10Protocol.PrologBotDescription buildPartial() {
+ if (result == null) {
+ throw new IllegalStateException(
+ "build() has already been called on this Builder.");
+ }
+ ww10.WW10Protocol.PrologBotDescription returnMe = result;
+ result = null;
+ return returnMe;
+ }
+
+ public Builder mergeFrom(com.google.protobuf.Message other) {
+ if (other instanceof ww10.WW10Protocol.PrologBotDescription) {
+ return mergeFrom((ww10.WW10Protocol.PrologBotDescription)other);
+ } else {
+ super.mergeFrom(other);
+ return this;
+ }
+ }
+
+ public Builder mergeFrom(ww10.WW10Protocol.PrologBotDescription
other) {
+ if (other ==
ww10.WW10Protocol.PrologBotDescription.getDefaultInstance()) return this;
+ if (other.hasId()) {
+ setId(other.getId());
+ }
+ if (other.hasName()) {
+ setName(other.getName());
+ }
+ if (other.hasProlog()) {
+ setProlog(other.getProlog());
+ }
+ this.mergeUnknownFields(other.getUnknownFields());
+ return this;
+ }
+
+ public Builder mergeFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+ com.google.protobuf.UnknownFieldSet.newBuilder(
+ this.getUnknownFields());
+ while (true) {
+ int tag = input.readTag();
+ switch (tag) {
+ case 0:
+ this.setUnknownFields(unknownFields.build());
+ return this;
+ default: {
+ if (!parseUnknownField(input, unknownFields,
+ extensionRegistry, tag)) {
+ this.setUnknownFields(unknownFields.build());
+ return this;
+ }
+ break;
+ }
+ case 8: {
+ setId(input.readInt32());
+ break;
+ }
+ case 18: {
+ setName(input.readString());
+ break;
+ }
+ case 26: {
+ setProlog(input.readString());
+ break;
+ }
+ }
+ }
+ }
+
+
+ // required int32 id = 1;
+ public boolean hasId() {
+ return result.hasId();
+ }
+ public int getId() {
+ return result.getId();
+ }
+ public Builder setId(int value) {
+ result.hasId = true;
+ result.id_ = value;
+ return this;
+ }
+ public Builder clearId() {
+ result.hasId = false;
+ result.id_ = 0;
+ return this;
+ }
+
+ // required string name = 2;
+ public boolean hasName() {
+ return result.hasName();
+ }
+ public java.lang.String getName() {
+ return result.getName();
+ }
+ public Builder setName(java.lang.String value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ result.hasName = true;
+ result.name_ = value;
+ return this;
+ }
+ public Builder clearName() {
+ result.hasName = false;
+ result.name_ = getDefaultInstance().getName();
+ return this;
+ }
+
+ // required string prolog = 3;
+ public boolean hasProlog() {
+ return result.hasProlog();
+ }
+ public java.lang.String getProlog() {
+ return result.getProlog();
+ }
+ public Builder setProlog(java.lang.String value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ result.hasProlog = true;
+ result.prolog_ = value;
+ return this;
+ }
+ public Builder clearProlog() {
+ result.hasProlog = false;
+ result.prolog_ = getDefaultInstance().getProlog();
+ return this;
+ }
+
+ // @@protoc_insertion_point(builder_scope:ww10.PrologBotDescription)
+ }
+
+ static {
+ defaultInstance = new PrologBotDescription(true);
+ ww10.WW10Protocol.internalForceInit();
+ defaultInstance.initFields();
+ }
+
+ // @@protoc_insertion_point(class_scope:ww10.PrologBotDescription)
+ }
+
+ private static com.google.protobuf.Descriptors.Descriptor
+ internal_static_ww10_PrologBotDescription_descriptor;
+ private static
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internal_static_ww10_PrologBotDescription_fieldAccessorTable;
+
+ public static com.google.protobuf.Descriptors.FileDescriptor
+ getDescriptor() {
+ return descriptor;
+ }
+ private static com.google.protobuf.Descriptors.FileDescriptor
+ descriptor;
+ static {
+ java.lang.String[] descriptorData = {
+ "\n\023WW10_protocol.proto\022\004ww10\"@\n\024PrologBot" +
+ "Description\022\n\n\002id\030\001
\002(\005\022\014\n\004name\030\002 \002(\t\022\016\n" +
+ "\006prolog\030\003 \002(\t"
+ };
+
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner
assigner =
+ new
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner()
{
+ public com.google.protobuf.ExtensionRegistry assignDescriptors(
+ com.google.protobuf.Descriptors.FileDescriptor root) {
+ descriptor = root;
+ internal_static_ww10_PrologBotDescription_descriptor =
+ getDescriptor().getMessageTypes().get(0);
+ internal_static_ww10_PrologBotDescription_fieldAccessorTable =
new
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+ internal_static_ww10_PrologBotDescription_descriptor,
+ new java.lang.String[] { "Id", "Name", "Prolog", },
+ ww10.WW10Protocol.PrologBotDescription.class,
+ ww10.WW10Protocol.PrologBotDescription.Builder.class);
+ return null;
+ }
+ };
+ com.google.protobuf.Descriptors.FileDescriptor
+ .internalBuildGeneratedFileFrom(descriptorData,
+ new com.google.protobuf.Descriptors.FileDescriptor[] {
+ }, assigner);
+ }
+
+ public static void internalForceInit() {}
+
+ // @@protoc_insertion_point(outer_class_scope)
+}
=======================================
--- /dev/null
+++ /lib/protobuf-java-2.3.0.jar Sun Nov 7 06:35:47 2010
Binary file, no diff available.
=======================================
--- /dev/null
+++ /src/bots/prologbot/PrologBot.java Sun Nov 7 06:35:47 2010
@@ -0,0 +1,303 @@
+package bots.prologbot;
+
+import game.NamedPlayer;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStreamReader;
+
+import org.apache.commons.io.FileUtils;
+
+import util.Utils;
+
+import com.biotools.meerkat.Action;
+import com.biotools.meerkat.Card;
+import com.biotools.meerkat.GameInfo;
+import com.biotools.meerkat.Hand;
+import com.biotools.meerkat.Player;
+import com.biotools.meerkat.util.Preferences;
+
+public class PrologBot implements Player, NamedPlayer {
+
+ private static String file_dir = "./data/prologbot/";
+
+ static {
+ File file = new File("/dev/shm/");
+ if (file.exists()) {
+ file_dir = "/dev/shm/";
+ try {
+ FileUtils.copyFileToDirectory(new File("./data/prologbot/
bk.pl"),
file);
+ } catch (IOException e) {
+ e.printStackTrace();
+ file_dir = "./data/prologbot/";
+ }
+ }
+ }
+
+ private final static File directory = new File(file_dir);
+
+ private int ourSeat; // our seat for the current hand
+ private Card c1, c2; // our hole cards
+ private GameInfo gi; // general game information
+ private Preferences prefs; // the configuration options for this bot
+
+ private boolean initialized = false;
+ private String name = "Unknown";
+
+ public PrologBot() {
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * An event called to tell us our hole cards and seat number
+ * @param c1 your first hole card
+ * @param c2 your second hole card
+ * @param seat your seat number at the table
+ */
+ public void holeCards(Card c1, Card c2, int seat) {
+ this.c1 = c1;
+ this.c2 = c2;
+ this.ourSeat = seat;
+ }
+
+ /**
+ * Requests an Action from the player
+ * Called when it is the Player's turn to act.
+ */
+ public Action getAction() {
+ try {
+ writeState();
+ return executeProlog();
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
+ } catch (InterruptedException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ /**
+ * Get the current settings for this bot.
+ */
+ public Preferences getPreferences() {
+ return prefs;
+ }
+
+ /**
+ * Load the current settings for this bot.
+ */
+ public void init(Preferences playerPrefs) {
+ this.prefs = playerPrefs;
+ }
+
+ /**
+ * @return true if debug mode is on.
+ */
+ public boolean getDebug() {
+ return prefs.getBooleanPreference("DEBUG", false);
+ }
+
+ /**
+ * print a debug statement.
+ */
+ public void debug(String str) {
+ if (getDebug()) {
+ System.out.println(str);
+ }
+ }
+
+ /**
+ * print a debug statement with no end of line character
+ */
+ public void debugb(String str) {
+ if (getDebug()) {
+ System.out.print(str);
+ }
+ }
+
+ /**
+ * A new betting round has started.
+ */
+ public void stageEvent(int stage) {
+ }
+
+ /**
+ * A showdown has occurred.
+ * @param pos the position of the player showing
+ * @param c1 the first hole card shown
+ * @param c2 the second hole card shown
+ */
+ public void showdownEvent(int seat, Card c1, Card c2) {
+ }
+
+ /**
+ * A new game has been started.
+ * @param gi the game stat information
+ */
+ public void gameStartEvent(GameInfo gInfo) {
+
this.gi = gInfo;
+ }
+
+ /**
+ * An event sent when all players are being dealt their hole cards
+ */
+ public void dealHoleCardsEvent() {
+ }
+
+ /**
+ * An action has been observed.
+ */
+ public void actionEvent(int pos, Action act) {
+ }
+
+ /**
+ * The game info state has been updated
+ * Called after an action event has been fully processed
+ */
+ public void gameStateChanged() {
+ }
+
+ /**
+ * The hand is now over.
+ */
+ public void gameOverEvent() {
+ }
+
+ /**
+ * A player at pos has won amount with the hand handName
+ */
+ public void winEvent(int pos, double amount, String handName) {
+ }
+
+ private final String n = System.getProperty("line.separator");
+
+ public synchronized void writeBot(String prolog) throws IOException {
+ File file = new File(file_dir, name + ".pl");
+ FileWriter out2 = new FileWriter(file);
+ BufferedWriter out = new BufferedWriter(out2);
+ out.write("% Generated by server" + n);
+ out.write(":- include(bk)." + n);
+ out.write(":- include(state)." + n);
+ out.write("" + n);
+ out.write("% Generated by client" + n);
+ out.write(prolog);
+ out.close();
+ out2.close();
+ initialized = true;
+ }
+
+ public synchronized void writeState() throws IOException {
+ if (initialized) {
+ FileWriter out2 = new FileWriter(new File(file_dir, "
state.pl"));
+ BufferedWriter out = new BufferedWriter(out2);
+ if (gi.isPreFlop()) {
+ out.write("round(preflop)." + n);
+ } else if (gi.isFlop()) {
+ out.write("round(flop)." + n);
+ } else if (gi.isTurn()) {
+ out.write("round(turn)." + n);
+ } else if (gi.isRiver()) {
+ out.write("round(river)." + n);
+ } else {
+ throw new IllegalStateException();
+ }
+ out.write("handcards([" + cardToString(c1) + "," + cardToString(c2)
+ "])." + n);
+ out.write("communitycards([");
+ Hand h = gi.getBoard();
+ for (int i = 0; i < h.size(); i++) {
+ if (i > 0) {
+ out.write(",");
+ }
+ out.write(cardToString(h.getCard(i)));
+ }
+ out.write("])." + n);
+ out.write("deficit(" + gi.getAmountToCall(ourSeat) + ")." + n);
+ out.close();
+ out2.close();
+ }
+ }
+
+ public String cardToString(Card c) {
+ String suit;
+ if (c.getSuit() == Card.CLUBS) {
+ suit = "c";
+ } else if (c.getSuit() == Card.SPADES) {
+ suit = "s";
+ } else if (c.getSuit() == Card.HEARTS) {
+ suit = "h";
+ } else if (c.getSuit() == Card.DIAMONDS) {
+ suit = "d";
+ } else {
+ throw new IllegalStateException();
+ }
+ return "card(" + c.getRank() + "," + suit + ")";
+ }
+
+ public synchronized Action executeProlog() throws IOException,
InterruptedException {
+ double toCall = gi.getAmountToCall(ourSeat);
+ if (initialized) {
+ if (toCall == 0.0D) {
+ return Action.checkAction();
+ }
+ ProcessBuilder pb = new ProcessBuilder("yap", "-l", name
+ ".pl", "-g", "evaluate", "-q");
+ pb.directory(directory);
+ Process p = pb.start();
+ int exitValue = p.waitFor();
+ if (exitValue != 0) {
+ throw new IllegalStateException();
+ }
+ InputStreamReader in = new InputStreamReader(p.getInputStream());
+ BufferedReader result = new BufferedReader(in);
+ String output = result.readLine();
+ result.close();
+ in.close();
+ if (output.equals("fold")) {
+ if (toCall == 0.0D) {
+ return Action.checkAction();
+ } else {
+ return Action.foldAction(toCall);
+ }
+ } else if (output.equals("call")) {
+ if (toCall == 0.0D) {
+ return Action.checkAction();
+ } else {
+ return Action.callAction(toCall);
+ }
+ } else if (output.startsWith("raise(")) {
+ double wantedRaiseAmount =
Double.parseDouble(output.substring(output.indexOf("(") + 1,
output.indexOf(")")));
+ if (gi.getAmountToCall(ourSeat) > 0) {
+ if (gi.getBankRoll(ourSeat) > gi.getAmountToCall(ourSeat)) {
+ double maxPossibleRaise = Utils.roundToCents(gi.getBankRoll(ourSeat)
- gi.getAmountToCall(ourSeat));
+ if (maxPossibleRaise < wantedRaiseAmount) {
+ wantedRaiseAmount = maxPossibleRaise;
+ }
+ return Action.raiseAction(gi, wantedRaiseAmount);
+ } else {
+ return Action.callAction(gi);
+ }
+ } else {
+ if (gi.getBankRoll(ourSeat) < wantedRaiseAmount) {
+ wantedRaiseAmount = gi.getBankRoll(ourSeat);
+ }
+ return Action.betAction(wantedRaiseAmount);
+ }
+ } else {
+ return Action.foldAction(toCall);
+ }
+ } else {
+ // avoid crazy fast games
+ Thread.sleep(10);
+ return Action.foldAction(toCall);
+ }
+ }
+
+ @Override
+ public void setIngameName(String name) {
+
this.name = name;
+ }
+}
=======================================
--- /dev/null
+++ /src/game/NamedPlayer.java Sun Nov 7 06:35:47 2010
@@ -0,0 +1,9 @@
+package game;
+
+import com.biotools.meerkat.Player;
+
+public interface NamedPlayer extends Player {
+
+ void setIngameName(String name);
+
+}
=======================================
--- /dev/null
+++ /src/ww10/DummyClient.java Sun Nov 7 06:35:47 2010
@@ -0,0 +1,40 @@
+package ww10;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.Socket;
+
+import ww10.WW10Protocol.PrologBotDescription;
+
+public class DummyClient {
+
+ public static void main(String[] args) {
+ for (int i = 0; i < 5; i++) {
+ try {
+ Socket socket = new Socket("localhost", 20000);
+ String n = "\n";
+ PrologBotDescription msg = WW10Protocol.PrologBotDescription
+ .newBuilder()
+ .setId(i)
+ .setName("Tias")
+ .setProlog(
+ "do(raise(10)) :- round(preflop), handcards(C), pair(C), !." + n
+ + "do(fold) :- round(preflop), deficit(D), bigblind(BB), D >=
1.5*BB, !." + n + "do(call) :- round(preflop), !." + n
+ + "do(fold) :- (round(flop);round(turn)), deficit(D),
bigblind(BB), D >= 2*BB, !." + n
+ + "do(call) :- (round(flop);round(turn)), !." + n
+ + "do(raise(10)) :- round(river), allcards(C), handeval(C,H),
(H==straight;H==flush;H==fourofakind;H==fullhouse), !."
+ + n + "do(fold) :- round(river), allcards(C),
handeval(C,highcard), !." + n + "do(call) :- !.").build();
+ OutputStream outputStream = socket.getOutputStream();
+ InputStream inputStream = socket.getInputStream();
+ msg.writeTo(outputStream);
+ outputStream.close();
+ inputStream.close();
+ socket.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ System.exit(-1);
+ }
+ }
+ }
+}
=======================================
--- /dev/null
+++ /src/ww10/PrologBotServer.java Sun Nov 7 06:35:47 2010
@@ -0,0 +1,89 @@
+package ww10;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.ServerSocket;
+import java.net.Socket;
+
+import ww10.WW10Protocol.PrologBotDescription;
+
+public class PrologBotServer implements Runnable {
+
+ public final int port;
+
+ private boolean running = true;
+
+ private ServerSocket serverSocket;
+
+ public PrologBotServer() {
+ this(20000);
+ }
+
+ public PrologBotServer(int port) {
+ this.port = port;
+ try {
+ serverSocket = new ServerSocket(port);
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ e.printStackTrace();
+ System.out.println("Could not listen on port: " + port);
+ System.exit(-1);
+ }
+ }
+
+ public void stop() throws IOException {
+ running = false;
+ serverSocket.close();
+ }
+
+ @Override
+ public void run() {
+ while (running) {
+ Socket clientSocket = null;
+ try {
+ clientSocket = serverSocket.accept();
+ System.out.println("Incoming connection");
+ InputStream inputStream = clientSocket.getInputStream();
+ OutputStream outputStream = clientSocket.getOutputStream();
+ read(inputStream);
+ inputStream.close();
+ outputStream.close();
+ clientSocket.close();
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ e.printStackTrace();
+ System.out.println("Accept failed: 4444");
+ System.exit(-1);
+ }
+ }
+
+ }
+
+ private void read(InputStream inputStream) {
+ try {
+ PrologBotDescription bot = PrologBotDescription.parseFrom(inputStream);
+ onNewBot(bot);
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ e.printStackTrace();
+ System.out.println("Could not parse from inputstream.");
+ System.exit(-1);
+ }
+
+ }
+
+ protected void onNewBot(PrologBotDescription bot) {
+
+ }
+
+ public static void main(String[] args) {
+ (new PrologBotServer() {
+ @Override
+ protected void onNewBot(PrologBotDescription bot) {
+ System.out.println(bot.toString());
+ }
+ }).run();
+ }
+
+}
=======================================
--- /dev/null
+++ /src/ww10/WW10Protocol.java Sun Nov 7 06:35:47 2010
@@ -0,0 +1,425 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: WW10_protocol.proto
+
+package ww10;
+
+public final class WW10Protocol {
+ private WW10Protocol() {}
+ public static void registerAllExtensions(
+ com.google.protobuf.ExtensionRegistry registry) {
+ }
+ public static final class PrologBotDescription extends
+ com.google.protobuf.GeneratedMessage {
+ // Use PrologBotDescription.newBuilder() to construct.
+ private PrologBotDescription() {
+ initFields();
+ }
+ private PrologBotDescription(boolean noInit) {}
+
+ private static final PrologBotDescription defaultInstance;
+ public static PrologBotDescription getDefaultInstance() {
+ return defaultInstance;
+ }
+
+ public PrologBotDescription getDefaultInstanceForType() {
+ return defaultInstance;
+ }
+
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return
ww10.WW10Protocol.internal_static_ww10_PrologBotDescription_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return
ww10.WW10Protocol.internal_static_ww10_PrologBotDescription_fieldAccessorTable;
+ }
+
+ // required int32 id = 1;
+ public static final int ID_FIELD_NUMBER = 1;
+ private boolean hasId;
+ private int id_ = 0;
+ public boolean hasId() { return hasId; }
+ public int getId() { return id_; }
+
+ // required string name = 2;
+ public static final int NAME_FIELD_NUMBER = 2;
+ private boolean hasName;
+ private java.lang.String name_ = "";
+ public boolean hasName() { return hasName; }
+ public java.lang.String getName() { return name_; }
+
+ // required string prolog = 3;
+ public static final int PROLOG_FIELD_NUMBER = 3;
+ private boolean hasProlog;
+ private java.lang.String prolog_ = "";
+ public boolean hasProlog() { return hasProlog; }
+ public java.lang.String getProlog() { return prolog_; }
+
+ private void initFields() {
+ }
+ public final boolean isInitialized() {
+ if (!hasId) return false;
+ if (!hasName) return false;
+ if (!hasProlog) return false;
+ return true;
+ }
+
+ public void writeTo(com.google.protobuf.CodedOutputStream output)
+ throws java.io.IOException {
+ getSerializedSize();
+ if (hasId()) {
+ output.writeInt32(1, getId());
+ }
+ if (hasName()) {
+ output.writeString(2, getName());
+ }
+ if (hasProlog()) {
+ output.writeString(3, getProlog());
+ }
+ getUnknownFields().writeTo(output);
+ }
+
+ private int memoizedSerializedSize = -1;
+ public int getSerializedSize() {
+ int size = memoizedSerializedSize;
+ if (size != -1) return size;
+
+ size = 0;
+ if (hasId()) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeInt32Size(1, getId());
+ }
+ if (hasName()) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeStringSize(2, getName());
+ }
+ if (hasProlog()) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeStringSize(3, getProlog());
+ }
+ size += getUnknownFields().getSerializedSize();
+ memoizedSerializedSize = size;
+ return size;
+ }
+
+ public static ww10.WW10Protocol.PrologBotDescription parseFrom(
+ com.google.protobuf.ByteString data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return newBuilder().mergeFrom(data).buildParsed();
+ }
+ public static ww10.WW10Protocol.PrologBotDescription parseFrom(
+ com.google.protobuf.ByteString data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return newBuilder().mergeFrom(data, extensionRegistry)
+ .buildParsed();
+ }
+ public static ww10.WW10Protocol.PrologBotDescription parseFrom(byte[]
data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return newBuilder().mergeFrom(data).buildParsed();
+ }
+ public static ww10.WW10Protocol.PrologBotDescription parseFrom(
+ byte[] data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return newBuilder().mergeFrom(data, extensionRegistry)
+ .buildParsed();
+ }
+ public static ww10.WW10Protocol.PrologBotDescription
parseFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return newBuilder().mergeFrom(input).buildParsed();
+ }
+ public static ww10.WW10Protocol.PrologBotDescription parseFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return newBuilder().mergeFrom(input, extensionRegistry)
+ .buildParsed();
+ }
+ public static ww10.WW10Protocol.PrologBotDescription
parseDelimitedFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ Builder builder = newBuilder();
+ if (builder.mergeDelimitedFrom(input)) {
+ return builder.buildParsed();
+ } else {
+ return null;
+ }
+ }
+ public static ww10.WW10Protocol.PrologBotDescription
parseDelimitedFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ Builder builder = newBuilder();
+ if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
+ return builder.buildParsed();
+ } else {
+ return null;
+ }
+ }
+ public static ww10.WW10Protocol.PrologBotDescription parseFrom(
+ com.google.protobuf.CodedInputStream input)
+ throws java.io.IOException {
+ return newBuilder().mergeFrom(input).buildParsed();
+ }
+ public static ww10.WW10Protocol.PrologBotDescription parseFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return newBuilder().mergeFrom(input, extensionRegistry)
+ .buildParsed();
+ }
+
+ public static Builder newBuilder() { return Builder.create(); }
+ public Builder newBuilderForType() { return newBuilder(); }
+ public static Builder
newBuilder(ww10.WW10Protocol.PrologBotDescription prototype) {
+ return newBuilder().mergeFrom(prototype);
+ }
+ public Builder toBuilder() { return newBuilder(this); }
+
+ public static final class Builder extends
+ com.google.protobuf.GeneratedMessage.Builder<Builder> {
+ private ww10.WW10Protocol.PrologBotDescription result;
+
+ // Construct using
ww10.WW10Protocol.PrologBotDescription.newBuilder()
+ private Builder() {}
+
+ private static Builder create() {
+ Builder builder = new Builder();
+ builder.result = new ww10.WW10Protocol.PrologBotDescription();
+ return builder;
+ }
+
+ protected ww10.WW10Protocol.PrologBotDescription internalGetResult()
{
+ return result;
+ }
+
+ public Builder clear() {
+ if (result == null) {
+ throw new IllegalStateException(
+ "Cannot call clear() after build().");
+ }
+ result = new ww10.WW10Protocol.PrologBotDescription();
+ return this;
+ }
+
+ public Builder clone() {
+ return create().mergeFrom(result);
+ }
+
+ public com.google.protobuf.Descriptors.Descriptor
+ getDescriptorForType() {
+ return ww10.WW10Protocol.PrologBotDescription.getDescriptor();
+ }
+
+ public ww10.WW10Protocol.PrologBotDescription
getDefaultInstanceForType() {
+ return ww10.WW10Protocol.PrologBotDescription.getDefaultInstance();
+ }
+
+ public boolean isInitialized() {
+ return result.isInitialized();
+ }
+ public ww10.WW10Protocol.PrologBotDescription build() {
+ if (result != null && !isInitialized()) {
+ throw newUninitializedMessageException(result);
+ }
+ return buildPartial();
+ }
+
+ private ww10.WW10Protocol.PrologBotDescription buildParsed()
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ if (!isInitialized()) {
+ throw newUninitializedMessageException(
+ result).asInvalidProtocolBufferException();
+ }
+ return buildPartial();
+ }
+
+ public ww10.WW10Protocol.PrologBotDescription buildPartial() {
+ if (result == null) {
+ throw new IllegalStateException(
+ "build() has already been called on this Builder.");
+ }
+ ww10.WW10Protocol.PrologBotDescription returnMe = result;
+ result = null;
+ return returnMe;
+ }
+
+ public Builder mergeFrom(com.google.protobuf.Message other) {
+ if (other instanceof ww10.WW10Protocol.PrologBotDescription) {
+ return mergeFrom((ww10.WW10Protocol.PrologBotDescription)other);
+ } else {
+ super.mergeFrom(other);
+ return this;
+ }
+ }
+
+ public Builder mergeFrom(ww10.WW10Protocol.PrologBotDescription
other) {
+ if (other ==
ww10.WW10Protocol.PrologBotDescription.getDefaultInstance()) return this;
+ if (other.hasId()) {
+ setId(other.getId());
+ }
+ if (other.hasName()) {
+ setName(other.getName());
+ }
+ if (other.hasProlog()) {
+ setProlog(other.getProlog());
+ }
+ this.mergeUnknownFields(other.getUnknownFields());
+ return this;
+ }
+
+ public Builder mergeFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+ com.google.protobuf.UnknownFieldSet.newBuilder(
+ this.getUnknownFields());
+ while (true) {
+ int tag = input.readTag();
+ switch (tag) {
+ case 0:
+ this.setUnknownFields(unknownFields.build());
+ return this;
+ default: {
+ if (!parseUnknownField(input, unknownFields,
+ extensionRegistry, tag)) {
+ this.setUnknownFields(unknownFields.build());
+ return this;
+ }
+ break;
+ }
+ case 8: {
+ setId(input.readInt32());
+ break;
+ }
+ case 18: {
+ setName(input.readString());
+ break;
+ }
+ case 26: {
+ setProlog(input.readString());
+ break;
+ }
+ }
+ }
+ }
+
+
+ // required int32 id = 1;
+ public boolean hasId() {
+ return result.hasId();
+ }
+ public int getId() {
+ return result.getId();
+ }
+ public Builder setId(int value) {
+ result.hasId = true;
+ result.id_ = value;
+ return this;
+ }
+ public Builder clearId() {
+ result.hasId = false;
+ result.id_ = 0;
+ return this;
+ }
+
+ // required string name = 2;
+ public boolean hasName() {
+ return result.hasName();
+ }
+ public java.lang.String getName() {
+ return result.getName();
+ }
+ public Builder setName(java.lang.String value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ result.hasName = true;
+ result.name_ = value;
+ return this;
+ }
+ public Builder clearName() {
+ result.hasName = false;
+ result.name_ = getDefaultInstance().getName();
+ return this;
+ }
+
+ // required string prolog = 3;
+ public boolean hasProlog() {
+ return result.hasProlog();
+ }
+ public java.lang.String getProlog() {
+ return result.getProlog();
+ }
+ public Builder setProlog(java.lang.String value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ result.hasProlog = true;
+ result.prolog_ = value;
+ return this;
+ }
+ public Builder clearProlog() {
+ result.hasProlog = false;
+ result.prolog_ = getDefaultInstance().getProlog();
+ return this;
+ }
+
+ // @@protoc_insertion_point(builder_scope:ww10.PrologBotDescription)
+ }
+
+ static {
+ defaultInstance = new PrologBotDescription(true);
+ ww10.WW10Protocol.internalForceInit();
+ defaultInstance.initFields();
+ }
+
+ // @@protoc_insertion_point(class_scope:ww10.PrologBotDescription)
+ }
+
+ private static com.google.protobuf.Descriptors.Descriptor
+ internal_static_ww10_PrologBotDescription_descriptor;
+ private static
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internal_static_ww10_PrologBotDescription_fieldAccessorTable;
+
+ public static com.google.protobuf.Descriptors.FileDescriptor
+ getDescriptor() {
+ return descriptor;
+ }
+ private static com.google.protobuf.Descriptors.FileDescriptor
+ descriptor;
+ static {
+ java.lang.String[] descriptorData = {
+ "\n\023WW10_protocol.proto\022\004ww10\"@\n\024PrologBot" +
+ "Description\022\n\n\002id\030\001
\002(\005\022\014\n\004name\030\002 \002(\t\022\016\n" +
+ "\006prolog\030\003 \002(\t"
+ };
+
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner
assigner =
+ new
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner()
{
+ public com.google.protobuf.ExtensionRegistry assignDescriptors(
+ com.google.protobuf.Descriptors.FileDescriptor root) {
+ descriptor = root;
+ internal_static_ww10_PrologBotDescription_descriptor =
+ getDescriptor().getMessageTypes().get(0);
+ internal_static_ww10_PrologBotDescription_fieldAccessorTable =
new
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+ internal_static_ww10_PrologBotDescription_descriptor,
+ new java.lang.String[] { "Id", "Name", "Prolog", },
+ ww10.WW10Protocol.PrologBotDescription.class,
+ ww10.WW10Protocol.PrologBotDescription.Builder.class);
+ return null;
+ }
+ };
+ com.google.protobuf.Descriptors.FileDescriptor
+ .internalBuildGeneratedFileFrom(descriptorData,
+ new com.google.protobuf.Descriptors.FileDescriptor[] {
+ }, assigner);
+ }
+
+ public static void internalForceInit() {}
+
+ // @@protoc_insertion_point(outer_class_scope)
+}
=======================================
--- /dev/null
+++ /src/ww10/WetenschapsweekStarter.java Sun Nov 7 06:35:47 2010
@@ -0,0 +1,102 @@
+package ww10;
+
+import game.CashGameDescription;
+import game.GameIDGenerator;
+import game.GameRunner;
+import game.HandHistoryWriter;
+import game.PublicGameInfo;
+import game.TableSeater;
+import game.deck.DeckFactory;
+import game.deck.RandomDeck;
+
+import java.io.FileWriter;
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import ww10.WW10Protocol.PrologBotDescription;
+import ww10.gui.DataModel;
+import bots.BotRepository;
+import bots.prologbot.PrologBot;
+
+import com.biotools.meerkat.GameObserver;
+
+public class WetenschapsweekStarter {
+
+ public static void main(String[] args) throws Exception {
+
+ // number of games
+ final int numGames = Integer.MAX_VALUE;
+ final int nbPlayers = 6;
+
+ // four Bots fight against each other
+ // valid BotNames can be obtained from the botRepository
+ String[] botNames = new String[nbPlayers];
+ String[] ingameNames = new String[nbPlayers];
+ for (int i = 0; i < nbPlayers; i++) {
+ if (i == nbPlayers - 1) {
+ botNames[i] = "DemoBot/SimpleBot";
+ ingameNames[i] = "SimpleBot";
+ } else {
+ botNames[i] = "PrologBot/PrologBot";
+ ingameNames[i] = "Player " + (i + 1);
+ }
+ }
+
+ BotRepository botRepository = new BotRepository();
+ TableSeater tableSeater = new TableSeater(botRepository, false);
+ GameIDGenerator gameIDGenerator = new GameIDGenerator(System.nanoTime());
+ HandHistoryWriter handHistoryWriter = new HandHistoryWriter();
+ String simulationFileName = new
SimpleDateFormat("yyMMdd-hhmm").format(new Date());
+ handHistoryWriter.setWriter(new FileWriter("./data/" +
simulationFileName + "-history.txt"));
+
+ // in the future created via GUI, and persisted via XML to
the ./data/games dir
+ CashGameDescription cashGameDescription = new CashGameDescription();
+ cashGameDescription.setSmallBlind(1);
+ cashGameDescription.setBigBlind(2);
+ cashGameDescription.setInitialBankRoll(200);
+ cashGameDescription.setNumGames(numGames);
+
+ cashGameDescription.setBotNames(botNames);
+ cashGameDescription.setInGameNames(ingameNames);
+
+ // start the game
+ GameRunner runner = cashGameDescription.createGameRunner();
+ final DataModel gui = new DataModel();
+ runner.addBankrollObserver(gui);
+ DeckFactory deckFactory = RandomDeck.createFactory();
+ List<GameObserver> observers = new ArrayList<GameObserver>();
+ // observers.add(handHistoryWriter);
+ observers.add(gui);
+ final PublicGameInfo gameInfo = runner.asyncRunGame(deckFactory,
tableSeater, gameIDGenerator, observers);
+
+ PrologBotServer server = new PrologBotServer() {
+
+ @Override
+ protected void onNewBot(PrologBotDescription botDescription) {
+ PrologBot bot = (PrologBot)
(gameInfo.getPlayer(botDescription.getId()).getBot());
+ try {
+ bot.writeBot(botDescription.getProlog());
+ gui.onSubmit(bot.getName(), truncate(botDescription.getName()));
+ } catch (IOException e) {
+ e.printStackTrace();
+ System.out.println("Could not write prolog code.");
+ System.exit(-1);
+ }
+ }
+
+ private String truncate(String name) {
+ if (name.length() > 20)
+ return name.substring(0, 20);
+ else
+ return name;
+ }
+
+ };
+
+ (new Thread(server, "PrologBotServer")).start();
+
+ }
+}
=======================================
--- /dev/null
+++ /src/ww10/gui/ActionPanel.java Sun Nov 7 06:35:47 2010
@@ -0,0 +1,78 @@
+package ww10.gui;
+
+import java.awt.Color;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.jfree.chart.ChartFactory;
+import org.jfree.chart.ChartPanel;
+import org.jfree.chart.JFreeChart;
+import org.jfree.chart.plot.MultiplePiePlot;
+import org.jfree.chart.plot.PiePlot;
+import org.jfree.data.category.DefaultCategoryDataset;
+import org.jfree.util.TableOrder;
+
+public class ActionPanel extends ChartPanel {
+
+ private static final long serialVersionUID = -534880050132416786L;
+
+ private final DataModel dataModel;
+
+ private final DefaultCategoryDataset dataset;
+
+ private final String[] rowKeys;
+
+ private final String[] columnKeys;
+
+ public ActionPanel(DataModel dataModel) {
+ super(null);
+ this.dataModel = dataModel;
+
+ String[] playerNames = dataModel.getPlayerNames();
+
+ double[][] data = new double[playerNames.length][5];
+
+ rowKeys = playerNames;
+ columnKeys = new String[] { "Check", "Bet", "Fold", "Call", "Raise" };
+
+ dataset = new DefaultCategoryDataset();
+ for (int r = 0; r < data.length; r++) {
+ String rowKey = rowKeys[r];
+ for (int c = 0; c < data[r].length; c++) {
+ String columnKey = columnKeys[c];
+ dataset.addValue(data[r][c], rowKey, columnKey);
+ }
+ }
+
+ final JFreeChart chart = ChartFactory.createMultiplePieChart(null, //
chart title
+ dataset, // dataset
+ TableOrder.BY_ROW, true, // include legend
+ true, false);
+ final MultiplePiePlot plot = (MultiplePiePlot) chart.getPlot();
+ final JFreeChart subchart = plot.getPieChart();
+ final PiePlot p = (PiePlot) subchart.getPlot();
+
+ p.setBackgroundPaint(Color.WHITE);
+
+ // p.setLabelGenerator(new StandardPieItemLabelGenerator("{0}"));
+ // p.setLabelFont(new Font("SansSerif", Font.PLAIN, 8));
+ // p.setInteriorGap(0.30);
+ p.setBackgroundPaint(null);
+ p.setOutlineStroke(null);
+
+ setChart(chart);
+ }
+
+ public void updateActionFrequencies(Map<String, int[]> freq) {
+ for (Entry<String, int[]> entry : freq.entrySet()) {
+ updateActionFrequencies(entry.getKey(), entry.getValue());
+ }
+ }
+
+ public void updateActionFrequencies(String player, int[] freq) {
+ for (int c = 0; c < freq.length; c++) {
+ String columnKey = columnKeys[c];
+ dataset.addValue(freq[c], player, columnKey);
+ }
+ }
+}
=======================================
--- /dev/null
+++ /src/ww10/gui/AverageProfitPanel.java Sun Nov 7 06:35:47 2010
@@ -0,0 +1,139 @@
+package ww10.gui;
+
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.awt.Font;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import javax.swing.BorderFactory;
+
+import org.jfree.chart.ChartFactory;
+import org.jfree.chart.ChartPanel;
+import org.jfree.chart.JFreeChart;
+import org.jfree.chart.axis.AxisLocation;
+import org.jfree.chart.plot.Marker;
+import org.jfree.chart.plot.PlotOrientation;
+import org.jfree.chart.plot.ValueMarker;
+import org.jfree.chart.plot.XYPlot;
+import org.jfree.chart.renderer.AbstractRenderer;
+import org.jfree.chart.renderer.xy.XYItemRenderer;
+import org.jfree.data.xy.XYSeries;
+import org.jfree.data.xy.XYSeriesCollection;
+import org.jfree.ui.Layer;
+import org.jfree.ui.RectangleAnchor;
+import org.jfree.ui.RectangleEdge;
+import org.jfree.ui.TextAnchor;
+
+public class AverageProfitPanel extends ChartPanel {
+
+ private static final long serialVersionUID = 263366236582410291L;
+
+ private final HashMap<String, XYSeries> playerToXYSeries;
+
+ private final XYPlot xyPlot;
+
+ public AverageProfitPanel(DataModel dataModel) {
+ super(null);
+
+ String[] playerNames = dataModel.getPlayerNames();
+
+ // create chart
+ playerToXYSeries = new HashMap<String, XYSeries>();
+ for (String playerName : playerNames) {
+ playerToXYSeries.put(playerName, new XYSeries(playerName));
+ //TODO setDescription
+ }
+
+ XYSeriesCollection xySeriesCollection = new XYSeriesCollection();
+ for (String playerName : playerNames) {
+ xySeriesCollection.addSeries(playerToXYSeries.get(playerName));
+ }
+
+ JFreeChart chart =
ChartFactory.createXYLineChart(null, "Games", "Average Profit",
xySeriesCollection, PlotOrientation.VERTICAL, true, false, false);
+ // chart.setBackgroundPaint(Color.WHITE);
+ xyPlot = chart.getXYPlot();
+ xyPlot.setBackgroundPaint(Color.WHITE);
+ XYItemRenderer xyir = xyPlot.getRenderer();//.get.setOutlineStroke()
+ try {
+ xyir.setBaseStroke(new BasicStroke(3));
+ // bug workaround
+ ((AbstractRenderer) xyir).setAutoPopulateSeriesStroke(false);
+
+ // xyir.setSeriesStroke(new BasicStroke(5));
+ // xyir.setSeriesStroke(0, ); //series line style
+ } catch (Exception e) {
+ System.err.println("Error setting style: " + e);
+ }
+ // xyPlot.setDomainGridlinesVisible(true);
+ xyPlot.setRangeGridlinesVisible(true);
+ // xyPlot.setDomainGridlinePaint(Color.black);
+ xyPlot.setRangeGridlinePaint(Color.GRAY);
+ xyPlot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
+
+ // // create some Pointers to the final bankrolls
+ // for (String playerName : playerNames) {
+ // double finalBankroll = playerToBankRoll.get(playerName);
+ // DecimalFormat moneyFormat = new DecimalFormat("0.00");
+ // String resultString = getChosenName(playerName) + ": € " +
moneyFormat.format(finalBankroll / (snapshotCurrentGamesPlayed)) + "/game)";
+ // final XYPointerAnnotation pointer = new
XYPointerAnnotation(resultString, Math.min(snapshotCurrentGamesPlayed,
numGames), finalBankroll,
+ // Math.PI * 5.9 / 6);
+ // pointer.setBaseRadius(130.0);
+ // pointer.setTipRadius(1.0);
+ // pointer.setLabelOffset(10.0);
+ // pointer.setOutlineVisible(true);
+ // pointer.setBackgroundPaint(Color.WHITE);
+ // chart.getXYPlot().addAnnotation(pointer);
+ //
+ // }
+
+ // after the first permutation the next permutations get
+ // merges with the existing data. We show a marker, what
+ // data is already merged
+ // final Marker permutationEnd = new
ValueMarker(snapshotCurrentGamesPlayed % numGames);
+ // permutationEnd.setLabel((currentSeatPermutation + 1) + "
permutation(s)");
+ // permutationEnd.setLabelAnchor(RectangleAnchor.TOP_LEFT);
+ // permutationEnd.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
+ // chart.getXYPlot().addDomainMarker(permutationEnd);
+ chart.getLegend().setPosition(RectangleEdge.RIGHT);
+
+ this.setFillZoomRectangle(true);
+ setBorder(BorderFactory.createLoweredBevelBorder());
+ this.setChart(chart);
+ }
+
+ public void addDataPoints(int game, Map<String, Double> avgProfits) {
+ for (Entry<String, Double> entry : avgProfits.entrySet()) {
+ playerToXYSeries.get(entry.getKey()).add(game, entry.getValue());
+ }
+ }
+
+ public void removeFirstDataPoints(int n) {
+ Collection<XYSeries> series = playerToXYSeries.values();
+ for (XYSeries s : series) {
+ s.delete(0, n - 1);
+ }
+ }
+
+ public void addMarker(int fCurrentGamesPlayed, String msg) {
+ final Marker submission = new ValueMarker(fCurrentGamesPlayed);
+ submission.setLabel(msg);
+ submission.setLabelFont(new Font("sansserif", Font.PLAIN, 20));
+ submission.setStroke(new BasicStroke(3));
+ submission.setLabelAnchor(RectangleAnchor.TOP_LEFT);
+ submission.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
+ xyPlot.addDomainMarker(submission);
+ }
+
+ public void removeFirstMarkers(int nbMarkers) {
+ if (nbMarkers > 0) {
+ Object[] markers = xyPlot.getDomainMarkers(Layer.FOREGROUND).toArray();
+ for (int i = 0; i < nbMarkers; i++) {
+ xyPlot.removeDomainMarker((Marker) markers[i]);
+ }
+ }
+ }
+
+}
=======================================
--- /dev/null
+++ /src/ww10/gui/DataModel.java Sun Nov 7 06:35:47 2010
@@ -0,0 +1,356 @@
+package ww10.gui;
+
+import game.stats.BankrollObserver;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+import javax.swing.SwingUtilities;
+
+import util.Utils;
+
+import com.biotools.meerkat.Action;
+import com.biotools.meerkat.Card;
+import com.biotools.meerkat.GameInfo;
+import com.biotools.meerkat.GameObserver;
+
+/**
+ * This BankrollObserver opens a window while the game is running, showing
the current
+ * progress. A bankroll-chart is updated every 10 seconds.<br>
+ * <br>
+ * The window closes itself on the end of the game.<br>
+ *
+ * Register this class on a GameRunner and call {@link #createGraph()} in
the end
+ * to open a window with the final result
+ */
+public class DataModel implements BankrollObserver, GameObserver {
+
+ private final SwingGUI gui = new SwingGUI(this);
+
+ private String[] playerNames;
+
+ private volatile int currentGamesPlayed;
+
+ private HashMap<String, String> chosenNames = new HashMap<String,
String>();
+
+ private final LinkedList<GameStats> bankrollWindow = new
LinkedList<GameStats>();
+ private final LinkedList<GameStats> plotTimes = new
LinkedList<GameStats>();
+ private final LinkedList<Long> markerTimes = new LinkedList<Long>();
+
+ private int nbGamesInTotalProfit = 0;
+
+ private final Map<String, Double> currentTotalProfit = new
HashMap<String, Double>();
+
+ private final long plotWindow = 60 * 1000;
+
+ private final long minBankrollWindow = plotWindow / 3;
+
+ private long lastSubmitTime = 0;
+
+ private final HashMap<String, int[]> currentActionFreqs = new
HashMap<String, int[]>();
+
+ private GameInfo gameInfo;
+
+ public synchronized String[] getPlayerNames() {
+ return playerNames;
+ }
+
+ public synchronized int getCurrentGamesPlayed() {
+ return currentGamesPlayed;
+ }
+
+ public synchronized String getChosenName(String fixedName) {
+ String chosenName = chosenNames.get(fixedName);
+ if (chosenName == null)
+ return fixedName;
+ else
+ return chosenName;
+ }
+
+ public synchronized String getLongChosenName(String fixedName) {
+ String chosenName = chosenNames.get(fixedName);
+ if (chosenName == null)
+ return fixedName;
+ else
+ return chosenName + " (" + fixedName + ")";
+ }
+
+ public synchronized void onSubmit(final String fixedName, final String
chosenName) {
+ //TODO update GUI
+ chosenNames.put(fixedName, chosenName);
+ lastSubmitTime = System.currentTimeMillis();
+ final int fCurrentGamesPlayed = currentGamesPlayed;
+ markerTimes.add(lastSubmitTime);
+ SwingUtilities.invokeLater(new Runnable() {
+ public void run() {
+ gui.averageProfitPanel.addMarker(fCurrentGamesPlayed, fixedName + "
submits " + chosenName);
+ }
+ });
+ }
+
+ @Override
+ public synchronized void gameStarted(int numSeatPermutations, int
numGames, Set<String> playerNames) {
+ this.playerNames = playerNames.toArray(new String[playerNames.size()]);
+ Arrays.sort(this.playerNames);
+
+ for (String player : playerNames) {
+ currentTotalProfit.put(player, 0.0);
+ currentActionFreqs.put(player, new int[5]);
+ }
+ SwingUtilities.invokeLater(new Runnable() {
+ public void run() {
+ gui.initialize();
+ }
+ });
+ }
+
+ @Override
+ public synchronized void updateBankroll(int seatpermutation, final
Map<String, Double> playerDelta) {
+ currentGamesPlayed++;
+
+ //update stats
+
+ currentGameStats.time = System.currentTimeMillis();
+ currentGameStats.game = currentGamesPlayed;
+ currentGameStats.bankrollDeltas = playerDelta;
+
+ addGameStats(currentGameStats);
+ bankrollWindow.add(currentGameStats);
+
+ if (currentGamesPlayed % 1 == 0) {
+ updatePlot();
+ }
+ }
+
+ private void updatePlot() {
+
+ //remove old stats
+
+ // update bankroll
+ removeFromWindow();
+
+ // update plot
+
+ // update data points
+ final int fNbRemoved = removeDatapoints();
+ final int fCurrentGamesPlayed = currentGamesPlayed;
+ final ConcurrentHashMap<String, Double> fCurrentAvgProfit =
getAvgProfit();
+
+ //update status
+ int currentGamesPlayed = getCurrentGamesPlayed();
+ double gamesPerSecond = getGamesPerSecond();
+ int window = getCurrentBankrollGameWindow();
+ final String status = "Completed: " + currentGamesPlayed + " games, "
+ "Speed: " + Utils.roundToCents(gamesPerSecond) + " games/s, " + "Window: "
+ + window + " games";
+
+ //update markers
+ final int fNbRemovedMarkers = removeMarkers();
+
+ //update action frequencies
+ final ConcurrentHashMap<String, int[]> fActionFreqs = new
ConcurrentHashMap<String, int[]>();
+ for (Entry<String, int[]> entry : currentActionFreqs.entrySet()) {
+ fActionFreqs.put(entry.getKey(), entry.getValue().clone());
+ }
+
+ SwingUtilities.invokeLater(new Runnable() {
+ public void run() {
+ gui.averageProfitPanel.removeFirstDataPoints(fNbRemoved);
+ gui.averageProfitPanel.addDataPoints(fCurrentGamesPlayed,
fCurrentAvgProfit);
+ gui.changeStatus(status);
+ gui.averageProfitPanel.removeFirstMarkers(fNbRemovedMarkers);
+ gui.actionPanel.updateActionFrequencies(fActionFreqs);
+ }
+ });
+ plotTimes.add(currentGameStats);
+ }
+
+ private int removeFromWindow() {
+ Iterator<GameStats> iter = bankrollWindow.iterator();
+ boolean done = false;
+ int nbRemoved = 0;
+ long currentTime = System.currentTimeMillis();
+ while (!done && iter.hasNext()) {
+ GameStats first = iter.next();
+ if (first.time < Math.min(lastSubmitTime, currentTime -
minBankrollWindow)) {
+ nbRemoved++;
+ undoGameStats(first);
+ iter.remove();
+ } else {
+ done = true;
+ }
+ }
+ return nbRemoved;
+ }
+
+ private int removeDatapoints() {
+ Iterator<GameStats> iter = plotTimes.iterator();
+ boolean done = false;
+ int nbRemoved = 0;
+ long currentTime = System.currentTimeMillis();
+ while (!done && iter.hasNext()) {
+ GameStats first = iter.next();
+ if (first.time < currentTime - plotWindow) {
+ nbRemoved++;
+ iter.remove();
+ } else {
+ done = true;
+ }
+ }
+ return nbRemoved;
+ }
+
+ private int removeMarkers() {
+ Iterator<Long> iter = markerTimes.iterator();
+ boolean done = false;
+ int nbRemoved = 0;
+ long currentTime = System.currentTimeMillis();
+ while (!done && iter.hasNext()) {
+ long first = iter.next();
+ if (first < currentTime - plotWindow) {
+ nbRemoved++;
+ iter.remove();
+ } else {
+ done = true;
+ }
+ }
+ return nbRemoved;
+ }
+
+ private ConcurrentHashMap<String, Double> getAvgProfit() {
+ ConcurrentHashMap<String, Double> avgProfit = new
ConcurrentHashMap<String, Double>();
+ for (String player : playerNames) {
+ double currentProfit = currentTotalProfit.get(player);
+ avgProfit.put(player, currentProfit / nbGamesInTotalProfit);
+ }
+ return avgProfit;
+ }
+
+ private void addGameStats(final GameStats stats) {
+ nbGamesInTotalProfit++;
+ for (String player : playerNames) {
+ //profit
+ double currentProfit = currentTotalProfit.get(player);
+ currentTotalProfit.put(player, currentProfit +
stats.bankrollDeltas.get(player));
+ //actions
+ int[] prevFreq = currentActionFreqs.get(player);
+ int[] statFreq = stats.actionFreqs.get(player);
+ for (int i = 0; i < statFreq.length; i++) {
+ prevFreq[i] += statFreq[i];
+ }
+ }
+ }
+
+ private void undoGameStats(final GameStats stats) {
+ nbGamesInTotalProfit--;
+ for (String player : playerNames) {
+ //profit
+ double currentProfit = currentTotalProfit.get(player);
+ currentTotalProfit.put(player, currentProfit -
stats.bankrollDeltas.get(player));
+ //actions
+ int[] prevFreq = currentActionFreqs.get(player);
+ int[] statFreq = stats.actionFreqs.get(player);
+ for (int i = 0; i < statFreq.length; i++) {
+ prevFreq[i] -= statFreq[i];
+ }
+ }
+ }
+
+ public synchronized float getGamesPerSecond() {
+ int nbGames = getCurrentBankrollGameWindow();
+ long time = getCurrentBankrollTimeWindow();
+ return (float) (nbGames / (time / 1000.0));
+ }
+
+ public synchronized int getCurrentBankrollGameWindow() {
+ return bankrollWindow.getLast().game - bankrollWindow.getFirst().game;
+ }
+
+ public synchronized long getCurrentBankrollTimeWindow() {
+ return bankrollWindow.getLast().time - bankrollWindow.getFirst().time;
+ }
+
+ private GameStats currentGameStats;
+
+ @Override
+ public void actionEvent(int pos, Action act) {
+ String player = gameInfo.getPlayerName(pos);
+ int[] freq = currentGameStats.actionFreqs.get(player);
+ switch (act.getType()) {
+ case Action.SMALL_BLIND:
+ break;
+ case Action.BIG_BLIND:
+ break;
+ case Action.CALL:
+ freq[3]++;
+ break;
+ case Action.RAISE:
+ freq[4]++;
+ break;
+ case Action.BET:
+ freq[1]++;
+ break;
+ case Action.CHECK:
+ freq[0]++;
+ break;
+ case Action.FOLD:
+ freq[2]++;
+ break;
+ case Action.MUCK:
+ break;
+ }
+
+ }
+
+ @Override
+ public void dealHoleCardsEvent() {
+ }
+
+ @Override
+ public void gameOverEvent() {
+ }
+
+ @Override
+ public void gameStartEvent(GameInfo gameInfo) {
+ this.gameInfo = gameInfo;
+ currentGameStats = new GameStats();
+ for (String player : playerNames) {
+ currentGameStats.actionFreqs.put(player, new int[5]);
+ }
+ }
+
+ @Override
+ public void gameStateChanged() {
+ }
+
+ @Override
+ public void showdownEvent(int arg0, Card arg1, Card arg2) {
+ }
+
+ @Override
+ public void stageEvent(int arg0) {
+ }
+
+ @Override
+ public void winEvent(int arg0, double arg1, String arg2) {
+ }
+}
+
+final class GameStats {
+
+ long time;
+ int game;
+ Map<String, Double> bankrollDeltas;
+
+ final Map<String, int[]> actionFreqs = new HashMap<String, int[]>();
+
+ public GameStats() {
+
+ }
+
+}
=======================================
--- /dev/null
+++ /src/ww10/gui/SwingGUI.java Sun Nov 7 06:35:47 2010
@@ -0,0 +1,124 @@
+package ww10.gui;
+
+import java.awt.GraphicsDevice;
+import java.awt.GraphicsEnvironment;
+
+import javax.swing.JFrame;
+import javax.swing.JProgressBar;
+import javax.swing.JSplitPane;
+import javax.swing.JTabbedPane;
+import javax.swing.UIManager;
+import javax.swing.UnsupportedLookAndFeelException;
+
+final class SwingGUI {
+
+ static {
+ try {
+ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
+ } catch (ClassNotFoundException e) {
+ e.printStackTrace();
+ } catch (InstantiationException e) {
+ e.printStackTrace();
+ } catch (IllegalAccessException e) {
+ e.printStackTrace();
+ } catch (UnsupportedLookAndFeelException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private final DataModel dataModel;
+
+ public SwingGUI(DataModel dataModel) {
+ this.dataModel = dataModel;
+ // created by non-swing thread, so do nothing.
+ }
+
+ void initialize() {
+
+ statusbar = new javax.swing.JProgressBar();
+ actionPanel = new ActionPanel(dataModel);
+ averageProfitPanel = new AverageProfitPanel(dataModel);
+
+ // set up frame
+ frame = new JFrame("Wetenschapsweek");
+ JSplitPane splitPane = new javax.swing.JSplitPane();
+
+ JTabbedPane tabs = new javax.swing.JTabbedPane();
+
+
frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
+
+ splitPane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
+
+ splitPane.setBottomComponent(tabs);
+ splitPane.setLeftComponent(statusbar);
+
+ frame.getContentPane().add(splitPane);
+
+ // this.progressFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
+ // Toolkit tk = Toolkit.getDefaultToolkit();
+ // int xSize = ((int) tk.getScreenSize().getWidth());
+ // int ySize = ((int) tk.getScreenSize().getHeight());
+ // this.progressFrame.setSize(xSize, ySize);
+ // this.progressFrame.setSize(1200, 800);
+ this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+ statusbar.setStringPainted(true);
+ //setting this causes gnome bars to be on top
+ // this.progressFrame.setResizable(false);
+ this.frame.setLocation(0, 0);
+ // Toolkit tk = Toolkit.getDefaultToolkit();
+ // int xSize = ((int) tk.getScreenSize().getWidth());
+ // int ySize = ((int) tk.getScreenSize().getHeight());
+ // this.progressFrame.setSize(xSize, ySize);
+ if (!this.frame.isDisplayable()) {
+ // Can only do this when the frame is not visible
+ this.frame.setUndecorated(true);
+ }
+ GraphicsDevice gd =
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
+ if (gd.isFullScreenSupported()) {
+ gd.setFullScreenWindow(this.frame);
+ } else {
+ // Can't run fullscreen, need to bodge around it (setSize to screen
size, etc)
+ }
+ // this.frame.addKeyListener(new KeyListener() {
+ //
+ // public void keyPressed(KeyEvent e) {
+ // }
+ //
+ // public void keyReleased(KeyEvent e) {
+ // }
+ //
+ // public void keyTyped(KeyEvent e) {
+ // if (e.getKeyChar() == 'f') {
+ // // progressFrame.setResizable(false);
+ // // // progressFrame.setUndecorated(true);
+ // // GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
+ // // GraphicsDevice graphicsDevice =
ge.getDefaultScreenDevice();
+ // // graphicsDevice.setFullScreenWindow(progressFrame);
+ // // //myDevice.setFullScreenWindow(null);
+ // } else if (e.getKeyChar() == 'x') {
+ // System.exit(0);
+ // }
+ // }
+ //
+ // });
+ tabs.addTab("Average Profit", averageProfitPanel);
+ tabs.addTab("Actions", actionPanel);
+
+ this.frame.pack(); // not needed?
+ this.frame.setVisible(true);
+ }
+
+ public void redraw() {
+
+ }
+
+ public void changeStatus(String status) {
+ statusbar.setString(status);
+ }
+
+ JFrame frame;
+ JProgressBar statusbar;
+ ActionPanel actionPanel;
+ AverageProfitPanel averageProfitPanel;
+
+}
=======================================
--- /.classpath Mon May 17 11:50:17 2010
+++ /.classpath Sun Nov 7 06:35:47 2010
@@ -3,10 +3,12 @@
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" output="junitclasses" path="junit"/>
<classpathentry kind="con"
path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry exported="true" kind="lib" path="lib/meerkat-api.jar"/>
+ <classpathentry exported="true" kind="lib" path="lib/meerkat-api.jar"
sourcepath="/home/guy/Werk/cspoker/Meerkat-API/docs"/>
+ <classpathentry kind="lib" path="lib/commons-io-1.4-sources.jar"/>
+ <classpathentry kind="lib" path="lib/protobuf-java-2.3.0.jar"/>
<classpathentry kind="con"
path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
<classpathentry exported="true" kind="lib" path="lib/commons-io-1.4.jar"/>
- <classpathentry kind="lib" path="lib/jfreechart-1.0.13.jar"/>
+ <classpathentry kind="lib" path="lib/jfreechart-1.0.13.jar"
sourcepath="/home/guy/Werk/cspoker/jfreechart-1.0.13/source"/>
<classpathentry kind="lib" path="lib/jcommon-1.0.16.jar"/>
<classpathentry kind="lib" path="lib/google-collections-0.9.jar"/>
<classpathentry exported="true" kind="lib" path="lib/log4j-1.2.14.jar"/>
=======================================
--- /junit/bots/BotRepositoryTest.java Wed Mar 17 11:20:21 2010
+++ /junit/bots/BotRepositoryTest.java Sun Nov 7 06:35:47 2010
@@ -1,6 +1,5 @@
package bots;
-
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@@ -19,7 +18,7 @@
BotRepository botRepository = new BotRepository();
Set<String> botNames = botRepository.getBotNames();
assertTrue(botNames.contains("SimpleBot/SimpleBot"));
-
+
BotMetaData botMetaData =
botRepository.getBotMetaData("SimpleBot/SimpleBot");
assertEquals("SimpleBot/SimpleBot", botMetaData.getBotName());
assertEquals("bots.demobots.SimpleBot", botMetaData.getBotClassName());
=======================================
--- /junit/game/DealerTest.java Thu Jun 24 00:38:31 2010
+++ /junit/game/DealerTest.java Sun Nov 7 06:35:47 2010
@@ -97,16 +97,16 @@
gameInfo.setBlinds(0.05, 0.10);
// we use one player at all seats
- Player mockPlayer=new PrerecordedPlayerMock( //
+ Player mockPlayer = new PrerecordedPlayerMock( //
Action.callAction(0.10), // player2: call BB
Action.callAction(0.05), // player0 (SB): call BB
- Action.checkAction(), // player1 (BB): check
- // -- flop --
- Action.betAction(0.10), // player0: bet
- Action.foldAction(0.10), // player1: fold
- Action.foldAction(0.10) // player2: fold
- );
-
+ Action.checkAction(), // player1 (BB): check
+ // -- flop --
+ Action.betAction(0.10), // player0: bet
+ Action.foldAction(0.10), // player1: fold
+ Action.foldAction(0.10) // player2: fold
+ );
+
gameInfo.setPlayer(0, PublicPlayerInfo.create("player0", 200,
mockPlayer));
gameInfo.setPlayer(1, PublicPlayerInfo.create("player1", 200,
mockPlayer));
BotLoggingDecorator botLog = new BotLoggingDecorator(mockPlayer, false);
=======================================
--- /junit/game/HandHistoryWriterTest.java Fri Apr 2 12:06:23 2010
+++ /junit/game/HandHistoryWriterTest.java Sun Nov 7 06:35:47 2010
@@ -32,7 +32,7 @@
gameInfo.setPlayer(7, PublicPlayerInfo.create("player8", 0.40, null));
gameInfo.setPlayer(8, PublicPlayerInfo.create("player9", 1.57, null));
gameInfo.newHand(0, 2, 4);
-
+
StringWriter handHistory = new StringWriter();
HandHistoryWriter handHistoryWriter = new MockHandHistoryWriter();
handHistoryWriter.setWriter(handHistory);
@@ -186,7 +186,7 @@
handHistoryWriter.actionEvent(0, Action.betAction(0.61));
handHistoryWriter.actionEvent(3, Action.callAction(0.61));
-
+
gameInfo.getPotManager().setPot(0, 0.38, new int[] { 4, 5, 0, 1, 3 });
// reduced by rake
gameInfo.getPotManager().setPot(0, 1.34, new int[] { 0, 3 });
@@ -212,7 +212,6 @@
gameInfo.setNumSeats(9);
return gameInfo;
}
-
/**
* overrides 'getGameTime()', otherwise the generated histories always
have different times
=======================================
--- /junit/game/TableSeaterTest.java Mon Mar 29 17:10:47 2010
+++ /junit/game/TableSeaterTest.java Sun Nov 7 06:35:47 2010
@@ -6,7 +6,6 @@
import bots.BotRepository;
-
public class TableSeaterTest {
@Test
public void testSeatPermutations() {
=======================================
--- /src/bots/BotMetaData.java Wed Mar 17 10:12:57 2010
+++ /src/bots/BotMetaData.java Sun Nov 7 06:35:47 2010
@@ -17,7 +17,7 @@
this.botName = botName;
this.botClassName = botClassName;
this.botPreferences = botPreferences;
- this.noLimit=noLimit;
+ this.noLimit = noLimit;
}
public String getBotName() {
=======================================
--- /src/bots/demobots/SimpleBot.java Mon Jun 7 13:32:52 2010
+++ /src/bots/demobots/SimpleBot.java Sun Nov 7 06:35:47 2010
@@ -307,6 +307,7 @@
}
} else {
double betAmount = Utils.roundToCents(gi.getMainPotSize() / 3 * 2);
+ //TODO check: is this even correct?
if (gi.getBankRoll(ourSeat) - betAmount < betAmount) {
betAmount = gi.getBankRoll(ourSeat);
}
=======================================
--- /src/bots/mctsbot/ai/bots/bot/AbstractBot.java Sat Apr 24 00:33:47 2010
+++ /src/bots/mctsbot/ai/bots/bot/AbstractBot.java Sun Nov 7 06:35:47 2010
@@ -32,11 +32,10 @@
this.playerContext = playerContext;
}
-
public abstract void doNextAction();
@Override
public String toString() {
- return "Abstract bot "+botId;
+ return "Abstract bot " + botId;
}
}
=======================================
--- /src/bots/mctsbot/ai/bots/bot/Bot.java Sat Apr 24 00:33:47 2010
+++ /src/bots/mctsbot/ai/bots/bot/Bot.java Sun Nov 7 06:35:47 2010
@@ -15,7 +15,6 @@
*/
package bots.mctsbot.ai.bots.bot;
-
public interface Bot {
void doNextAction();
=======================================
--- /src/bots/mctsbot/ai/bots/bot/gametree/action/BetAction.java Sat Apr 24
00:33:47 2010
+++ /src/bots/mctsbot/ai/bots/bot/gametree/action/BetAction.java Sun Nov 7
06:35:47 2010
@@ -37,8 +37,7 @@
}
@Override
- public void perform(RemoteHoldemPlayerContext context)
- {
+ public void perform(RemoteHoldemPlayerContext context) {
context.betOrRaise(amount);
}
@@ -50,20 +49,20 @@
betState = new AllInState(gameState, new AllInEvent(actor, amount));
} else if (stack > amount) {
betState = new BetState(gameState, new BetEvent(actor, amount));
- } else throw new IllegalStateException("Can't bet amount: "+amount+",
with stack: " + stack);
+ } else
+ throw new IllegalStateException("Can't bet amount: " + amount + ", with
stack: " + stack);
PlayerState nextToAct = betState.getNextActivePlayerAfter(actor);
if (nextToAct != null) {
- return new NextPlayerState(betState, new NextPlayerEvent(nextToAct
- .getPlayerId()));
+ return new NextPlayerState(betState, new
NextPlayerEvent(nextToAct.getPlayerId()));
}
throw new IllegalStateException("Round can't be over after a bet.");
}
@Override
public String toString() {
- if(gameState.getPlayer(actor).getStack() == amount){
- return "Bet " + Util.parseDollars(amount)+ " (all-in)";
- }else{
+ if (gameState.getPlayer(actor).getStack() == amount) {
+ return "Bet " + Util.parseDollars(amount) + " (all-in)";
+ } else {
return "Bet " + Util.parseDollars(amount);
}
}
=======================================
--- /src/bots/mctsbot/ai/bots/bot/gametree/action/CallAction.java Sat Apr
24 00:33:47 2010
+++ /src/bots/mctsbot/ai/bots/bot/gametree/action/CallAction.java Sun Nov
7 06:35:47 2010
@@ -36,8 +36,7 @@
}
@Override
- public void perform(RemoteHoldemPlayerContext context)
- {
+ public void perform(RemoteHoldemPlayerContext context) {
context.checkOrCall();
}
@@ -46,9 +45,7 @@
boolean roundEnds = true;
Set<PlayerState> players = gameState.getAllSeatedPlayers();
forloop: for (PlayerState player : players) {
- if (player.isActivelyPlaying()
- && !player.getPlayerId().equals(actor)
- && gameState.getDeficit(player.getPlayerId()) > 0) {
+ if (player.isActivelyPlaying() && !player.getPlayerId().equals(actor)
&& gameState.getDeficit(player.getPlayerId()) > 0) {
roundEnds = false;
break forloop;
}
@@ -60,11 +57,8 @@
int bet = actorState.getBet();
// what if small or big blind all-in?
- if (roundEnds
- && gameState.getRound().equals(Round.PREFLOP)
- && actor.equals(gameState.getSmallBlind())
- && largestBet <= gameState.getTableConfiguration()
- .getBigBlind()) {
+ if (roundEnds && gameState.getRound().equals(Round.PREFLOP) &&
actor.equals(gameState.getSmallBlind())
+ && largestBet <= gameState.getTableConfiguration().getBigBlind()) {
roundEnds = false;
}
@@ -77,14 +71,12 @@
if (roundEnds) {
return getNewRoundState(state);
} else {
- PlayerState nextActivePlayerAfter = state
- .getNextActivePlayerAfter(actor);
+ PlayerState nextActivePlayerAfter =
state.getNextActivePlayerAfter(actor);
if (nextActivePlayerAfter == null) {
// BigBlind is all-in
return getNewRoundState(state);
}
- return new NextPlayerState(state, new NextPlayerEvent(
- nextActivePlayerAfter.getPlayerId()));
+ return new NextPlayerState(state, new
NextPlayerEvent(nextActivePlayerAfter.getPlayerId()));
}
}
=======================================
--- /src/bots/mctsbot/ai/bots/bot/gametree/action/CheckAction.java Sat Apr
24 00:33:47 2010
+++ /src/bots/mctsbot/ai/bots/bot/gametree/action/CheckAction.java Sun Nov
7 06:35:47 2010
@@ -32,8 +32,7 @@
}
@Override
- public void perform(RemoteHoldemPlayerContext context)
- {
+ public void perform(RemoteHoldemPlayerContext context) {
context.checkOrCall();
}
@@ -41,16 +40,12 @@
public GameState getStateAfterAction() throws GameEndedException {
PlayerState nextToAct = gameState.getNextActivePlayerAfter(actor);
// if bigblind is all-in, he shouldn't check again, so we're safe
- boolean newRound = nextToAct.hasChecked()
- || gameState.getRound().equals(Round.PREFLOP)
- && actor.equals(gameState.getBigBlind())
- && gameState.getLargestBet() <= gameState
- .getTableConfiguration().getBigBlind();
+ boolean newRound = nextToAct.hasChecked() ||
gameState.getRound().equals(Round.PREFLOP) &&
actor.equals(gameState.getBigBlind())
+ && gameState.getLargestBet() <=
gameState.getTableConfiguration().getBigBlind();
CheckState checkState = new CheckState(gameState, new CheckEvent(actor));
if (!newRound) {
- return new NextPlayerState(checkState, new NextPlayerEvent(
- nextToAct.getPlayerId()));
+ return new NextPlayerState(checkState, new
NextPlayerEvent(nextToAct.getPlayerId()));
}
return getNewRoundState(checkState);
}
=======================================
--- /src/bots/mctsbot/ai/bots/bot/gametree/action/FoldAction.java Sat Apr
24 00:33:47 2010
+++ /src/bots/mctsbot/ai/bots/bot/gametree/action/FoldAction.java Sun Nov
7 06:35:47 2010
@@ -34,27 +34,22 @@
}
@Override
- public void perform(RemoteHoldemPlayerContext context)
- {
+ public void perform(RemoteHoldemPlayerContext context) {
context.fold();
}
@Override
- public GameState getStateAfterAction() throws GameEndedException,
- DefaultWinnerException {
+ public GameState getStateAfterAction() throws GameEndedException,
DefaultWinnerException {
boolean roundEnds = true;
Set<PlayerState> players = gameState.getAllSeatedPlayers();
PlayerState first = null;
boolean noDefaultWinner = false;
// TODO use getNbPlayers()
forloop: for (PlayerState player : players) {
- if (roundEnds && player.isActivelyPlaying()
- && !player.getPlayerId().equals(actor)
- && gameState.getDeficit(player.getPlayerId()) > 0) {
+ if (roundEnds && player.isActivelyPlaying()
&& !player.getPlayerId().equals(actor) &&
gameState.getDeficit(player.getPlayerId()) > 0) {
roundEnds = false;
}
- if (!noDefaultWinner && !player.getPlayerId().equals(actor)
- && !player.hasFolded()) {
+ if (!noDefaultWinner && !player.getPlayerId().equals(actor)
&& !player.hasFolded()) {
if (first != null) {
noDefaultWinner = true;
} else {
@@ -66,22 +61,17 @@
}
}
if (!noDefaultWinner) {
- throw new DefaultWinnerException(first, new FoldState(gameState,
- new FoldEvent(actor)));
- }
- if (roundEnds
- && gameState.getRound().equals(Round.PREFLOP)
- && actor.equals(gameState.getSmallBlind())
- && gameState.getLargestBet() <= gameState
- .getTableConfiguration().getBigBlind()) {
+ throw new DefaultWinnerException(first, new FoldState(gameState, new
FoldEvent(actor)));
+ }
+ if (roundEnds && gameState.getRound().equals(Round.PREFLOP) &&
actor.equals(gameState.getSmallBlind())
+ && gameState.getLargestBet() <=
gameState.getTableConfiguration().getBigBlind()) {
roundEnds = false;
}
FoldState foldState = new FoldState(gameState, new FoldEvent(actor));
if (!roundEnds) {
- return new NextPlayerState(foldState, new NextPlayerEvent(foldState
- .getNextActivePlayerAfter(actor).getPlayerId()));
+ return new NextPlayerState(foldState, new
NextPlayerEvent(foldState.getNextActivePlayerAfter(actor).getPlayerId()));
}
return getNewRoundState(foldState);
}
=======================================
--- /src/bots/mctsbot/ai/bots/bot/gametree/action/ProbabilityAction.java
Sat Apr 24 00:33:47 2010
+++ /src/bots/mctsbot/ai/bots/bot/gametree/action/ProbabilityAction.java
Sun Nov 7 06:35:47 2010
@@ -39,8 +39,7 @@
@Override
public String toString() {
- return actionWrapper.toString() + " (" + Math.round(probability * 100)
- + "% chance)";
+ return actionWrapper.toString() + " (" + Math.round(probability * 100)
+ "% chance)";
}
}
=======================================
--- /src/bots/mctsbot/ai/bots/bot/gametree/action/RaiseAction.java Sat Apr
24 00:33:47 2010
+++ /src/bots/mctsbot/ai/bots/bot/gametree/action/RaiseAction.java Sun Nov
7 06:35:47 2010
@@ -37,8 +37,7 @@
}
@Override
- public void perform(RemoteHoldemPlayerContext context)
- {
+ public void perform(RemoteHoldemPlayerContext context) {
context.betOrRaise(amount);
}
@@ -57,8 +56,7 @@
} else {
raiseState = new RaiseState(gameState, new RaiseEvent(actor, amount,
movedAmount));
}
- return new NextPlayerState(raiseState, new NextPlayerEvent(raiseState
- .getNextActivePlayerAfter(actor).getPlayerId()));
+ return new NextPlayerState(raiseState, new
NextPlayerEvent(raiseState.getNextActivePlayerAfter(actor).getPlayerId()));
}
@Override
@@ -71,8 +69,8 @@
int movedAmount = deficit + amount;
if (movedAmount >= stack) {
- return "Raise " + Util.parseDollars(amount)+ " (all-in)";
- }else{
+ return "Raise " + Util.parseDollars(amount) + " (all-in)";
+ } else {
return "Raise " + Util.parseDollars(amount);
}
}
=======================================
--- /src/bots/mctsbot/ai/bots/bot/gametree/action/SearchBotAction.java Sat
Apr 24 00:33:47 2010
+++ /src/bots/mctsbot/ai/bots/bot/gametree/action/SearchBotAction.java Sun
Nov 7 06:35:47 2010
@@ -43,29 +43,21 @@
public abstract void perform(RemoteHoldemPlayerContext context);
- public abstract GameState getStateAfterAction() throws GameEndedException,
- DefaultWinnerException;
-
- protected GameState getNewRoundState(GameState lastState)
- throws GameEndedException {
+ public abstract GameState getStateAfterAction() throws
GameEndedException, DefaultWinnerException;
+
+ protected GameState getNewRoundState(GameState lastState) throws
GameEndedException {
Round nextRound = lastState.getRound().getNextRound();
if (nextRound == null) {
throw new GameEndedException(lastState);
}
-// List<Pot> pots = Collections.emptyList();
- NewRoundState newRoundState = new NewRoundState(lastState,
- new NewRoundEvent(nextRound, new Pots(lastState
- .getGamePotSize())));
- PlayerState firstToAct = newRoundState
- .getNextActivePlayerAfter(newRoundState.getDealer());
- if (firstToAct == null
- || newRoundState.getNextActivePlayerAfter(firstToAct
- .getPlayerId()) == null) {
+ // List<Pot> pots = Collections.emptyList();
+ NewRoundState newRoundState = new NewRoundState(lastState, new
NewRoundEvent(nextRound, new Pots(lastState.getGamePotSize())));
+ PlayerState firstToAct =
newRoundState.getNextActivePlayerAfter(newRoundState.getDealer());
+ if (firstToAct == null ||
newRoundState.getNextActivePlayerAfter(firstToAct.getPlayerId()) == null) {
// no one/only one left
return getNewRoundState(newRoundState);
}
- return new NextPlayerState(newRoundState, new NextPlayerEvent(
- firstToAct.getPlayerId()));
+ return new NextPlayerState(newRoundState, new
NextPlayerEvent(firstToAct.getPlayerId()));
}
public boolean endsInvolvementOf(PlayerId botId) {
=======================================
--- /src/bots/mctsbot/ai/bots/bot/gametree/mcts/FixedSampleMCTSBot.java Sat
Apr 24 00:33:47 2010
+++ /src/bots/mctsbot/ai/bots/bot/gametree/mcts/FixedSampleMCTSBot.java Sun
Nov 7 06:35:47 2010
@@ -38,13 +38,8 @@
private final int samplesTurn;
private final int samplesRiver;
- public FixedSampleMCTSBot(PlayerId botId, GameStateContainer gameState,
RemoteHoldemPlayerContext playerContext,
- Config config,
- int samplesPreFlop,
- int samplesFlop,
- int samplesTurn,
- int samplesRiver,
- MCTSListener.Factory[] MCTSlisteners) {
+ public FixedSampleMCTSBot(PlayerId botId, GameStateContainer gameState,
RemoteHoldemPlayerContext playerContext, Config config, int samplesPreFlop,
+ int samplesFlop, int samplesTurn, int samplesRiver,
MCTSListener.Factory[] MCTSlisteners) {
super(botId, gameState, playerContext);
this.config = config;
this.MCTSlistenerFactories = MCTSlisteners;
@@ -57,15 +52,24 @@
@Override
public void doNextAction() {
GameState gameState = gameStateContainer.getGameState();
- RootNode root = new RootNode(gameState,botId,config);
+ RootNode root = new RootNode(gameState, botId, config);
switch (gameState.getRound()) {
- case PREFLOP: nbSamples = samplesPreFlop; break;
- case FLOP: nbSamples = samplesFlop; break;
- case TURN: nbSamples = samplesTurn; break;
- case FINAL: nbSamples = samplesRiver; break;
- default: throw new
IllegalStateException(gameState.getRound().toString());
- }
- do{
+ case PREFLOP:
+ nbSamples = samplesPreFlop;
+ break;
+ case FLOP:
+ nbSamples = samplesFlop;
+ break;
+ case TURN:
+ nbSamples = samplesTurn;
+ break;
+ case FINAL:
+ nbSamples = samplesRiver;
+ break;
+ default:
+ throw new IllegalStateException(gameState.getRound().toString());
+ }
+ do {
iterate(root);
iterate(root);
iterate(root);
@@ -101,14 +105,14 @@
iterate(root);
iterate(root);
iterate(root);
- }while(root.getNbSamples()<nbSamples);
+ } while (root.getNbSamples() < nbSamples);
if (printed && gameState.getRound() == r)
printed = false;
- if(logger.isDebugEnabled()){
+ if (logger.isDebugEnabled()) {
logger.debug("Stopped MCTS.");
}
root.selectChild(config.getMoveSelectionStrategy()).getLastAction().getAction().perform(playerContext);
-
+
MCTSListener[] listeners = createListeners(gameState, botId);
for (MCTSListener listener : listeners) {
listener.onMCTS(root);
@@ -123,10 +127,10 @@
private void iterate(RootNode root) {
Round round = gameStateContainer.getGameState().getRound();
- if (printed && round == r){
+ if (printed && round == r) {
currentCount = root.getNbSamples();
- if (currentCount-lastCount!=1) {
- for (long i = lastCount+1; i <= currentCount; i++)
+ if (currentCount - lastCount != 1) {
+ for (long i = lastCount + 1; i <= currentCount; i++)
System.out.println(i + " - " + root.getEV() + " - " +
root.getEVStdDev());
} else {
System.out.println(currentCount + " - " + root.getEV() + " - " +
root.getEVStdDev());
@@ -141,7 +145,7 @@
private MCTSListener[] createListeners(GameState gameState, PlayerId
actor) {
MCTSListener[] listeners = new
MCTSListener[MCTSlistenerFactories.length];
- for (int i=0;i<MCTSlistenerFactories.length;i++) {
+ for (int i = 0; i < MCTSlistenerFactories.length; i++) {
listeners[i] = MCTSlistenerFactories[i].create(gameState, actor);
}
return listeners;
=======================================
---
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/FixedSampleMCTSBotFactory.java
Sun May 23 13:04:51 2010
+++
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/FixedSampleMCTSBotFactory.java
Sun Nov 7 06:35:47 2010
@@ -48,25 +48,15 @@
private final int samplesTurn;
private final int samplesRiver;
- public FixedSampleMCTSBotFactory(
- String name,
- OpponentModel.Factory opponentModelFactory,
- SelectionStrategy decisionNodeSelectionStrategy,
- SelectionStrategy opponentNodeSelectionStrategy,
- SelectionStrategy moveSelectionStrategy,
- ShowdownNode.Factory showdownNodeFactory,
- BackPropagationStrategy.Factory backPropStratFactory,
- Sampler sampler,
- int samplesPreFlop,
- int samplesFlop,
- int samplesTurn,
- int samplesRiver,
+ public FixedSampleMCTSBotFactory(String name, OpponentModel.Factory
opponentModelFactory, SelectionStrategy decisionNodeSelectionStrategy,
+ SelectionStrategy opponentNodeSelectionStrategy, SelectionStrategy
moveSelectionStrategy, ShowdownNode.Factory showdownNodeFactory,
+ BackPropagationStrategy.Factory backPropStratFactory, Sampler sampler,
int samplesPreFlop, int samplesFlop, int samplesTurn, int samplesRiver,
MCTSListener.Factory... listeners) {
this.name = name;
this.listeners = listeners;
this.opponentModelFactory = opponentModelFactory;
- this.decisionNodeSelectionStrategy=decisionNodeSelectionStrategy;
- this.opponentNodeSelectionStrategy=opponentNodeSelectionStrategy;
+ this.decisionNodeSelectionStrategy = decisionNodeSelectionStrategy;
+ this.opponentNodeSelectionStrategy = opponentNodeSelectionStrategy;
this.moveSelectionStrategy = moveSelectionStrategy;
this.showdownNodeFactory = showdownNodeFactory;
this.backPropStratFactory = backPropStratFactory;
@@ -82,16 +72,9 @@
copies++;
OpponentModel opponentModel = opponentModelFactory.create();
- Config config = new Config(opponentModel, showdownNodeFactory,
- decisionNodeSelectionStrategy, opponentNodeSelectionStrategy,
- moveSelectionStrategy, backPropStratFactory, sampler);
- return new FixedSampleMCTSBot(botId, gameStateContainer, playerContext,
- config,
- samplesPreFlop,
- samplesFlop,
- samplesTurn,
- samplesRiver,
- listeners);
+ Config config = new Config(opponentModel, showdownNodeFactory,
decisionNodeSelectionStrategy, opponentNodeSelectionStrategy,
moveSelectionStrategy,
+ backPropStratFactory, sampler);
+ return new FixedSampleMCTSBot(botId, gameStateContainer, playerContext,
config, samplesPreFlop, samplesFlop, samplesTurn, samplesRiver, listeners);
}
@Override
=======================================
--- /src/bots/mctsbot/ai/bots/bot/gametree/mcts/MCTSBotFactory.java Sun May
23 13:04:51 2010
+++ /src/bots/mctsbot/ai/bots/bot/gametree/mcts/MCTSBotFactory.java Sun
Nov 7 06:35:47 2010
@@ -43,22 +43,14 @@
private final String name;
private final BackPropagationStrategy.Factory backPropStratFactory;
- public MCTSBotFactory(
- String name,
- OpponentModel.Factory opponentModelFactory,
- SelectionStrategy decisionNodeSelectionStrategy,
- SelectionStrategy opponentNodeSelectionStrategy,
- SelectionStrategy moveSelectionStrategy,
- ShowdownNode.Factory showdownNodeFactory,
- BackPropagationStrategy.Factory backPropStratFactory,
- Sampler sampler,
- int decisionTime,
- MCTSListener.Factory... listeners) {
+ public MCTSBotFactory(String name, OpponentModel.Factory
opponentModelFactory, SelectionStrategy decisionNodeSelectionStrategy,
+ SelectionStrategy opponentNodeSelectionStrategy, SelectionStrategy
moveSelectionStrategy, ShowdownNode.Factory showdownNodeFactory,
+ BackPropagationStrategy.Factory backPropStratFactory, Sampler sampler,
int decisionTime, MCTSListener.Factory... listeners) {
this.name = name;
this.listeners = listeners;
this.opponentModelFactory = opponentModelFactory;
- this.decisionNodeSelectionStrategy=decisionNodeSelectionStrategy;
- this.opponentNodeSelectionStrategy=opponentNodeSelectionStrategy;
+ this.decisionNodeSelectionStrategy = decisionNodeSelectionStrategy;
+ this.opponentNodeSelectionStrategy = opponentNodeSelectionStrategy;
this.moveSelectionStrategy = moveSelectionStrategy;
this.showdownNodeFactory = showdownNodeFactory;
this.backPropStratFactory = backPropStratFactory;
@@ -70,13 +62,9 @@
public Bot createBot(final PlayerId botId, GameStateContainer
gameStateContainer, RemoteHoldemPlayerContext playerContext) {
OpponentModel opponentModel = opponentModelFactory.create();
- Config config = new Config(opponentModel, showdownNodeFactory,
- decisionNodeSelectionStrategy, opponentNodeSelectionStrategy,
- moveSelectionStrategy, backPropStratFactory, sampler);
- return new MCTSBot(botId, gameStateContainer, playerContext,
- config,
- decisionTime,
- listeners);
+ Config config = new Config(opponentModel, showdownNodeFactory,
decisionNodeSelectionStrategy, opponentNodeSelectionStrategy,
moveSelectionStrategy,
+ backPropStratFactory, sampler);
+ return new MCTSBot(botId, gameStateContainer, playerContext, config,
decisionTime, listeners);
}
@Override
=======================================
--- /src/bots/mctsbot/ai/bots/bot/gametree/mcts/MCTSMeerkatBot.java Thu May
27 13:49:11 2010
+++ /src/bots/mctsbot/ai/bots/bot/gametree/mcts/MCTSMeerkatBot.java Sun
Nov 7 06:35:47 2010
@@ -13,12 +13,10 @@
import bots.mctsbot.ai.bots.bot.gametree.mcts.listeners.MCTSListener;
import bots.mctsbot.ai.bots.bot.gametree.mcts.listeners.SWTTreeListener;
import bots.mctsbot.ai.bots.bot.gametree.mcts.nodes.MCTSBucketShowdownNode;
-import
bots.mctsbot.ai.bots.bot.gametree.mcts.strategies.backpropagation.MaxDistributionPlusBackPropStrategy;
-import
bots.mctsbot.ai.bots.bot.gametree.mcts.strategies.backpropagation.MixedBackPropStrategy;
import
bots.mctsbot.ai.bots.bot.gametree.mcts.strategies.backpropagation.SampleWeightedBackPropStrategy;
import
bots.mctsbot.ai.bots.bot.gametree.mcts.strategies.selection.MaxValueSelector;
+import
bots.mctsbot.ai.bots.bot.gametree.mcts.strategies.selection.SamplingSelector;
import
bots.mctsbot.ai.bots.bot.gametree.mcts.strategies.selection.SamplingToFunctionSelector;
-import
bots.mctsbot.ai.bots.bot.gametree.mcts.strategies.selection.UCTPlusPlusSelector;
import
bots.mctsbot.ai.bots.bot.gametree.mcts.strategies.selection.UCTSelector;
import
bots.mctsbot.ai.bots.bot.gametree.search.expander.sampling.StochasticUniversalSampler;
import bots.mctsbot.ai.opponentmodels.weka.WekaRegressionModelFactory;
@@ -132,13 +130,13 @@
botFactory = new MCTSBotFactory("MCTSBot", //
WekaRegressionModelFactory.createForZip("bots/mctsbot/ai/opponentmodels/weka/models/model1.zip"),//
- new SamplingToFunctionSelector(30, new UCTSelector(40000)), //
decisionSelection
- new SamplingToFunctionSelector(50, new UCTPlusPlusSelector()),//
opponentSelection
+ new SamplingToFunctionSelector(20, new UCTSelector(50000)), //
decisionSelection
+ new SamplingSelector(),// opponentSelection
new MaxValueSelector(),// moveSelection
new MCTSBucketShowdownNode.Factory(), // showdown evaluation
- new MixedBackPropStrategy.Factory(50, new
SampleWeightedBackPropStrategy.Factory(), new
MaxDistributionPlusBackPropStrategy.Factory()), //
+ new SampleWeightedBackPropStrategy.Factory(), //
new StochasticUniversalSampler(3), // sample creation
- 100, // thinking time
+ 500, // thinking time
listeners.toArray(new MCTSListener.Factory[0]));
// botFactory = new MCTSBotFactory("MCTSBot", //
=======================================
--- /src/bots/mctsbot/ai/bots/bot/gametree/mcts/listeners/MCTSListener.java
Sat Apr 24 00:33:47 2010
+++ /src/bots/mctsbot/ai/bots/bot/gametree/mcts/listeners/MCTSListener.java
Sun Nov 7 06:35:47 2010
@@ -22,12 +22,11 @@
public interface MCTSListener {
void onMCTS(RootNode node);
-
- static interface Factory{
-
+
+ static interface Factory {
+
MCTSListener create(GameState gameState, PlayerId actor);
-
- }
-
+
+ }
}
=======================================
--- /src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/AbstractNode.java Sat
Apr 24 00:33:47 2010
+++ /src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/AbstractNode.java Sun
Nov 7 06:35:47 2010
@@ -17,7 +17,6 @@
import bots.mctsbot.ai.bots.bot.gametree.action.ProbabilityAction;
-
public abstract class AbstractNode implements INode {
//parent
=======================================
--- /src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/Config.java Sat Apr
24 00:33:47 2010
+++ /src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/Config.java Sun Nov
7 06:35:47 2010
@@ -31,39 +31,34 @@
private final BackPropagationStrategy.Factory backPropStratFactory;
private final Sampler sampler;
- public Config(OpponentModel model,
- ShowdownNode.Factory showdownNodeFactory,
- SelectionStrategy decisionNodeSelectionStrategy,
- SelectionStrategy opponentNodeSelectionStrategy,
- SelectionStrategy moveSelectionStrategy,
- BackPropagationStrategy.Factory backPropStratFactory,
- Sampler sampler
- ) {
+ public Config(OpponentModel model, ShowdownNode.Factory
showdownNodeFactory, SelectionStrategy decisionNodeSelectionStrategy,
+ SelectionStrategy opponentNodeSelectionStrategy, SelectionStrategy
moveSelectionStrategy, BackPropagationStrategy.Factory backPropStratFactory,
+ Sampler sampler) {
this.model = model;
this.showdownNodeFactory = showdownNodeFactory;
- this.decisionNodeSelectionStrategy=decisionNodeSelectionStrategy;
+ this.decisionNodeSelectionStrategy = decisionNodeSelectionStrategy;
this.opponentNodeSelectionStrategy = opponentNodeSelectionStrategy;
- this.moveSelectionStrategy=moveSelectionStrategy;
+ this.moveSelectionStrategy = moveSelectionStrategy;
this.backPropStratFactory = backPropStratFactory;
this.sampler = sampler;
}
-
+
public OpponentModel getModel() {
return model;
}
-
+
public Factory getShowdownNodeFactory() {
return showdownNodeFactory;
}
-
+
public SelectionStrategy getMoveSelectionStrategy() {
return moveSelectionStrategy;
}
-
+
public SelectionStrategy getDecisionNodeSelectionStrategy() {
return decisionNodeSelectionStrategy;
}
-
+
public BackPropagationStrategy.Factory getBackPropStratFactory() {
return backPropStratFactory;
}
@@ -75,5 +70,5 @@
public Sampler getSampler() {
return sampler;
}
-
-}
+
+}
=======================================
--- /src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/ConstantLeafNode.java
Sat Apr 24 00:33:47 2010
+++ /src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/ConstantLeafNode.java
Sun Nov 7 06:35:47 2010
@@ -21,53 +21,53 @@
public class ConstantLeafNode extends LeafNode {
public final int value;
- private int nbSamples=0;
-
+ private int nbSamples = 0;
+
public ConstantLeafNode(InnerNode parent, ProbabilityAction lastAction,
int value) {
super(parent, lastAction);
this.value = value;
}
-
+
@Override
public double getEV() {
return value;
}
-
+
@Override
public double getStdDev() {
return 0;
}
-
+
@Override
public double getEVStdDev() {
return 0;
}
-
+
@Override
public double getEVVar() {
return 0;
}
-
+
@Override
public double getVariance() {
return 0;
}
-
+
@Override
public int getNbSamples() {
return nbSamples;
}
-
+
@Override
public int getNbSamplesInMean() {
return nbSamples;
}
-
+
@Override
public double simulate() {
return value;
}
-
+
@Override
public void backPropagate(double value) {
++nbSamples;
=======================================
--- /src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/DecisionNode.java Sat
Apr 24 00:33:47 2010
+++ /src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/DecisionNode.java Sun
Nov 7 06:35:47 2010
@@ -20,20 +20,19 @@
import bots.mctsbot.client.common.gamestate.GameState;
import bots.mctsbot.common.elements.player.PlayerId;
-public class DecisionNode extends InnerNode{
-
- public DecisionNode(InnerNode parent, ProbabilityAction probAction,
- GameState gameState, PlayerId bot, Config config) {
+public class DecisionNode extends InnerNode {
+
+ public DecisionNode(InnerNode parent, ProbabilityAction probAction,
GameState gameState, PlayerId bot, Config config) {
super(parent, probAction, gameState, bot, config);
}
public INode selectChild() {
return config.getDecisionNodeSelectionStrategy().select(this);
- }
-
+ }
+
@Override
protected BackPropagationStrategy createBackPropStrategy() {
return config.getBackPropStratFactory().createForDecisionNode(this);
}
-
-}
+
+}
=======================================
--- /src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/INode.java Sat Apr 24
00:33:47 2010
+++ /src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/INode.java Sun Nov 7
06:35:47 2010
@@ -23,27 +23,27 @@
INode selectRecursively();
void expand();
-
+
double simulate();
void backPropagate(double value);
InnerNode getParent();
-
+
ProbabilityAction getLastAction();
double getEV();
-
+
double getStdDev();
-
+
double getEVStdDev();
-
+
int getNbSamplesInMean();
-
+
double getVariance();
-
+
int getNbSamples();
-
+
GameState getGameState();
double getEVVar();
=======================================
--- /src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/InnerNode.java Sun
May 23 13:04:51 2010
+++ /src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/InnerNode.java Sun
Nov 7 06:35:47 2010
@@ -37,20 +37,20 @@
//config
protected final Config config;
- //parent
+ //parent
public final GameState gameState;
public final PlayerId bot;
- //children
+ //children
private double[] probabilities = null;
private double[] cumulativeProbability = null;
private ImmutableList<INode> children = null;
- //protected boolean inTree = false;
-
- protected final BackPropagationStrategy backPropStrategy;
-
- public InnerNode(InnerNode parent, ProbabilityAction probAction,
GameState gameState, PlayerId bot, Config config) {
+ //protected boolean inTree = false;
+
+ protected final BackPropagationStrategy backPropStrategy;
+
+ public InnerNode(InnerNode parent, ProbabilityAction probAction,
GameState gameState, PlayerId bot, Config config) {
super(parent, probAction);
this.bot = bot;
this.gameState = gameState;
@@ -58,9 +58,9 @@
this.backPropStrategy = createBackPropStrategy();
}
- protected abstract BackPropagationStrategy createBackPropStrategy();
-
- public INode selectRecursively() {
+ protected abstract BackPropagationStrategy createBackPropStrategy();
+
+ public INode selectRecursively() {
//if(!inTree) return this;
// long size = config.getModel().getVisitorSize();
boolean needsChildExpansion = (children == null);
@@ -76,9 +76,9 @@
return selectedChild;
}
- public abstract INode selectChild();
-
- public INode selectChild(SelectionStrategy selectionStrategy) {
+ public abstract INode selectChild();
+
+ public INode selectChild(SelectionStrategy selectionStrategy) {
return selectionStrategy.select(this);
}
@@ -87,11 +87,11 @@
//inTree = true;
}
- public double simulate() {
+ public double simulate() {
throw new IllegalStateException("Selected node must ne leaf.");
}
- public INode getRandomChild() {
+ public INode getRandomChild() {
double randomNumber = random.nextDouble();
ImmutableList<INode> children = getChildren();
for (int i = 0; i < cumulativeProbability.length - 1; i++) {
@@ -102,12 +102,12 @@
return children.get(cumulativeProbability.length - 1);
}
- public void backPropagate(double value) {
+ public void backPropagate(double value) {
backPropStrategy.onBackPropagate(value);
parent.backPropagate(value);
}
- @Override
+ @Override
public double getEV() {
return backPropStrategy.getEV();
}
@@ -142,7 +142,7 @@
return backPropStrategy.getNbSamplesInMean();
}
- public ImmutableList<INode> getChildren() {
+ public ImmutableList<INode> getChildren() {
return children;
}
@@ -155,7 +155,7 @@
return config;
}
- protected void expandChildren() {
+ protected void expandChildren() {
if (children == null) {
Expander expander = new Expander(gameState, config.getModel(),
gameState.getNextToAct(), bot, config.getSampler());
List<ProbabilityAction> actions = expander.getProbabilityActions();
@@ -209,7 +209,5 @@
public double[] getProbabilities() {
return probabilities;
}
-
}
-
=======================================
--- /src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/LeafNode.java Sat Apr
24 00:33:47 2010
+++ /src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/LeafNode.java Sun
Nov 7 06:35:47 2010
@@ -27,10 +27,10 @@
public INode selectRecursively() {
return this;
}
-
+
@Override
public final void expand() {
// no op
}
-
-}
+
+}
=======================================
---
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/MCTSBucketShowdownNode.java
Sat Apr 24 00:33:47 2010
+++
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/MCTSBucketShowdownNode.java
Sun Nov 7 06:35:47 2010
@@ -25,13 +25,13 @@
public final BucketRollOut rollout;
public final int stackSize;
-
+
public MCTSBucketShowdownNode(GameState gameState, InnerNode parent,
ProbabilityAction probAction, OpponentModel model) {
super(parent, probAction);
- this.rollout = new BucketRollOut(gameState,parent.bot,model);
+ this.rollout = new BucketRollOut(gameState, parent.bot, model);
this.stackSize = rollout.botState.getStack();
}
-
+
@Override
public double simulate() {
return stackSize + rollout.doRollOut(4);
@@ -41,15 +41,14 @@
public GameState getGameState() {
return rollout.gameState;
}
-
- public static class Factory implements ShowdownNode.Factory{
-
+
+ public static class Factory implements ShowdownNode.Factory {
+
@Override
public MCTSBucketShowdownNode create(GameState gameState, InnerNode
parent, ProbabilityAction probAction) {
- return new
MCTSBucketShowdownNode(gameState,parent,probAction,parent.getConfig().getModel());
- }
-
- }
-
+ return new MCTSBucketShowdownNode(gameState, parent, probAction,
parent.getConfig().getModel());
+ }
+
+ }
}
=======================================
---
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/MCTSShowdownRollOutNode.java
Sat Apr 24 00:33:47 2010
+++
/src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/MCTSShowdownRollOutNode.java
Sun Nov 7 06:35:47 2010
@@ -24,13 +24,13 @@
public final DistributionRollout4 rollout;
public final int stackSize;
-
+
public MCTSShowdownRollOutNode(GameState gameState, InnerNode parent,
ProbabilityAction probAction) {
super(parent, probAction);
- this.rollout = new DistributionRollout4(gameState,parent.bot);
+ this.rollout = new DistributionRollout4(gameState, parent.bot);
this.stackSize = rollout.botState.getStack();
}
-
+
@Override
public double simulate() {
return stackSize + rollout.doRollOut(2, 2).getMean();
@@ -40,15 +40,14 @@
public GameState getGameState() {
return rollout.gameState;
}
-
- public static class Factory implements ShowdownNode.Factory{
-
+
+ public static class Factory implements ShowdownNode.Factory {
+
@Override
public MCTSShowdownRollOutNode create(GameState gameState, InnerNode
parent, ProbabilityAction probAction) {
- return new MCTSShowdownRollOutNode(gameState,parent,probAction);
- }
-
- }
-
+ return new MCTSShowdownRollOutNode(gameState, parent, probAction);
+ }
+
+ }
}
=======================================
--- /src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/OpponentNode.java Sat
Apr 24 00:33:47 2010
+++ /src/bots/mctsbot/ai/bots/bot/gametree/mcts/nodes/OpponentNode.java Sun
Nov 7 06:35:47 2010
@@ -20,21 +20,20 @@
import bots.mctsbot.client.common.gamestate.GameState;
import bots.mctsbot.common.elements.player.PlayerId;
-public class OpponentNode extends InnerNode{
-
- public OpponentNode(InnerNode parent, ProbabilityAction probAction,
- GameState gameState, PlayerId bot, Config config) {
+public class OpponentNode extends InnerNode {
+
+ public OpponentNode(InnerNode parent, ProbabilityAction probAction,
GameState gameState, PlayerId bot, Config config) {
super(parent, probAction, gameState, bot, config);
}
@Override
public INode selectChild() {
return config.getOpponentNodeSelectionStrategy().select(this);
- }
-
+ }
+
@Override
protected BackPropagationStrategy createBackPropStrategy() {
return config.getBackPropStratFactory().createForOpponentNode(this);
}
-
-}
+
+}
=======================================
***Additional files exist in this changeset.***