/** * Compute the payoffs of the game. * * @param prevMoves The list of the last moves. * @return List of triplets with player's name, payoff, and a flag telling whether it's the played role. */ public List<PayOff> GetPayoffs(GdlList prevMoves) { // (role name, payoff, my role?) list var payoffs = new List<PayOff>(Roles.Count); // Construct list of previous moves GroundFact[] previousMoves = ParsePreviousMoves(prevMoves); UpdateCurrentState(previousMoves); foreach (TermObject role in Roles) { int payoff; try { Fact goal = GetAnAnswer(CurrentContext, "goal", role.ToString(), "?x"); var score = (TermObject)goal.GetTerm(1); payoff = int.Parse(score.ToString()); } catch (Exception) { payoff = -1; } payoffs.Add(new PayOff(role.ToString(), payoff, role.Equals(MyRole))); } return payoffs; }
public static void Initialise(GdlList description) { SymbolTable = Parser.SymbolTable; GameInformation = new MetaGdl(Parser).ExamineGdl(description); var expressions = new List<Expression>(); expressions.AddRange(GameInformation.GetRules()); expressions.AddRange(GameInformation.GetAllGrounds()); Prover = new AimaProver(expressions); }
/// <summary> /// Ends the game specified by <tt>gameId</tt>. The final moves are /// processed and the payoffs are computed and printed to the logger. /// </summary> /// <param name="gameId">Name of the game to terminate.</param> /// <param name="prevMoves">The last set of moves made in the game.</param> public static void EndGame(String gameId, GdlList prevMoves) { IGamer gamer = Games[gameId]; if (gamer == null) { Logger.Error(gameId + ": WARNING: Attempting to terminate game [" + gameId + "], but no such game"); return; } try { var prevMovesStr = new StringBuilder(); prevMovesStr.Append(" Previous moves: "); foreach (GdlExpression exp in prevMoves) { prevMovesStr.Append(exp); prevMovesStr.Append(" "); } Logger.Info(gameId + ": Beginning payoff computation." + prevMovesStr); // Get the list of payoffs: <Role, Payoff, IsMe> List<PayOff> results = gamer.GetPayoffs(prevMoves); // Figure out what the longest role is int maxRoleLength = results.Select(res => res.PlayerName.Length).Concat(new[] { 0 }).Max(); // Print out the payoffs foreach (PayOff res in results) { // print the right amount of spaces (so that things line up right) var spacing = new StringBuilder(); for (int i = 0; i < maxRoleLength - res.PlayerName.Length; i++) spacing.Append(" "); Logger.Info(" " + (res.PlayedRole ? "->" : " ") + " " + res.PlayerName + spacing + " " + res.Payoff + " " + (res.PlayedRole ? "<-" : " ")); } } catch (Exception e) { Logger.Fatal(gameId + ": Error computing payoff: " + e.GetType().Name + " - " + e.Message); } // tell the game it's time to die. gamer.StopIt(); Games.Remove(gameId); }
/// <summary> /// Construct a variable fact from a GdlList. Note that the list <i>must</i> /// be a list of atoms, in other words, there cannot be any nested lists. The /// fact is constructed by taking the first element of the list as the fact's /// relation name, and every subsequent element as a column. If an atom is /// found to be a variable, then that column is marked as a variable. /// </summary> /// <param name="list">The list to build the fact from.</param> /// <returns>A variable fact representing the data from the list.</returns> public static Fact FromList(GdlList list) { int relName = ((GdlAtom)list[0]).GetToken(); var terms = new Term[list.Arity]; // Turn each element of the list into a term. // Make sure to turn same variables into the same term. bool vars = false; var varMap = new Dictionary<GdlVariable, TermVariable>(); for (int i = 0; i < list.Arity; i++) { GdlExpression exp = list[i + 1]; if ((exp is GdlVariable) == false) { terms[i] = Term.BuildFromGdl(exp, varMap); // Check to see if this term has variables in it. // (But don't bother if we already know that we have variables.) if (!vars && terms[i].HasVariables) vars = true; } else { var var = (GdlVariable)exp; terms[i] = new TermVariable(var.GetToken()); vars = true; } } // Only return a variable fact if this actually has variables if (vars) return new VariableFact(true, relName, terms); return new GroundFact(relName, terms); }
internal StopRequestHandler(ISocketWrapper socket, HttpHeader header, GdlList content, string matchId) : base(socket, header, matchId) { _content = content; }
protected GroundFact[] ParsePreviousMoves(GdlList prevMoves) { if (prevMoves == null) return new GroundFact[0]; if (prevMoves.Size != Roles.Count) Logger.Error(GameId + ": Previous move list is not the same size as number of roles!"); var previousMoves = new GroundFact[prevMoves.Size]; for (int i = 0; i < prevMoves.Size; i++) { if (i >= Roles.Count) break; previousMoves[i] = new GroundFact(Parser.TokDoes, Roles[i], Term.BuildFromGdl(prevMoves[i])); } return previousMoves; }
/** * Think about the next move and return it. * * @param prevMoves The moves just made, or nil if none (first move). * @return A triple containing: the move, an explanation (or null) and a taunt (or null). */ public Tuple<GdlExpression, string, string> Play(GdlList prevMoves) { // Construct list of previous moves GroundFact[] previousMoves = ParsePreviousMoves(prevMoves); if (previousMoves.Length > 0) UpdateCurrentState(previousMoves); Tuple<Term, string, string> move = MoveThink(); // Convert the Term to a GdlExpression GdlExpression moveGdl; if (move == null || move.Item1 == null) { Logger.Error(GameId + ": move returned by moveThink was null"); moveGdl = new GdlAtom(SymbolTable, Parser.TokNil); move = new Tuple<Term, string, string>(null, "", ""); } else { // the top-level element returned is list of all elements in the parse; // in this case, we have just one, the move. moveGdl = Parser.Parse(move.Item1.ToString())[0]; } var m = new Tuple<GdlExpression, string, string>(moveGdl, move.Item2, move.Item3); return m; }
/// <summary> /// Starts a new game. Takes the information from the start message /// and gives it to the gamer factory, which creates an appropriate /// gamer for the game. /// see stanfordlogic.Gamer /// </summary> /// <param name="gameId">The identifier of the game being started.</param> /// <param name="role">The role I am playing in the new game.</param> /// <param name="description">The description (rules) of the game.</param> /// <param name="startClock">The time given to think about the game.</param> /// <param name="playClock">The time given to make a move.</param> /// <returns>The Gamer instance created to play the game.</returns> public static IGamer NewGame(String gameId, GdlAtom role, GdlList description, int startClock, int playClock) { lock (typeof(GameManager)) { if (_gamerFactory == null) { Logger.Error("No gamer factory set!"); return null; } // Make sure this game isn't already active: if (Games.Contains(gameId)) { Logger.Error("Game already active: " + gameId); return null; } Logger.Info(""); Logger.Info("-----------------------------------------------"); Logger.Info("NEW GAME! " + gameId); Logger.Info(""); Logger.Info(" My role : " + role); Logger.Info("Start clock : " + startClock); Logger.Info(" Play clock : " + playClock); Logger.Info(""); // put in a temporary game: Games[gameId] = null; } IGamer g = _gamerFactory.MakeGamer(gameId, role, description, startClock, playClock); lock (typeof(GameManager)) { Games[gameId] = g; } return g; }
private void ExamineTopLevelList(GdlList list) { // Is this a rule, or a relation? // Note that it is safe to assume that the head is in fact an atom. var head = (GdlAtom)list[0]; if (head.GetToken() == _parser.TokImpliedby) { Implication impl = ExamineRule(list); AddRule(impl.Consequent.RelationName, impl); } else { // It must be a ground fact at this point: it can't have variables, // since there is no rule to specify binding. var f = (GroundFact)ExamineListRelation(list, head.GetToken()); AddGround(head.GetToken(), f); // Is this a role? if (head.GetToken() == _parser.TokRole) _roles.Add((TermObject)f.GetTerm(0)); } }
private void ExamineListTerm(GdlList list) { // The first element here must be a function symbol. // Note that it is safe to assume that the head is in fact an atom. var head = (GdlAtom)list[0]; int token = head.GetToken(); //TODO: Make sure that 'token' is a function symbol. //if (IsObjectSymbol(token) || IsRelationSymbol(token)) // throw new Exception("Symbol '" + token + "' (" + _parser.SymbolTable[token] + ") already exists, but not as a function symbol!"); // Add it to our list of function symbols AddFunctionSymbol(token); // Now look at the rest of the elements in the list. for (int i = 1; i < list.Size; i++) ExamineTerm(list[i]); }
private Expression ExamineListRelation(GdlList relation, int relName) { // First: check to see if this is a logical operator, i.e. one of not/or/and if (relName == _parser.TokNotOp) // The next element must be a sentence return new Negation(ExamineRelation(relation[1])); if (relName == _parser.TokOrOp) { // all the rest of the elements are relations (sentences), not terms. var disjuncts = new Expression[relation.Arity]; for (int i = 1; i <= relation.Arity; i++) disjuncts[i - 1] = ExamineRelation(relation[i]); return new Disjunction(false, disjuncts); } // Second case: normal relation. //TODO: Make sure this symbol isn't a function/object symbol already. //if (IsFunctionSymbol(relName) || IsObjectSymbol(relName)) // throw new Exception(string.Format("Symbol '{0}' ({1}) already exists, but not as a relation symbol!", relName, _parser.SymbolTable[relName])); // Add the relation name to our list of relation symbols. AddRelationSymbol(relName, relation.Arity); // Examine each term of the relation for (int i = 1; i <= relation.Arity; i++) ExamineTerm(relation[i]); // Convert the relation to a (ground or variable) fact. return Fact.FromExpression(relation); }
public Implication ExamineRule(GdlList rule) { // First element is the IMPLIEDBY token; ignore it. // Second element is the head of the rule. It's a relation (fact). var head = (Fact)ExamineRelation(rule[1]); // Everything thereafter are the antecedent relations. var conjuncts = new Expression[rule.Arity - 1]; // Create the conjunct list for (int i = 2; i < rule.Size; i++) conjuncts[i - 2] = ExamineRelation(rule[i]); conjuncts = DistinctSorter.SortDistincts(conjuncts); // Create a rule structure and add it to our list. return new Implication(false, head, conjuncts); }
protected abstract RequestHandler CreateFromList(ISocketWrapper socket, RequestHandler.HttpHeader header, GdlList list);