U U N N G400 C C S S
G53IDS I I D D 40 C C
Dissertation T C
Author: Robe Robert rt M M rxm08u Subm Submit itte ted d May May 2011 2011,, in pa part rtiial fulf fulfil ilme ment nt of the the cond condit itio ions ns of the the award ward of B B S S ..
I here hereby by Decl Declar are e that that this this diss disse ertat rtatio ion n is all all my own work work,, excep xceptt as indi indica cate ted d in the the text text:: Signature:
May 5, 2011
Abstract
Chess AI research has largely stagnated into optimisations of the same paradi paradigms gms,, such such that that some some believ believee resear research ch should should focu focuss on a differe different nt game. game. We propose Time Chess, a Chess-related game designed to be interesting and challenging for humans, and prohibitively complex for currently prevalent Chess AI approaches, in an attempt to encourage advances in new AI paradigms. High complexity is achieved by extruding Chess into the higher dimension of Time. The game rules are designed and specified, and sample implementations of a Time Chess Engine and 3D Interface are designed and implemented, along with a Protocol Specification to ensure compatibility between future engines, GUIs and AIs.
2
Contents 1
Introduction 1.1 Aims . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2 Background 2.1 Chess Programs . . . . 2.2 Current Chess AI . . . 2.3 Other HyperChesses . . 2.4 Other Complex Games 2.4.1 Go . . . . . . . 2.4.2 Arimaa . . . . . 3
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
Design 3.1 System Architecture . . . . . . . . . . . . . . . 3.2 Designing Time Chess as a Game . . . . . . . 3.2.1 Game Design Principles . . . . . . . . 3.2.2 Game Design Process . . . . . . . . . . 3.2.3 Move Notation . . . . . . . . . . . . . 3.2.4 .2.4 Designing Backwards Time Travel . . . 3.2. .2.5 Designing the Movement of the Pawn 3.3 Designin ning Time Chess as Softwar ware . . . . . . . 3.3.1 Requirements Specification . . . . . . 3.3.2 Engine Design . . . . . . . . . . . . . . 3.4 Designing the 3D Interface . . . . . . . . . . . 3.4.1 Piece Shapes . . . . . . . . . . . . . . . 3.4.2 Boards . . . . . . . . . . . . . . . . . .
4 Implementation 4.1 Technology Choices . . . . . . . . . . . 4.1.1 Why Python? . . . . . . . . . . 4.1.2 Why NumPy? . . . . . . . . . . 4.1.3 Why VPython? . . . . . . . . . . 4.2 Implementing The Time Chess Engi ngine 4.2.1 Implementation Description . . 4.2.2 How it works . . . . . . . . . . 4.3 Implementing the 3D Interface . . . . . 4.3.1 Imp Implementation Description . . 4.3.2 How it Works . . . . . . . . . .
3
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . .
. . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . .
. . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5 5
. . . . . .
7 7 7 8 9 9 10
. . . . . . . . . . . . . . . . . . . . . . . . . .
13 13 14 14 15 17 18 22 23 23 25 25 26 27
. . . . . . . . . .
29 29 29 30 30 31 31 32 39 39 40
. . . . . .
. . . . . . . . . .
4.4 5
Extra Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.4.1 Stereo . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Evaluation 5.1 Difficulty for Computers . . . . . . . . . 5.1.1 Branching Factor . . . . . . . . . 5.2 Unit Tests . . . . . . . . . . . . . . . . . 5.3 User Acceptance Testing . . . . . . . . . 5.3.1 The King becoming Lost in Time 5.3.2 Survey . . . . . . . . . . . . . . . 5.4 Requirements . . . . . . . . . . . . . . .
42 42
. . . . . . .
45 45 45 46 47 47 50 53
. . . . .
55 55 55 55 56 57
. . . . . . . . . . .
63 63 64 64 66 66 67 67 67 67 68 68
B Time Time Ch Cheess Engine gine Commu ommuni nica cati tion on Prot Protoc oco ol Speci pecifi ficati cation on B.1 Messages from the GUI to the Engi ngine . . . . . . . . . . . . . . . . B.2 Messages from the Engine to the GUI . . . . . . . . . . . . . . . .
69 70 71
C Time Chess 3D Interface: User Guide C.1 Looking Around . . . . . . . . . C.2 Selecting Pieces . . . . . . . . . C.3 Moving Pieces . . . . . . . . . . C.4 Keyboard Controls . . . . . . . .
73 73 73 73 74
6 Summary 6.1 Further Work . . . . . . . . . . . . . . 6.1.1 Interface Improvements . . . . 6.1.2 Accurate Complexity Est Estimates 6.1.3 Affective Analysis . . . . . . . . 6.1.4 Personal Reflections . . . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
A The Rules of Time Chess A.1 Board and Pieces . . . . . . . . . . . . . . . . A.2 Objective . . . . . . . . . . . . . . . . . . . . A.3 Movement . . . . . . . . . . . . . . . . . . . A.3.1 Blocking . . . . . . . . . . . . . . . . A.4 Forward Time Travel . . . . . . . . . . . . . A.4.1 Appearance Order . . . . . . . . . . A.4.2 The ‘Lost in Time’ Rule . . . . . . . . A.5 Backward Time Travel . . . . . . . . . . . . . A.5.1 Taking Pieces Back in Time . . . . . A.5.2 Braindead Pieces and Steamrollering A.6 Check . . . . . . . . . . . . . . . . . . . . . .
4
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . .
. . . .
Chapter 1
Introduction This document documents the design of Time Chess, a new Chess variant which incorporates time travel as a core game mechanic, and the construction of a computer implementati implementation on of Time Chess to make make the game playable playable by pairs of humans.
1.1 Aims Time Chess has two main (interrelated) aims. The first aim of Time Chess is to have an extremely high cognitive load. In layman’ man’s term terms, s, this this can can be thou though ghtt of as “how “how diffic difficul ultt the the game game is to play play”. ”. Howe Howeve verr this definition is insufficient, because ‘difficulty’ is a broad term which can refer to many different challenges, including non-mental ones. Specifically, ‘cognitive load’ in this context refers to the level of mental activity involved in playing the game properly. properly. It is a function function of the amount of processing processing that must be done, and the amount of game state information that must be stored in working memory in order to play. (Paas, Tuovinen, Tabbers & Van Gerven 2003) Determinants of cognitive load include the number of possible moves available able to the the play player er and the the numb number er of fact factor orss that that must must be cons consid ider ered ed in eval evalua uati ting ng a possible move. The cognitive cognitive load of a game is therefor thereforee closely related related to its complexity. 5
Chess is generally considered to be a complex game (Shannon 1950), but Time Chess is far more complex. This complexity helps to contribute to the second aim of Time Chess, which is to provide a chess variant that presents new and interesting challenges to both human and machine players, encouraging AI research to yield results useful in general Chess AI and beyond. It’s worth noting that we do not aim to implement a Time Chess AI here, but to provide the groundwork for others to build on.
6
Chapter 2
Background 2.1 2.1 Ch Ches esss Prog Progra rams ms Ther Th eree is a very very larg largee numb number er of prog progra rams ms allo allowi wing ng huma humans ns to play play Ch Ches esss on a comcomputer puter.. The These se are genera generally lly divide divided d into into Chess Engines Engines and Chess User Interface Interfacess. The player(s) interact with the interface, and the interface communicates with the engine, gine, which which is respons responsibl iblee for for the rules rules of the game. game. This This archit architect ecture ure is essent essential ially ly a Model View Controller. Most chess software is written with ‘loose coupling’ in mind mind,, such such that that the the engi engine ne and and the the inte interf rfac acee need need very very litt little le know knowle ledg dgee abou aboutt one another to work together. They communicate by standardised protocols, for example Chess Engine Communication Communication Protocol , and can thus work equally well with any component supporting the protocol. Shou Should ld the the play player er deci decide de to play play a comp comput uter er (or (or set set up a comp comput uter er vs. vs. comp comput uter er game), the engine handles the AI.
2.2 Curre Current nt Chess Chess AI Standard Chess is essentially beaten as an AI challenge. Easily available software running on a standard personal computer can beat master and even world champion human players. players. But some researchers researchers find existing existing Chess AI unsatisfying unsatisfying,, and Chess AI research has not provided as much that is useful outside of the field
7
as was once expected. Successful Chess AIs do not think about Chess in the way that that humans humans do. The algori algorithm thmss used used genera generally lly work by evalua evaluatin tingg large large number numberss of potential moves, looking ahead several moves, and deciding on the best move based on those evaluations. “ …we should expect that machines will perform this narrow task so well … that their skill will be orders of magnitude superior to the best human play… What will be the significance of this accomplishment for other areas of AI research? Sadly, not much. The brute force nature of the final solution might tell us how to go about building a parallel architecture ‘Go’ or ‘Che ‘Check cker er’’ mach machin ine, e, if we are are so incl inclin ined ed,, but but it does does not not scal scalee up to prob proble lems ms in robotics or expert systems, for example.” – L. Stephen Coles (Coles 2002)
We posit that if researchers are to make progress p rogress in Chess AI which will be useful in other fields, these brute-force based ‘successful but boring’ approaches must first be broken. Time Chess aims to do that.
2.3 Other HyperChesses Time Time Ch Ches esss can can be thou though ghtt of as Ch Ches esss extr extrud uded ed into into the the extr extraa dime dimens nsio ion n of time time.. Chess games games extruded into higher higher dimensions dimensions can be called HyperChesses. Several Several HyperChesses have been designed (Pritchard & Beasley 2007). Most of these extrude into a single higher spatial dimension, creating 3D Chess. Perhaps the best known is “P Tri-D Chess”, which is played on a bizarre array of boards boards of different different sizes. Programs Programs like like Parmen allow this game to be played on a computer. There is also Raumschach, a game played on a 5 ×5×5 board, and a large number ber of vari varian ants ts play played ed on 8×8×3 boards boards,, includ including ing Millenn Millennium ium 3d Chess Chess and DragDragonChess. 8
Few Few atte attemp mpts ts have have been been made made to use Time Time as a dime dimens nsio ion n in Hype HyperC rChe hess ss,, and and those that have have not been very serious. Jay Shaffstall Shaffstall proposed a ‘Temporal ‘Temporal Chess’ (Shaffstall n.d.), but little came of it. In all of these HyperChesses, with the possible exception of Raumshach, the extra dimension is treated as a ‘second-class citizen’, either by the board being smaller in that dimension, or by having movement in that dimension occur under limited limited or varied rules. rules. In Time Chess, we aim to have t be as important a coordinate as x or y.
2.4 Other Other Comp Complex lex Games Games There are many games designed to be complex, and some that are specifically designed to be challenging for machine players.
2.4.1 Go Go is a highly complex game (Allis 1994), and provides a much more difficult challenge in AI research research than Chess. The reasons reasons for this are explored explored in detail in Crâsmaru (1999), we will only briefly summarise them here. • The board board is 19 19×19, much larger than a chess board. • Movement Movement is less restricte restricted. d. Generally Generally almost any any unoccupied unoccupied space is a legal move. • The game becomes more complex as it goes on, as pieces are added, in concontrast to Chess, in which pieces are removed. • Evaluating a move requires analysis of the structure of the layout, with few of the computationally cheap move evaluation factors available to Chess, like “What’s the value of the pieces I can take if I make this move”.
9
For thes thesee reas reason ons, s, Go is thou though ghtt of by many many as the the next next chal challe leng ngee and and focus ocus of game game AI rese resear arch ch (Sto (Stone ne n.d.) n.d.).. Howe Howeve ver, r, ther theree are are also also thos thosee wh who o thin thinkk that that Ch Ches esss still has a lot to teach us (Iqbal n.d.), and should not be abandoned yet.
2.4. 2.4.22
Arim Arimaa aa
Arimaa is a game designed with fairly similar goals to those of Time Chess. It is intended to be playable by a four year old, and very difficult to play for an AI (Syed & Syed 2003). 2003). One way in which it poses a problem problem for brute-force brute-force based AI players is by having a very high number of possible moves available each turn (∼17,281 compared to Chess’ ∼35). The number (called the branching factor ) is so high high in Arim Arimaa aa beca becaus usee eachturn eachturn is made made up of seve severa rall move moves, s, and and ther theree are are seve severa rall choices that need to be made in each move. In chess, there is only one move per turn, and two choices to be made per move - which piece to move, and where to move move it to. to. Th Ther eree are are a maxim maximum um of 16 piec pieces es from from wh whic ich h to choo choose se,, and and gene genera rall llyy only a few possible moves for a piece. For example, Knights get at most 8 possible moves, and the most mobile piece, a queen, when placed in its most free position, the centre of the board, still has only 27 possible moves. In Arimaa Arimaa,, four four moves moves a turn turn are possib possible, le, immedi immediate ately ly increa increasin singg possib possibili ilitie tiess by a factor of four. However, not all four moves must be used each turn, a player can elect to make any number number of moves between one and four. This further further increases the number of possible turns. The player may elect to allocate their up to four moves however they want between their pieces, further increasing the number of possib possibili ilitie ties. s. The game game revolv revolves es around around a mechan mechanic ic of ‘push ‘pushing ing and pullin pulling’, g’, by which pieces can move opposing pieces on the board. A piece can move away from an opposing piece leaving it in place, or it can move and pull the opposing piece with it, which provides another choice, doubling the search space for many moves. Each extra choice provides an extra dimension to the abstract turn-space, exponentially increasing the size of that space (this is often called “The Curse of Dimensionality”). The resulting explosion of options makes the search space ex-
10
tremely large and difficult for an AI to handle, but doesn’t inconvenience human players much. Human players can be thought of as having a particular maneuver, goal or strategy in mind, and searching for a way to work within the restrictions set by the game rules to achieve that aim. Most Chess AIs can be thought of as having a space of possible moves, and attempting to search that space for a good move to play. Look Looked ed at in this this way way it is clea clearr that that for a huma human, n, more more free freedo dom m mean meanss weak weaker er restrictions applied by the game, which makes it easier to play, but for a Chess AI that freedom means a much larger move-space to search. More choice makes things easier for the human and harder for the AI. 2.4.2.1 2.4.2.1 Difference Difference to Time Chess Chess
The aims of Arimaa vary from those of Time Chess, in that Arimaa attempts to be simple for a human and difficult for a machine, whilst Time Chess makes no attempt to be simple for a human to play. While Arimaa, like Time Chess, can be played on a standard chessboard, Arimaa is so radically different in its gameplay that it cannot be considered a ‘chess variant’, but is rather a completely different game played on the same board. Advanc vances es in Arim Arimaa aa AI may may not not be helpf helpful ul in deve develo lopi ping ng more more inte intere rest stin ingg AI for for nornormal mal Ch Ches ess. s. Time Time Ch Ches esss on the the othe otherr hand hand is simi simila larr enoug enough h to Ch Ches esss that that adva advanc nces es in Time Chess AI are more likely to be applicable to standard Chess.
11
12
Chapter 3
Design 3.1 Syste System m Archit Architect ecture ure At the highest level, the design consists of two separate programs - The Time Chess Engine, and the User Interface. The programs are functionally independent, and communicate using a simple text protocol. This architecture is influenced by the design design of popular existing chess programs, most notably notably the GNUChess engine and the XBoard chess GUI. This approach approach has many advantages over monolithic monolithic designs. designs. Firstly, Firstly, it is a sensible separation of concerns. The loosely coupled design means that the two programs are insulated from changes in the other during development. The engine can be rewritten to operate in a very different way, but as long as it still supports the protocol, protocol, the GUI need not be changed changed at all, and vice versa. Not only this this,, but but the the modu modula lari rity ty of the the syst system em allo allows ws part partss to be swap swappe ped d out and and repl replac aced ed by completely different ones. Other programmers could develop their own interfaces, which could be completely different from mine but would work with the engine without any reconfiguration. The components are unconcerned not just with the nature of the other component, but also with the nature of the connection tion betwee between n them. them. My implem implement entati ation on will will use operat operating ing system system level level pipes, pipes, but the system could work just as well over a TCP connection for example.
13
3.2 Designing Designing Time Chess Chess as a Game 3.2.1 Game Design Design Principl Principles es Before formalising the design of the game, I decided on some principles which I wanted the game to adhere to. 3.2.1.1 3.2.1.1 Remain Remain true to Chess
• Styling, gameplay concepts, terminology etc. should not be changed changed unless necess necessary ary.. This This will will make make the game game more more clear clear to those those alread alreadyy famili familiar ar with with Chess • Piece movements should be their Chess equivalents extruded into a higher dimension as literally as possible 3.2.1.2 3.2.1.2 Be complex complex for computers computers
• The game’s state space should be large, as should the number of available choices, to keep the branching factor high. 3.2.1.3 3.2.1.3 Allow for intere interesting sting and tactica tacticall gameplay gameplay
• Attempt to ‘nerf the FOO strategies’, that is to say don’t don’t allow ‘First-Order Optimal’ strategies to allow players to win without requiring much skill 3.2.1.4 3.2.1.4 PlayerPlayer-Time Time is linear linear
• Repetitionisdullandlong-winded. Neverrequirethesameturntobeplayed more than once • If move movess to the the past past requ requir iree the the inte interve rveni ning ng turn turnss to be play played ed agai again, n, it woul would d bepossibletohaveanever-endinggamethatcontinuallyloopsoverthesame few moves, because players would be motivated to continually backtrack to attempt to prevent past losses and mistakes.
14
3.2.1.5 3.2.1.5 To hell with paradox paradoxes es
• Paradoxes should should be either impossible to create, or trivial to resolve unambiguously and deterministically.
3.2.2 Game Design Design Process Process The first part of the design process, since Time Chess is a variant of Chess, was to full fullyy fami famili liar aris isee myse myself lf with with the the deta detail ilss of the the rules rules of Ch Ches ess. s. I obta obtain ined ed and and read read a copy of “Laws of Chess”, a document published by the F, the World Chess Federatio eration. n. The docume document nt is probab probably ly the most most author authorita itativ tivee chess chess rule-s rule-set et availa available ble.. By use use of this this docu docume ment nt,, and the the free freely ly avai availa labl blee sour source ce code code of the the GNUCh GNUChes esss Chess engine (GNU Project n.d.), I implemented my own chess game in Python. An interaction with the resulting program is shown in figure 3.1. This made sure that I properly understood the rules of Chess, since it’s not possible to write a program to simulate chess without understanding all of the rules. It also helped me to gather my thoughts on what kinds of algorithms and data structures work well for this class of problem, which would be useful later. Once I had a good grasp of the rules of Chess, I began planning in detail how to extrude it into a higher dimension. For this I looked at the hyperchess games discussed in section 2.3, which gave me a good idea of the general approach taken by other Chess variants, and made me aware of their shortcomings that I wished to avoid. During the course of the design process I discussed the rules with a number of people, including the members of The University of Nottingham Chess Club, which made made several things clear to me. Firstly, Firstly, this game was (as intended) very confus confusing ing,, and difficul difficultt to discus discusss verbal verbally ly.. English English gramma grammatic tical al constr construct uction ionss are very poorly suited to talking about time travel, so clear and consistent use of language was required. required. Secondly Secondly,, the game was much easier to discuss discuss with Chess enth enthus usia iast stss than than with with thos thosee not as inte intere rest sted ed in Ch Ches ess. s. There There is no doub doubtt that that this this had had many many caus causes es,, not leas leastt of wh whic ich h was was inte intere rest st,, but but a larg larger er part part than than anti antici cipat pated ed 15
Figure 3.1: Interaction with the command line interface of the chess game, showing movement and display of possible moves
16
was due to knowledge knowledge of a shared shared terminology terminology with Chess. Chess terminology terminology could be exapted to describe related concepts in Time Chess, which confirmed my belief that Time Chess should echo Chess as closely as practical, to aid understanding of the game by Chess players. Thirdly, because verbal discussion of the rules was difficult, we made use of sketches and diagrams as visual aids. From this it became apparent that Time Chess is a fundamentally three-dimensional game, which is difficult to express on a two-dimensional plane. This Th is need need for for a 3D way way to expl explai ain n the the game game,, comb combin ined ed with with the the ineff ineffec ecti tive vene ness ss of hand hand gest gestur ures es,, demo demons nstr trat ated ed a need need for for a tool tool to allo allow w easy easy 3D visua visuali lisa sati tion onss of arrang arrangeme ements nts of pieces pieces.. The tool tool was built built fairly fairly quickl quickly, y, making making use of the Python Python language and the visual module (see section 4.1.3). It allowed simple 3D scenes of Time Time Ch Ches esss scen scenar ario ioss to be buil builtt quic quickl klyy and and inte intera ract cted ed with with,, wh whic ich h was was a grea greatt help help in discus discussin singg hypoth hypotheti etical cal scenari scenarios os and comple complexx rules. rules. An screen screensho shott of the tool is shown in figure 3.2. The excellent performance of the visual module for this task led to the decision to use it for a full 3D interface to the engine.
3.2.3 3.2.3 Move Move Notat Notation ion Because positions in Time Chess have an extra dimension, a new notation had to be created to describe them. Normal notation simply concatenates the file letter with the rank number, so a piece on file c and rank 6 is at position c6. In Time Chess there is also a time coordinate representing the turn. One option is simply to conc concat aten enat atee the the turn turn onto onto the the stan standa dard rd nota notati tion on,, so the the same same piec piecee in turn turn one would be at c61. This would work, work, because the rank number number is only ever 1–8, and thus is always exactly one digit long, so there is no need to delimit the fields. However, the chosen solution was to separate the values with a ’t’. Thus the piece would be at c6t1. This makes the positions easier to understand, since the ’t’ can be read as ‘time’ or ‘turn’. It also allows for future variants to be played on boards with more than 9 ranks without modifying the notation.
17
Figure 3.2: The 3D visualisation tool demonstrating the move options of a Knight For denoting movements, the notation simply concatenates two positions, so c6t1e8t1 means “Move from file c, rank 6 in turn 1 to file e rank 8 in turn 1”.
3.2.4 Designing Designing Backward Backwardss Time Tr Travel avel The main game design challenge of Time Chess is backwards time travel. 3.2.4.1 3.2.4.1 Differen Differentt Time Time Travel Travel Models Models
There are many different models of time travel (Nahin ( Nahin & Nahin 1994), which have different differentunderl underlying ying assumptions assumptions,, levelsof levels of internal internal consistenc consistency, y, and consequence consequencess for gameplay. Among the decisions that must be made are: • Single Single vs. Multiple Multiple Timelines Timelines – In some models there is only one timeline, and thus the past that the
travel traveller ler arrive arrivess at leads leads direct directly ly to the presen presentt from from which which the travel traveller ler left left,, wh whic ich h may may be the the same same or diffe differe rent nt from from wh when en the the trav travel elle lerr left left it. it.
18
– In others others,, travel travellin lingg backwa backwards rdsin in time time causes causes a new timeli timeline ne that that splits splits
and diverges from the first when something is changed • Choice Choice vs. Fate Fate some mode models ls,, chan change gess to the the past past have have cons conseq eque uenc nces es for for the the pres presen entt – In some and future – In other models (known as Eternalist or Block Time models (Stanford
Univer Universit sityy 2008)) 2008))thepast, thepast, presen presentt andfut and future ureare areaa consis consisten tentt immuta immutable ble whol wh ole, e, so any any chan change ge you you mak make to the the past past inev inevit itab ably ly lead leadss to the the cond condiitions observed before making the change. In other words, every backwards time travel must by definition establish a stable time loop, such that changing the present by changing the past is impossible, because the the pres presen entt you you obse observe rve is the the resu result lt of you you havi having ng alre alread adyy chan change ged d the the past. • Stable vs. Unstable Unstable – In some some mode models ls,, the univ univer erse se itse itself lf is in enda endange ngere red d by time time trav travel el,, be-
cause the creation of paradoxes creates contradictions that cause reality itself to collapse • Physical Laws vs. Regulatory Laws – In some models, the limitations on time travel are inherently invio-
lable, as they are natural consequences of the laws of the universe – Othe Otherr mode models ls cont contai ain n an agen agentt or agen agents ts resp respon onsi sibl blee for for ensu ensuri ring ng that that
certain certain rules are obeyed by time time travellers. travellers. These can be in the form form of ‘Time Cops’, or some form of disembodied entity that acts to attempt to maintain the ‘natural order of things’. • Low Level Consistency vs. High Level Consistency Consistency vs. No Consistency – Some models require low level consistency, that is to say that at every
point in the timeline(s), from the perspective of every individual, the 19
universe must remain consistent (or ‘make sense’). Almost all models of time travel proposed by physicists fall into this category. Some models models requir requiree only only high high level level consis consisten tency cy,, meanin meaningg that that imposimpos– Some sible sible or inconsi inconsiste stent nt things things are permis permissib sible le in certai certain n timeli timelines nes or from from certain perspectives, as long as the ‘definitive’ or ‘final’ time line makes sense. – Some models seem to require almost no consistency at all, but this is
mostly down to lazy writing. 3.2.4.2 3.2.4.2 Choosing Choosing a Time Time Travel Travel Model Model
Thee orig Th origin inal al inte intent ntio ion n was was a syst system em with with a sing single le time timeli line ne,, choi choice ce,, stab stabil ilit ity, y, phys physiical laws, and low level consistency. However, it quickly became clear that a single timeline was incompatible with choice and low level consistency, without ‘overwriting’ the timeline by re-playing past moves, which I decided would be bad for gameplay (section 3.2.1.4). In other words, in order to have a timeline that is consistent at all points (in a game like this this would mean that all moves in every timeline must be legal), it’s necessary that either the past can never be changed (which would negate the point of having it as a possible move), or turns must be replayed when something changes them (to maintain consistency). 3.2.4.3 3.2.4.3 Limitation Limitationss to Causality Causality
Low level consistency means that causality always follows properly. Models with low level causality are subject to the ‘Butterfly Effect’ (Hilborn 2004); A change to the the past past is lik likely ely to caus causee othe otherr chang changes es,, and and thos thosee chan change gess are are lik likely ely to caus causee thei theirr own corresponding changes, and so on. The easy way to deal with this in a Time Ches Ch esss game game is to, to, wh when enev ever er ther theree is a chang change, e, play play from from that that poin point, t, with with the the play player erss obeyin obeyingg the normal normal rules, rules, thus thus mainta maintaini ining ng low level level consis consisten tency cy.. Howeve Howeverr this this is unacceptable for reasons discussed in section 3.2.1.4, chief among them being the possibility of being stuck in an endless game replaying the same few turns.
20
So, So, consi consist sten ency cy must must be figur figured ed out out witho without ut huma human n inte interf rfer erenc encee if the the game game is to rema remain in play playab able le.. The The natur naturee of the the situ situat atio ion n - each each chan change ge caus causing ing a numb number er of further changes - clearly calls for a recursive algorithm. The problem is that many backward time travel moves would involve a change which creates changes which undo the original original change - a paradox. paradox. A recursive recursive algorithm attemptin attemptingg to resolv solvee such such a move move will will ente enterr an infini infinite te recu recurs rsiv ivee loop loop.. Such Such loop loopss can can be dete detect cted ed (Van (Van Geld Gelder er 1987) 987),, but but the the best best cour course se of acti action on wh when en such such a loop loop is dete detect cted ed is not not clear. clear. At what point of the loop should it be stopped and the board state fixed? fixed? Perhaps all moves resulting in paradoxes should be illegal, but this would reduce the number of available moves at each turn, reducing the branching factor of the game, which we decided against in section 3.2.1.2. So, without human interaction, true recursive low level consistency in Time Chess quickly becomes very messy. Some form of limit must be put on causality, and thus consistency. Changes cannot be allowed to cause more changes indefinite nitely ly.. Th Thee ques questi tion on then then beco become mess “Whe “Where re to draw draw the the line line?” ?”.. How How much much can can you you restrict causality without negating the point of travelling backward in time in the first place? 3.2.4. 3.2.4.4 4 The Decisi Decision on
The system I settled on (described in section A.5) is that when pieces travel back in time, any opposing piece they land on is captured and removed from the game from that point forward, forward, but no further further change is made to the timeline. timeline. Pieces Pieces taken by a captured piece are not returned, moves made illegal by the changes remain remain as they are. The piece that travelled travelled back remains remains in place, propagating forward forward to the present as though it had just sat still in the intervening time. If another piece moves into the space occupied by the backward traveller as it propagates agates to the presen present, t, the backwa backward rd travel traveller ler is destro destroyed yed.. This This stops stops the existe existence nce of the inactive backwards traveler from having knock-on effects on the timeline.
21
3.2.4.5 3.2.4.5 An Alternate Alternate Possibi Possibility lity
An option was considered which involved a degree of consistency and causality high higher er than than that that of the the chos chosen en solu soluti tion on,, was was one one that that atte attemp mpte ted d to guar guaran ante teee that that all moves at all times were either legal or didn’t happen. That is to say that if any move is, due to changes brought about by time travel, rendered illegal, that move is simply undone, and the timeline continues continues as though at that turn no move of any any kind kind was made made.. It is wort worth h noti noting ng that that in both both Ch Ches esss and and Time Time Ch Ches ess, s, the the only only way a player may end their turn is by making a move, there is no option to ‘skip a turn’, so undoing a move does not render it legal in the normal sense. The advantage of this system is that moves are able to have tactically useful knock-on effects (like undoing an opponent’s move) but are not susceptible to paradoxes. paradoxes. In the case of a paradox, paradox, all moves involved involved in the loop will eventueventually be rendered illegal and undone. However, this solution was rejected because in situ situat atio ions ns of para parado doxx (whi (which ch are are quit quitee lik likely ely for for long long back backwa ward rdss time time trav travel el)) the the effect effect is to undo every move up to the present, present, effectively effectively resetting the board to the latest point not affected affected by the paradox. paradox. This means that although although the turn number is larger, for all intents and purposes the players may as well be replaying a turn from several moves ago, which goes against the principles discussed in section 3.2.1.4.
3.2.5 Designing Designing the Movemen Movementt of of the the Pawn Pawn The Pawn is an unusual piece in both Chess and Time Chess, following unique movement movement rules. The Pawn is the only piece which is restricted restricted in the direcdirection it can move based on its colour, colour, since it can only move forward. forward. It could be argued that in order to properly extrude this concept into higher dimensions, White Pawns should be able to move backwards in time but not forwards, and Black Pawns Pawns should be able to move forwards in time but not backwards. backwards. However, ever, due to the differe difference ncess in the practi practical cal gamepl gameplay ay conseq consequen uences ces of forwar forward d and backward time travelling moves, this would almost certainly unbalance the game 22
by giving one side’s side’s pawns an unfair advantage. advantage. So the movement of the Pawns described in section A.3 applies to pawns of either colour.
The final result of the game design process is the document The Rules of Time Chess, Appendix A.
3.3 Designing Designing Time Chess Chess as Software Software 3.3.1 Requireme Requirements nts Specificat Specification ion 3.3. 3.3.1. 1.11 Aim Aim
Thee aim Th aim of the the soft softwa ware re syst system em is to allo allow w huma human n and and mach machin inee play player erss to play play the the game of Time Chess, as defined in The Rules of Time Chess (appendix A). 3.3.1. 3.3.1.22 Engine Engine
• Keeps track of the state of a game of Time Chess – Maintains a data structure storing the state of the board at every past
turn – Maintains a count of what turn the game is at, which increments with
every legal move • Allows Allows moves moves to be made – Only allows moves to occur if they are legal¹
• Responds with informative informative messages when an illegal move is attempted – Supplies the reason that the move is illegal
• Enforces player turn order, starting with white and only switching turns when a legal move is made ¹according to The Rules of Time Chess (appendix A)
23
• Detects when the the game is finished, and which side was victorious – Starts a new game when a game is concluded
• Supports the Time Time Chess Engine Communication Communication Protocol (appendix (appendix B) – Receives TCECP messages via stdin – Sends TCECP messages via stdout – Outputs all non-TCECP output to stderr – Returns accurate and relevant information in response to TCECP in-
formation requests – Acts on TCECP commands appropriately – Comprehends Time Chess Move Notation (section 3.2.3) 3.3.1. 3.3.1.33 3D Interf Interface ace
• Allows the user to see a 3D representation of the game state – Represents pieces as 3D objects
* Objects must be recognisable as chess chess pieces * Objectsmustbedifferentiablebyshapeintodifferenttypesofpiece – Represents the squares of the board – Shows game state as a ‘stack’ of chess boards
* Places Places the beginning of the game at the bottom and subsequent subsequent turns on top as layers • Allows the user to adjust their view of the game game state – Allows adjusting the rotation of the view – Allows adjusting the tilt of the view – Allows adjusting the zoom level of the view – Allows adjusting which layers
24
• Allows the user to select their pieces – Selects pieces by clicking on them
• Allows the user to see which moves are available for for a selected piece – Visibly highlights positions which can be moved to by that piece
• Allows the user to select intended moves – Selects moves by clicking on the highlighted positions
• Opens a connection to to a program supporting the engine side of the TCECP • Supports the the GUI side of TCECP Sends proper properly ly forma formatte tted d TCECP TCECP comman commands ds andreq and reques uests ts to theTCECP – Sends Interface Responds ds approp appropria riatel telyy to data data receiv received ed through through the TCECP TCECP Interf Interface ace – Respon
3.3.2 3.3.2 Engin Enginee Design Design Thee gene Th genera rall stru struct ctur uree of clas classe sess outl outline ined d in figur figuree 3.3 3.3 was was devi devise sed d to be able able to meet meet the requirements. The engine is to be operated by the makeMove method, and interrogated for data by the getPossibleMoves and getState methods. methods. These can be called by an interface program which will use them to support TCECP (appendix B), acting as an intermediary to allow the engine to be driven by the user interface.
3.4 Design Designing ing the 3D Inter Interfac facee The main focus of this project is the creation of the game of Time Chess, and an engine to allow it to be played by human and machine players. In order for the game game to be play playab able le by huma humans ns,, some some form form of User User Inte Interf rfac acee is requi require red. d. Howev However er,, intuitive user interaction and a large game-play feature set were not required by
25
Figure Figure 3.3: UML Class Diagram showing showing an overview of the Time Chess Engine structure the project project aims or proposal, and were considered considered to be low priority goals. The design of the 3D interface is functional, and meets the requirements.
3.4.1 3.4.1 Piece Piece Shapes Shapes The piece shapes had to be recognisable as their respective pieces, but there was also a motivation to keep them simple, with low polygon counts, so that in complex scenarios with large numbers of pieces the program performance would not suffer. The final piece designs were inspired by real world chess sets designed in the ‘minimalist’ style, with simple geometric shapes.
26
3.4. 3.4.22 Boar Boards ds Because several boards would be stacked on top of one another, it was important that that it be possib possible le to see throug through h them. them. The possib possibili ility ty of a semisemi-tra transp nspare arent nt board board was considered, but it caused performance issues and could not easily be clicked through. For these reasons it was decided that the boards would be represented
with simple white gridlines on the borders between squares. This loses the marking of black and white squares, but in Time Chess this is made less important by the the more more vari varied ed move moveme ment nt that that the the piec pieces es are are capa capabl blee of. of. For For examp example le Time Time Bish Bish-ops ops are are not not guar guaran ante teed ed to stay stay on the the same same colo colour ur of squa square re in the the way way that that regu regula larr bishops are.
27
28
Chapter 4
Implementation 4.1 Technolog echnologyy Choices Choices 4.1.1 4.1.1 Wh Whyy Python Python?? Python Python is an interp interpret reted, ed, genera general-p l-purp urpose ose highhigh-lev level el progra programmi mming ng languag language. e. I decided to use it in this project for a number of reasons. Because it is high-level, interpreted, and
Python is well suited to the project.
dynamically typed, Python is well suited to a ‘rapid prototyping’ style of development, with large numbers of small, quick development-testing cycles. This suits my need needs, s, beca becaus usee it must must be possi possibl blee to quic quickl klyy chan change ge the the worki workings ngs of the the game game to experiment and test new game rules. The standard library of Python is extensive, and there is a large community of
third third party modules providing providing all sorts of extra functionality functionality.. This is useful because it keeps the possibility of extra features open. For example, if I want to add func functi tion onali ality ty to play play Time Time Ch Ches esss over over a networ networkk late later, r, I know know that that ther theree are are a wide wide variety of modules to ease network communications in the standard library, providing good support for a number of protocols, including HTTP, XML-RPC, Telnet etc. There are also lower-level networking and data processing modules like socket, ssl and json which would make it easy to design my own. The same is
29
true for other areas of expansion like display, interaction, data storage etc; There are modules for almost anything I’d be likely to need.
4.1.2 4.1.2 Why Nu NumPy mPy?? I decided to use NumPy to store the game state. state. NumPy NumPy is a module for for Python which allows the creation of large, multi-dimensional arrays and matrices, and includes a large library of high-level mathematical functions to operate on these arrays. I made this decision for several reasons. potential ially ly veryimp very import ortant ant for for an applic applicati ation on like like this, this, and Python Python,, being being Speed is potent an interpreted language, is not particularly fast. The NumPy module is written in native C code and runs very quickly (Cai, Langtangen & Moe 2005). Elegance is made possible by closely corresponding metaphors. A game of chess
in wh whic ich h time time is a vali valid d dime dimens nsio ion n of moti motion on,, tran transl slat ates es very very neat neatly ly into into a 3D arra arrayy of chess pieces. The wide array of high level functions NumPy provides for handling 3D arrays is likely to contain many direct analogues to operations one may want to perform on a Time Chess game.
4.1.3 4.1.3 Wh Whyy VPytho VPython? n? The visual module module provides Python Python with a simple simple way to make make 3D graphics. I chose originally to use it for the visualisations used to help me imagine the rules of Time Chess, and decided that it would be well suited to the task of making a full 3D Time Chess GUI. I feel that it is well suited to the task for the following reasons: the modu module le’’s main main sell selling ing poin points ts.. Its Its tagtag-li line ne is “ 3D programSimplicity is one of the ming for ordinary mortals”, and it was designed to allow students of physics with
no prior knowledge of programming to write 3D physics simulation and demonstrati stration on progra programs ms (Scher (Scherer er,, Dubois Dubois & Sherwoo Sherwood d 2000) 2000).. I am simply simply attemp attemptin tingg to
30
represent the game state in a clear way, and to allow a user to interact with it, so this simplicity helps to avoid unnecessary complications. Features like variable opacity, complex lighting, pixel shader enhanced material
effects etc. are available if required, but set to sensible defaults to allow them to be ignored. important feature. feature. It doesn’t doesn’t make sense to lose Cross-platform Cross-platform support is an important the benefits of using a cross-platform language by binding to a single platform 3D library.
4.2 Impleme Implementing nting The Time Chess Chess Engine Engine This section covers two levels of detail. One is the broad overview to give a feel of the structure of the software, and the other is specific and quite detailed description of the workings of the program wherever it is doing something particularly complicated or interesting.
4.2.1 Implemen Implementatio tation n Descripti Description on If the whole system is a form of Model View Controller, then the engine plays the part of the model and the controller, with the interface playing the part of the view. 4.2. 4.2.1. 1.11 Th Thee Pos Object
objectss repres represent ent positi positions ons in the game. game. They have have three three coordi coordinat nates, es, x, y and Pos object t.
They can be initialised either either by giving these these coordinates coordinates separately, separately, or in the
form of Time Chess Position Notation (see section 3.2.3). 4.2. 4.2.1. 1.22 Th Thee Piece Object Piece is a parent class for the subclasses Pawn, Rook, Knight, Bishop, Queen and King. Objects of these classes represent pieces, but more specifically they repre-
31
sent a specific instance instance of a piece in a game. For example, example, the White King is one piece in the game, but is represented by several King objects, one for each turn in which the King exists. exists. If the King doesn’t doesn’t move, there might might be King objects at and so on. on. Two Piece object objectss repres represent ent the same same in-gam in-gamee piece piece e1t0, e1t1, e1t2 and if they share the same pieceId attribute. The Piece objects representing one ingame game piec piecee form form a ‘line ‘lineag age’ e’ , with with the the same same pieceId attributes attributes and sequential sequential age attributes. 4.2. 4.2.1. 1.33 The Game Object
Within the MVC structure, the Game is the model. model. It is effectively effectively a data strucstructure class, mostly concerned with storing the state of the board in a game of Time Ches Ch ess. s. It It inher inherit itss from from a Nu NumP mPyy arra arrayy obje object ct,, and and can can be thou though ghtt of as a thin thin wrap wrap-per around a three-dimensional array of Piece objects. A major function of this wrapper is to allow the array to be indexed into using Pos objects, but it also provides some extra functionality for finding sets of pieces that meet certain criteria. 4.2. 4.2.1. 1.4 4 Th Thee TimeChessEngine Object
The TimeChessEngine object plays the role of the controller in the MVC architectur tecture. e. It conta contains ins a Game object, and manipulates it in accordance with the rules of Time Chess as the game progresses. It handles commands from the view mostly using the attemptMove method, through which the view can relay intended tended moves moves from from the user. user. The TimeChessEngine is respons responsibl iblee for for calcul calculati ating ng if move movess are are lega legal, l, andworkin andworkingg thro throug ugh h thei theirr rami ramific ficat atio ions ns on the the stat statee of the the Game object.
4.2.2 4.2.2 How How it works works 4.2.2. 4.2.2.11 Overvie Overview w
When the program is started, a new TimeChessEngine object object is created. created. It initialises tialises itself, making a fresh Game object with the board in its starting position.
32
When attemptMove is called with a Move, the system first checks whether the give given n move move is lega legall acco accord rdingto ingto the the rules rules of Time Time Ch Ches ess. s. If it is ille illega gal, l, attemptMove retu returns rns a fals falsee Result and and conc conclu lude des. s. If the the move move is lega legal, l, it is carr carrie ied d out. out. A move move in the present simply simply moves a piece on the board in the current turn. turn. A move to the past makes an instance of the moved piece at the destination and propagate gatess the the chan change gess up to the the pres presen ent. t. A move move into into the the futu future re adds adds an entr entryy into into the the which stores ‘in transit’ transit’ pieces. Once the move has been carried futureQueue, which out, the futureQueue is checked for legality (since the move may have rendered some of the moves illegal), and any travellers due to arrive on the board this turn are placed on the board. board. The system then then checks to see if the turn resulted resulted in checkmate. If it did, the game is over, but if it didn’t, the turn is incremented, the contents of this turn’s layer are propagated up to the next layer, and the system waits until attemptMove is called again, for the other side to make a turn. 4.2.2.2 4.2.2.2 Implemen Implementing ting Forward Forward Time Time Travel Travel
The original design was that movements into the future would simply involve removing the piece from its starting location and placing it in its finishing location. However, this turned out to be insufficient for a few reasons, most important of which is the Lost in Time Rule (section (section A.4.2). Because Because the legality legality of a forward time travelling move cannot be known for sure at the time the move is declared, placing the new piece directly at its target position on the board would be premature, since the move may be rendered illegal in the intervening turns. The solution chosen to deal with this was to maintain a collection containing all of the pieces which are attempting to travel forwards in time. When the part of the turn sequence comes for pieces to come out of time travel, this collection is examined, and any pieces which are due to come out of time travel at this turn must first verify that their move has been legal, and if it is, they appear, and if it isn’t, they become Lost in Time. A future move can become invalid in a few different ways. The first occurs
33
when the piece making making the move is captured captured in the past. The piece was taken taken before it could make the move into the future, so the future move never happened. This is checked checked for by finding the immediate predecess predecessor or to the piece in the futureQueue (see section 4.2.2.3 for more about finding predecessors). If the piec piecee has has been been tak taken, en, it will will not not be poss possib ible le to find find its its paren parent, t, so the the syst system em know knowss that that the the time time trav travel elli ling ng piec piecee has has been been kill killed ed in the the past past and and neve neverr got got to mak make the the move into the future. The second way in which a move stored in the futureQueue may become invalid is blocking (section A.3.1), which occurs when pieces are positioned in between the piece and its destination. destination. This is checked checked for by finding the parent of the the trav travell ellin ingg piec piece, e, and and ensu ensuri ring ng that that the the move move it is maki making ng is stil stilll retu return rned ed by the the parent’s getMoves object. If a piece has moved in the way of the move, getMoves will no longer list it as a possible move (see section 4.2.2.4 for more about finding possible moves for a piece). Pawns have a special case, because they can move forwards, but can only capture diagonally diagonally.. So if a Pawn moves diagonall diagonallyy into the future, in order for the move to be legal, there must be an opposing piece there to capture, or the Pawn would not have been able to make the diagonal move. 4.2.2.3 Implementing Implementing Backward Time Travel
Implementing backwards time travelling moves proved to be an especially challenging task, which required substantial refactoring. The original design for the Game object was an array of signed integers, with each each intege integerr repres represent enting ingaa piece. piece. Zero Zero denoti denoting ng an empty empty space, space, positi positive ve number numberss for for wh whit itee piec pieces es and negat negativ ivee numb number erss for for blac blackk piec pieces es,, with with each each piec piecee type type bein beingg its its own own numbe number. r. This had had the the adva advant ntag agee of keepi eeping ng the the arra arrayy smal smalll in memo memory ry and and fast to copy, but proved too simple. The difficulty occurs when the system tries to deal with taking pieces back in time. The rules state that when a piece is taken in the past, all occurrences of the piece between the time it is taken and the present
34
are are remo remove ved d from from the the game game (sec (secti tion on A.5. A.5.1) 1).. The The prob proble lem m then then aris arises es of how how to find find all all the the inst instan ance cess to remo remove ve from from the the game game.. If the the Blac Blackk Quee Queen n is tak taken in the the past past,, that piece is represented by the integer -5, so it’s a simple matter of changing all occurrences of -5 in the array between the time of capture and the present to 0. However, if the White Knight is taken, represented by the integer 3, removing all 3s from the required turns will remove both white knights, not just the one that
has been captured. One solution to this issue that was considered was using separate integers for each specific specific piece, piece, like a piece ID number. White White Pawns could be 1 to 8, Black Black Pawns –1 to –8, Rooks as 10, 11, –10 and –11, Knights as 20, 21, –20 and –21, and so on. However, there was another flaw with using simple integers. When a piece travels back in time, it then sits still in the intervening turns as a braindead piece (see section A.5.2). Thus in the turns between the start and end of the backwards move, there may be more than one instance of the same piece - the original as it was on the first pass, and the older time traveller copy making the second pass. pass. If that piece is subsequently subsequently captured captured at a point in its timeline timeline betw betwee een n the the time timess of the the two two copi copies es,, only only the the olde olderr copy copy shou should ld be dest destro roye yed. d. Bu Butt a simple integer identifier for the pieces gives no way of knowing which piece is the original, and which the older time travelling copy. Because of these limitations, it was decided to store an object in the array the Piece obje object ct - rath rather er than than a simp simple le inte intege ger. r.,, and repr repres esen entt empt emptyy spac spaces esPiece object objectss have have a pieceId attrib attribute ute that that keeps keeps track track of which which in-gam in-gamee piece piece they they reprepresent, and an age attribute, keeping track of how many turns they have directly lived through through at that point. When the turn changes, changes, the makeChild method is called for every Piece in the old turn, which produces a ‘child’ Piece with the same pieceId as the parent, and an age of the parent’s age incremented incremented by 1. The resulting Pieces populate the new turn. Using Using this system, the proper proper remova movall of inst instan ance cess from from the the boar board d is simp simple le - just just remo remove ve everypiec everypiecee with with the the same same form of pieceId as the captured piece, and equal or greater age. In this way any form
35
convoluted time travel situation can occur, and if a piece is taken, all instances of it furt furthe herr on in its its time timeli line ne are are dest destro roye yed. d. Th This is is done done by the the eraseLineageFrom method. 4.2.2.4 4.2.2.4 Finding Finding Possib Possible le Moves Moves for a Piece Piece
Every instance of a subclass of Piece knows its type, the board it is on, and its positi position on on that that board. board. The getMoves meth method od retu return rnss a list list of move movess that that may may be legal for that Piece at the current time. However, a move returned by getMoves may still be illegal because of factors like check. Each subclass of Piece implements their own getMoves method, reflecting how the pieces move differently. For a piece type like Knight, getMoves simply returns moves to all of the positions a knight’s move away which are on the board and don’t contain any pieces of its own colour. The movements of the Rook, Bishop and Queen follow the same general pattern, involving moves being available in a particular direction until the way is blocked blocked by the edge of the board or by another piece. Rooks do this in the compass directions, directions, Bishops Bishops do it diagonally, diagonally, and Queens do both. Because Because of these similarities, movement for these pieces can be generalised out. This is done with the getMovesInDirections meth method od,, wh whic ich h is give given n a list list of dire direct ctio ions ns as 3D vecvectors tors,, and goes goes thro through ugh each each one addi adding ng lega legall move movess for for as long long as the the path path rema remain inss clear. 4.2.2.5 4.2.2.5 Pawn Pawn Promotion Promotion
If a Pawn reaches the far side of the board, it is ‘promoted’ and becomes a Queen. This This is elegan elegantly tly implem implement ented ed using using the id/age id/age system system descri described bed in sectio section n 4.2.2. 4.2.2.3. 3. When makeChild is called on a Pawn object to produce the next instance of the in-game piece, the Pawn first checks to see if it is on the first or last ranks of the boar board d (sinc (sincee Pawnscan Pawnscan never never move move back backwa ward rds, s, the the piec piecee does does notneed to ensu ensure re it has reach reached ed the opposite end end of the the boar board, d, beca becaus usee a Pawn Pawn can can neve neverr reac reach h its its own own
36
end). If the Pawn is at the end of the board, instead of creating a new Pawn object with the same pieceId and incremented age, it creates a Queen object instead. Thee nice Th nice thin thingg abou aboutt this this is that that the the Queen obje object ct has has the the pieceId attrib attribute ute of the Pawn it once was, so if the Pawn is captured in the past, before it was promoted to
a Quee Queen, n, the the Quee Queen n is stil stilll dest destro roye yed d in acco accord rdan ance ce with with rule ruless desc descri ribe bed d in sect sectio ion n A.5.1. 4.2.2.6 4.2.2.6 Checking Checking for Check
The state of check occurs when an opposing piece is in a position where it can attack the King (see section A.6). The TimeChessEngine object tests for the state of check with the isInCheck method. method. This method method works by finding all moves available to the enemy and checking whether and of those positions contain an instance of the King. In many many Chess Chess implem implement entati ations ons,, check check is tested testedmor moree quickl quicklyy by lookin lookingg ‘back ‘back-wards’, starting from the position of the King and looking for knights in the positions one knight’s-move away, pawns one pawn’s-move away and so on. This is faster because there is only one King, and many pieces that could attack it. However in Time Chess this this is not necessarily necessarily the case. Because Because the king can be attacked in the current turn or any turn before it, there may be a large number of positions which, if attackable, would cause check. Since the only pieces that can threaten the king are those in the current turn (since pieces may only be commanded from the present), there are at most 16 pieces which could threaten the king, and generally fewer, since check is more likely to happen towards the end of the game when many pieces have been taken. 4.2.2.7 4.2.2.7 Checking Checking for Checkmate Checkmate
The state of Checkmate occurs when a side has no available moves that would not result in their king being in check. Because of the complex nature of Time Chess, we could find to way to detect
37
if a move ends in check, other than simply making the move and then checking to see if the move ended in check. This means that in order to detect checkmate, you must check every move available, to be sure that every one of them ends in check. check. The moveEndsInCheck method returns whether or not the given move ends ends in chec check. k. To achi achiev evee this this,, it first first mak makes a deep deep copy copy of the the TimeChessEngine object. A ‘deep copy’ of a composite object is a copy not only of the object, but of the objects it contains, so a deep copy of the TimeChessEngine object also copies the Game object and its contained Piece objects, making a full copy of the game stat state. e. Th Thee copy copy is give given n the the move move to exec execut utee by the the attemptMove method method,, and the isInCheck method is then called to see if the copied game is in check.
Performance moveEndsInChec k on every The isInCheckmate method method must must call call moveEndsInCheck every move move avai availl-
able, to ensure that they all end in check, and thus that the game is in checkmate. This means that detecting checkmate is the most expensive operation in the program by a substantial margin. Some measures were taken to improve its performance. Firstly, Firstly, not all possible possible moves must be searched. searched. As soon as a move is found which does not end in check, there is no checkmate, so the search can stop there. Thismeansthat isInCheckmate runsquickly runsquickly for for most most non-ch non-check eckmat matee game game states states,, because as soon as it finds a move that doesn’t end it checkmate, it stops. Secondly, the number of possible moves that need to be checked can be reduced by 33% or more by eliminating future moves for everything other than the King King.. A move move into into the the futur futuree effec effecti tive vely ly remo remove vess a piec piecee from from the the boar board d for for a numnumber of turns, so no move into the future (by a piece that is not the king) can ever result in a checked king no longer being in check.
38
4.3 Impleme Implementing nting the 3D Interface Interface 4.3.1 4.3.1 Implement Implementation ation Descript Description ion 4.3. 4.3.1. 1.11 Th Thee Piece Object
The Piece object represents a 3D object that looks like a Chess piece. It gets most of its functi functiona onalit lityy by inheri inheritin tingg from from theVPy the VPytho thon n frame object object,, which which is design designed ed as a cont contai aine nerr for for othe otherr VPyt VPytho hon n 3D obje object cts. s. The frame hold holdss all all of the the obje object ctss totogether in one frame of reference, effectively grouping them into a more complex 3D object. For example, a Piece representing a pawn groups together a cone ob ject and a sphere object, which together form the shape of a pawn. 4.3. 4.3.1. 1.22 Th Thee Ghost Object
The Ghost object object repres represent entss ‘ghos ‘ghost’ t’ pieces pieces,, which which are semitr semitransp anspare arent nt pieces pieces used used to indic indicat atee posi positi tion onss wh wher eree piec pieces es will will come come out out of time time trav travel el in the the futu future re.. Th They ey inherit from Piece and their only difference is a lower opacity. 4.3. 4.3.1. 1.33 The Layer Object
The Layer object object represents the state of the board during one turn of the Time Chess game. game. It also inherits inherits from from frame, and groups together some curve ob jects, which show as white gridlines separating the positions on the board, and the Piece objects on the board. 4.3. 4.3.1. 1.4 4 Th Thee Controller Object
The Controller object objectis is respon responsib sible le for for convey conveying ing user user input input to thegam the gamee engine, engine, and updating the 3D scene to show the results.
39
4.3.2 4.3.2 How How it Works orks 4.3.2. 4.3.2.11 Overvie Overview w
When the program is started, a controller object is created. The Controller ob ject initialises itself and opens a connection to a program which is started by a command given on the command line. The intention is for this program to be an engine engine or other other progra program m that that support supportss TCECP TCECP throug through h stdin and stdout. In this this implementati implementation on this is TCECPInterface.py,whichrunsa TimeChessEngine ob ject, supplying it with commands it receives, and returning the results. The Controller then then ente enters rs a game game loop loop,, in wh whic ich h it hand handle less mous mousee and and keyeyboard board input input from from theuse the user. r. When When intera interacti ction on with with theeng the engine ine is requir required, ed, the send, recv and communicate methods are used to send and receive TCECP messages.
The showLayer and hideLayer methods are used to create and hide layers of the board, and the makeHighlight and clearHighlights methods are used to create and destroy possible move highlights. 4.3.2.2 4.3.2.2 Creating Creating Pieces Pieces
Because Piece objects have no behaviour determined by their type, it didn’t make make sense to have a large number of subclasses, subclasses, one for each piece type. There is only one Piece class, class, which can have the appearance appearance of any piece type. This is achieved by a data structure that stores the attributes of the 3D objects that make up each piece type, and a generalised method to build them, which makes use of a lot of Python’s more advanced features, such as tuple unpacking, module dictionaries and keyword argument unpacking. The geometries data structure is a Python dictionary (like a hash table) which uses piece type characters (‘b’ for bish bishop op,, ‘r’ ‘r’ for for rook rook etc) etc) as the the inde indexx to stor storee a list list of entr entrie iess wh whic ich h form form the the inst instru rucctions to make a specific simple geometric object. This is best demonstrated with examples. examples. In figure 4.1, we can see that the pawn piece piece type (represented (represented by the character ‘p’) is made up of two pieces of geometry; The first is a cone positioned 40
geometries = { "p":[ "p" :[ ("cone" "cone", , ("sphere" "sphere", , ],
{"pos" "pos":( :(0 0,0,0), "axis" "axis":( :(0 0,0,.5 .5), ), "radius" "radius": :.3 .3}), }), {"pos" "pos":( :(0 0,0,.5 .5), ), "radius" "radius": :.15 .15}) })
... "k":[ "k" :[ ("cylinder" "cylinder", , {"pos" "pos":( :(0 0,0,0), "axis" "axis":( :(0 0,0,.7 .7), ), "radius" "radius": :.2 .2} } ), ("box" "box", , {"pos" "pos":( :(0 0,0,.85 .85), ), "width" "width": :0.1 0.1, , "height" "height": :0.1 0.1, , "length": "length" :.3 .3, , "axis" "axis":( :(1 1,0,0)}), ("box" "box", , {"pos" "pos":( :(0 0,0,.85 .85), ), "width" "width": :0.1 0.1, , "height" "height": :0.1 0.1, , "length": "length" :.3 .3, , "axis" "axis":( :(0 0,0,1)}), ] } for prim, prim, args in geometries[ptype]:
visual. visual.__dict__[prim](frame __dict__[prim](frame= =self self, , color color= =col,** col,**args) args)
Figure 4.1: System to generate 3D objects from stored geometry information at the origin, with an axis of 0.5 units straight up, and a radius of 0.3 units, and the the seco second nd is a sphere loca locate ted d 0.5 0.5 unit unitss up from from the the orig origin in (at (at the the top top of the the cone cone), ), with a radius of 0.15 units. The last two lines of figure 4.1 construct the required geometry objects for the given piece type (stored in the ptype variable). variable). The for loop iterates over the list returned by geometries[ptype], and unpacks each item into the variables prim and args. In the the case case of a pawn, pawn, wh wher eree ptype='p', the first iteration of the loop would occur with prim="cone" and args={"pos":(0,0,0), Inside the loop, loop, the ‘bu ‘built iltin in’’ dictio dictionary nary of the "axis":(0,0,.5), "axis":(0,0,.5), "radius":.3} "radius":.3}. Inside module le is acce access ssed ed by the the __dict__ attribute. attribute. Indexing Indexing into the module’ module’ss visual modu with the the key "cone" return returnss the constr construct uctor or for the cone object, object, which which __dict__ with is then then called called.. The ** before before the args argume argument nt inform informss Python Python that that args isadiction tionary ary wh whic ich h is to be unpac unpackked into into keywo eyword rd argum argumen ents ts.. So for for the the first first iter iterat atio ion n of the loop for a pawn, the line visual.__dict__[prim](frame=self visual.__dict__[prim](frame=self, , color=col,**args) color=col,**args)
is effectively translated into cone(frame=self, color=col, pos=(0,0,0), axis=(0,0,.5), radius=.3)
41
This sort of dynamic introspection is one of the things that makes Python such a powerful language. 4.3.2.3 4.3.2.3 Displayin Displayingg Layers Layers
The process of using the TCECP interface to request the contents of a layer from theeng the engine ine andthe and then n constr construct ucting ing 3D object objectss from from that that data data is time time consum consuming ing,, and shoul should d not not be done done more more ofte often n than than nece necess ssary ary.. So, So, Layer object objectss have have a turnMade attr attrib ibut ute, e, wh whic ich h stor stores es the the turn turn the the game game was at wh when en the the Layer was made. made. When the Controller requires a layer to be displayed, it calls the showLayer method, which first checks the existing Layer object for that layer to see if it was made this turn and thus is up to date. If the layer is out of date, buildLayer is called to create a new Layer object with data fetched from the engine. The hideLayer method does not destroy the Layer object, but simply sets its visible attribute attribute to False. The visible attr attrib ibut utee is an attr attrib ibut utee of the the VPyt VPytho hon n frame object, which causes the object to disappear from the 3D scene, but stay in
memory. If showLayer is called and an existing Layer object is up to date, it is simple set to be visible, and no new layer must be built. This effectively works as a cache of 3D objects, improving performance.
4.4 Extra Extra Featu Features res 4.4. 4.4.11
Ster Stereo eo
In the course of a game of Time Chess, complex 3D configurations of pieces must be analysed. This can become difficult when there are many overlapping layers of varying opacity, because the user has no sense of depth perception. By rendering two images of the scene as seen from slightly offset camera positions, and mapping the right one to the red channel and the left to the blue channel nel (figu (figure re 4.3), 4.3), a ster stereo eosc scop opic ic 3D effec effectt can can be prod produc uced ed for for user userss weari wearing ng red/bl red/blue ue filter glasses (figure 4.4) (Konrad & Halle 2007).
42
Figure 4.2: Complex, densely layered scenes can be difficult to understand Since user preference will vary, and not all users will have red/blue glasses available to them, this feature can be toggled on and off with the ‘ s’ key.
43
Figure Figure 4.3: 4.3: Red/Blu Red/Bluee Stere Stereo o can enormo enormousl uslyy improv improvee game game immers immersion ion and ease ease of use
Figure 4.4: Red/Blue Filter Glasses used for stereo viewing
44
Chapter 5
Evaluation 5.1 Difficul Difficulty ty for for Compu Computer terss 5.1.1 Branching Branching Factor Factor One of the factors that makes a game difficult for move-space searching AI algorithms is a high branching factor . Since one of the aims of Time Chess was to have a high branching factor, this will be evaluated. Chess has a branching branching factor of about 35 (Laramée 2000). 2000). This number number was calculated by taking a large corpus of good quality games, calculating the number of legal moves available available at each point of the game, and taking a mean. We don’t have a large corpus of good quality games, because there are as yet no good Time Chess players. players. To obtain some data to give a rough idea of a branching branching factor, factor, a program was written to play games by picking moves randomly from the set of legal moves for each turn. The result of ten such games is shown in figure 5.1. As expected, the branching factor falls as the game goes on, as pieces are taken. I believe this is not a particularly good representation of a real human game, because the random choice loses a lot of pieces in time, by jumping pieces blindly into the future with no care for clearing a path for them. Many, possibly most future moves, while perfectly legal, are effectively suicide because there is no easy way to ensure that the move remains legal until the piece reappears at its desti-
45
Figure 5.1: Mean branching factors for ten games of random Time Chess nation. This is likely to have led the branching factor to fall more rapidly than it normally would, as pieces like Queens, which contribute a lot of options, are for that very reason highly vulnerable to being Lost in Time by random movement choice. Noneth Nonethele eless, ss, themea the mean n branch branching ing factor factorove overal ralll was68, was 68, which which is appro approxim ximate ately ly twic twicee the the bran branch chin ingg fact factor or of Ch Ches ess. s. Th This is is high high enou enough gh for for Time Time Ch Ches esss to be conconsidered to have achieved its aims with regard to branching factor.
5.2 5.2 Unit nit Tests ests The Python programming language provides good support for unit tests in the standard library, through the unittest module (O’boyle, Tenderholt & Langner 2008). 2008). Unit tests tests were written for major features features and edge cases, cases, and used for regression testing when new feature were implemented.
46
5.3 User User Acceptanc Acceptancee Testing esting Late in the development process, the alpha release level software was tested by a number of third party volunteer software testers, of varying levels of experience in computer use and Chess. During this testing a number of bugs were discovered and corrected.
5.3.1 The King becoming becoming Lost in Time A bug that was discovered during later stages of play testing was that of losing the King in time. The possibility of a King becoming Lost in Time had been briefly considered, but dismissed as impossible, since a King can move at most one turn forwards in time time.. When When a piec piecee move movess forwa forward rd in time time by one one turn turn,, it disa disapp ppea ears rs,, the the oppo opposi sing ng side has a move, and then the time travelling piece reappears at its destination. Blocking is thus impossible, because any opposing piece attempting to block will simply simply be taken taken by the reappearing reappearing piece. A move forward of one turn doesn’t doesn’t move move ‘thr ‘throug ough h’ any any inte interm rmed edia iate te spac spaces es,, so ther theree are are no spac spaces es wh whic ich h can can be fille filled d by an opposing piece attempting to block it. However, this thinking was incomplete. While it’s true that it’s impossible to caus causee a King King to beco become me Lost Lost in Time Time by bloc blocki king ng it, it, that that’’s not not the the only only way way a piec piecee can can beco become me Lost Lost in Time Time.. A piec piecee is Lost Lost in Time Time if a forwa forward rd time time trav travel elli ling ng move move it made made is rend render ered ed ille illega gall befo before re it is comp comple lete te.. So if a piec piecee move movess forwa forward rd in time time to a position which is already occupied with a piece of the same colour, the time travelling piece becomes Lost in Time, because it’s not legal to take a piece of the same colour. With a King this almost al most certainly has to be done deliberately, since the only way it could happen is if the King is moved one forward in time and one position in space, to a space directly ‘above’ an existing piece of the same colour. It should be clear to the player making the move that as soon as the opposition has its turn,
47
the the piec piecee the the King King is ‘over over’’ will will stil stilll be ther theree wh when en the the King King trie triess to reapp reappea ear, r, wh whic ich h makes the move illegal and renders the King Lost in Time. This move is so clearly stupid that I had never thought to try it. There’s a lesson here about the benefits of play testing. So, when the play tester made this stupid move, their King became Lost in Time. But because Lost in Time pieces are not ‘captured’ ‘captured’,, just gone, the system did not detect any problems. The King was not on the board, but it wasn’t checkmate mated, d, so the the game game cont contin inue ued. d. Not Not only only was was the the King King not chec checkm kmat ated ed,, it was now un-checkable from that turn forwards, because it was no longer on the board! It was not a stupid move at all, in fact it was probably the best move in the game, rendering rendering the King almost completely completely un-checkable un-checkable!¹ !¹ Clearly Clearly this was a gamebreaking loophole of the kind I decided not to allow in section 3.2.1.3 I examined several possible solutions. 1. Don’t allow the King to move to positions directly directly above pieces of the same colour. The problem with this is that it is possible for this move to not result in the King becoming lost in time, since the piece can be captured in the intervening turn, turn, making making the King’ King’ss move move legal. legal. This This is extreme extremely ly unlik unlikely ely,, since since not only would the player need to decide to take the very risky move of moving their King forwards in time to directly above a piece of the same colour, but thei theirr oppo oppone nent nt woul would d have have to then then deci decide de to capt captur uree that that piec piecee to mak make the the move legal again. again. But however however unlikely unlikely this is, it is legal, so declaring the all moves to directly above pieces of the same colour illegal would reduce the branching factor of the game unnecessarily, which goes against section 3.2.1.2. 2. Make Make the King capture any piece it lands on when reappearing from time travel, even pieces of the same colour. ¹It’ ¹It’s worth worth noting noting that that the King King was not comple completel telyy invuln invulnera erable ble,, as it could could theore theoretic ticall allyy still still be checked in the past before it made the move that caused it to become Lost in Time.
48
This would be very simple to implement, and would fix the problem, but it has a wider reach than just making the King never be lost in time. It introduces a strange precedent of deliberately taking your own pieces, which is inelegant and divergent from chess, going against section 3.2.1.1 3. State tate that that if a King King beco become mess lost lost in time time,, the the game game is lost lost by the the owne ownerr of the the King. This is the solution I chose. It keeps options open, and doesn’t change the rest of the game, but punishes players for deliberately causing their King to be Lost in Time.
49
5.3. 5.3.22 Surv Survey ey After using the software, testers were asked to rate their agreement with a series of statements, on a scale of 1 to 5. Numb Nu mber er
Meani Meaning ng
1
Strongly Disagree
2
Disagree
3
Neit Neithe herr agre agreee nor nor Disa Disagr gree ee
4
Agree
5
Strongly Agree
To what extent do you agree with the following statements? 1. I am a skilled Chess Chess player (here 1 means you never play Chess, 5 means you play in competitions) 2. I found the the concept of Time Chess confusing. 3. The Rules of Time Time Chess document helped me to understand the game 4. Playing the game on the computer helped helped me to understand the game 5. I feel that I now understand the game well 6. I found found the game game fun to play play 7. Playing Time Chess required more thought thought than playing Chess Chess 8. Playing Time Chess required a different kind of thought to playing Chess 9. The 3D interface interface was was easy to use 10. The 3D interface gave me all the the information I needed to make make decisions 11. The game was stable (it didn’t didn’t crash or have have many glitches) 12. The game game was responsiv responsivee
50
The results of the survey are shown in figure 5.2.
Figure 5.2: Mean Responses of the Survey Participants The mean self-assessed Chess skill of the testers was 2.7, meaning on average testers considered themselves ‘casual chess players’. players’. Time Chess does not seem to have been thought to be confusing, or at least people were not prepared to admit that they found found it confusing, averaging averaging 2.8 on that question. question. Playing Playing the game through the 3D interface was found to be more effective than reading the documentat mentation ion at teachi teaching ng tester testerss to unders understan tand d the rules. rules. Many Many test test partic participa ipants nts also also had discussed the nature of the game with the designer before testing, which is likely to have biased those results. The combination of rules documentation and play playin ingg the the game game was deem deemed ed succ succes essf sful ul in helpi helping ng user userss to under underst stan and d the the game game,, with testers on average agreeing that they now understand Time Chess. The game was agreed to be fun on average, with no individuals rating lower than 3. Testers strongly agreed, with an average of 4.4, that Time Chess required more thought than ordinary Chess, and also agreed, though less strongly with an average of 3.6, that Time Chess required a different kind of thinking to regular Chess. 51
Thee inte Th interf rfac acee was was agre agreed ed to be easy easy to use use (mea (mean n rati rating ng of 3.6) 3.6),, but but not not thou though ghtt to provid providee all the inform informati ation on useful useful to making making Time Time Chess Chess decisi decisions ons (mean (mean rating rating of 2.4). Follow-up questions about this failing found that testers would have liked more more fine fine cont contro roll over over exac exactl tlyy wh whic ich h turns turns are are view viewed ed at any any time time,, rath rather er than than just just seeing which which turns can be affected affected by a piece’s piece’s movement. It had been assumed that unless a player wanted to move a piece to a turn in the past, they would not want to see that turn, but this turned out not to always be the case. The interf interface acewas was agreed agreed to be stable stable(th (there ere were were no unexpec unexpected tedcra crashe shess during during testing), rated on average at 3.7, and acceptably responsive (mean rating 2.9). The responsiveness score is likely to be caused by the lag in detecting cases of checkmate. Running cross correlations between the questions, we find a lot of things that are fairly obvious; More skilled chess players are less likely to find Time Chess confusing, more likely to say they understand it, and more likely to find it fun. So Time Chess appeals more to skilled Chess players. Also, better Chess players are more likely to have gained more understanding from reading the rules, relative to playing the game. It seems skilled players were more more able able to unders understan tand d the writte written n rules, rules, and people people who played played less less Chess Chess learnt learnt better from the hands on experience of playing the game. There The re’’s a very strong strong negati negative ve correl correlati ation on betwee between n finding finding Time Time Chess Chess confus confus-ing ing and and findi finding ng it fun. fun. Peopl eoplee do not seem seem to enjoy enjoy being being confus confused. ed. This This was a little little unexp unexpec ecte ted, d, beca because use the the comp comple lexi xity ty of Time Time Ch Ches esss is one of its its sell sellin ingg poin points ts.. It is possible that those who enjoy being confused are less likely to report their experiences as being confusing, because it is more likely to be remembered as a learning experience. It’s worth noting that the sample size of this survey is too small to make statistically significant claims, but as far as conclusions can be drawn from this data, Time Chess seems to have broadly achieved its aims.
52
5.4 5.4 Requ Requir irem emen ents ts The requirements for the project are specified in section 3.3.1, and nothing would be gained by repeating them them all here with check-marks check-marks next to them. All of the requirements specified were met, and some extra features (like those mentioned in section 4.4) we also added. From a requirements perspective, the project was a success.
53
54
Chapter 6
Summary 6.1 6.1 Fur urth ther er Work ork The obvious and intended follow-up work to this project, as stated in the project aims (section 1.1), is the development of an Artificial Intelligence solution able to play Time Chess to a good standard. However this is not the only opportunity for expansion on this work that presents itself.
6.1.1 Interfac Interfacee Improvem Improvements ents The 3D interface broadly met its stated aims, but the survey indicated that testers were were not not enti entire rely ly happ happyy with with the the leve levell of info inform rmat atio ion n it prov provid ided ed,, so ther theree is room room for improvement to the interface in future work.
6.1.2 Accurate Accurate Complexit Complexityy Estimates Estimates The calculation of the mathematical complexity of games like Chess and Go has had articles and papers dedicated to it (Storer 1983, 1983, Crâsmaru 1999). This document touched briefly on the subject of calculating some complexity measures for Time Chess Chess in section section 5.1.1, but there there is a great deal more more work that that could be done done in making more accurate measurement of branching factor, as well as estimating the size of the game’s state-space and other complexity metrics.
55
6.1.3 Affective Affective Analysis Analysis Sinc Sincee one one of the the main main stat stated ed aims aims of Time Time Ch Ches esss as a game game was was to have have a high high cogcogniti nitive ve load load,, this this shou should ld be asse assess ssed ed in more more deta detail il than than time time andresour andresource cess allo allowe wed. d. Thee surve Th surveyy (sec (secti tion on 5.3.2 5.3.2)) ask asked test tester erss how how much much they they agre agreed ed with with the the stat statem emen ents ts “I found the concept of Time Chess confusing” and “Playing Time Chess required more thought than playing Chess”, and the responses suggested that playing Time Chess
was likely likely to have a high cognitive load. However However this approach is very limited. Self-reported affect information is known to be unreliable (Clark & Watson 1988), and even if this data is accurate it is very simple and one dimensional. The field of Affective Computing has a lot to offer here, in terms of the accuracy, detail, depth and volume of data that is achievable. One of the main fields of focus for current AC research is education (Tao & Tan 2005), a field in which assessing confusion and cognitive load are important goals, so fairly robust systems have already already been developed developed for that purpose (Ikehara (Ikehara & Crosby 2005). There is also substantial existing research into measuring the affect of test subjects playing educational games (Sykes 2006). Time Chess is not a particularly educational game game,, but but tech techni niqu ques es for for meas measuri uring ng affec affectt in a gami gaming ng indi indivi vidu dual al woul would d be read readil ilyy transferable to the task of measuring cognitive load in the mind of a Time Chess player. Information gathered from the interface, such as time taken for each move, number of pieces selected and examined before move selection, time spent ad justing views of the board, time spent inactive etc. could be examined as possible determinants of cognitive load, as could facial analysis techniques. By gaining clear, detailed, temporally and contextually indexed empirical data on the affect of people playing variants of Time Chess, the game can be optimised for mental challenge.
56
6.1.4 Persona Personall Reflection Reflectionss The idea of Time Chess occurred to the author at a young age, at a time when actual actually ly implem implement enting ing it was an unreac unreachab hable le goal. goal. Althou Although gh the origin original al idea idea was, in the course of its being refined and fleshed out into a full specification, found to be a logical impossibility, a working version of the rules could be devised which kept to the spirit of Time Chess. It is satisfying to have the skills and opportunity to finally realise an idea which has been harboured for almost a decade, and in the course of doing so to make both a fun game and what is hopefully a useful contribution to the field of AI research.
57
58
Bibliography Allis, L. (1994), Searching for solutions in games and artificial intelligence , Ponsen & Looijen. Cai, Cai, X., X., Langta Langtange ngen, n, H. & Moe, Moe, H. H. (2005) (2005),, ‘On ‘On the perform performanc ancee of the Python Python proprogramming language for serial and parallel scientific computations’, Scientific Programming 13(1), 31–56.
Clark, L. & Watson, D. (1988), ‘Mood and the mundane: Relations between daily life events and self-reported mood.’, mood.’, Journal of Personality and Social Psychology 54(2), 296.
Coles, L. S. (2002), ‘Computer chess: The drosophila of ai’. URL: http://www.drdobbs.com/high-performance http://www.drdobbs.com/high-performance-computing/184405 -computing/184405171 171
Crâsmaru, M. (1999), ‘On the complexity of Tsume-Go’, Lecture notes in computer science pp. 222–231.
GNU Project (n.d.), ‘GNU Chess SVN Repository’ Repositor y’. URL: http://svn.savannah.gnu.org/viewvc/trunk/src/?root=chess
Hilborn, R. (2004), ‘Sea gulls, butterflies, and grasshoppers: A brief history of the butterfly effect in nonlinear dynamics’, American Journal of Physics 72, 425. Ikehara, C. & Crosby, M. (2005), ‘Assessing cognitive load with physiological sensors’. Iqbal, A. (n.d.), ‘What Computer Chess Still Has to Teach Us’. 59
Konr Konrad ad,, J. & Halle Halle,, M. (200 (2007) 7),, ‘3‘3-D disp displa lays ys and and sign signal al proc proces essi sing ng’,’, Signal Signal Processin Processingg Magazine, IEEE 24(6), 97–111.
Laramée, F. D. (2000), ‘Chess Programming’. Nahin, P. & Nahin, P. (1994), Time machines, AIP Press. O’boyle, O’boyle, N., Tenderholt, enderholt, A. & Langner, K. (2008), ‘cclib: ‘cclib: A library for packageindependent computational chemistry algorithms’, Journal of computational chemistry 29(5), 839–845.
Paas, F., Tuovinen, J., Tabbers, H. & Van Gerven, P. (2003), ‘Cognitive load measurement as a means to advance cognitive load theory’, Educational psychologist 38(1), 63–71.
Pritchard, D. & Beasley, J. (2007), The Classified Encyclopedia of Chess Variants , Beasley. Scherer, D., Dubois, P. & Sherwood, B. (2000), ‘VPython: 3D interactive scientific graphics for students’, Computing Computing in Science & Engineering 2(5), 56–62. Shaffstall, J. (n.d.), ‘Temporal ‘Temporal Chess’. Chess’. URL: http://www.squidoo.com/temporalchess
Shannon, C. (1950), ‘XXII. Programming a computer for playing chess’, Philosophical Magazine (Series 7) 41(314), 256–275.
Stanford University (2008), ‘Stanford Encyclopedia of Philosophy on Time’. URL: http://plato.stanford.edu/entries/time/
Stone, R. (n.d.), ‘A Brief Study and Review of Chess and Go Artificial Intelligence’. Storer, J. (1983), ‘On the complexity of chess’, Journal of Computer and System Sciences 27(1), 77–100.
Syed, O. & Syed, A. (2003), ‘Arimaa-a new game designed to be difficult for computers’, International Computer Games Association Journal 26, 138–139. 60
Sykes, J. (2006), ‘Affective ‘Affective gaming: advancing the argument for game-based learning’, Affective and emotional aspects of human-computer human-computer interaction pp. 3–7. Tao, J. & Tan, T. (2005), ‘Affective computing: A review’, Affective Computing and Intelligent Intelligent Interaction pp. 981–995.
Van Gelder, A. (1987), ‘Efficient loop detection in Prolog using the tortoise-andhare technique’, The Journal of Logic Programming 4(1), 23–31.
61
62
Appendix A
The Rules of Time Chess For the purposes of this document, it is assumed that the reader is generally familiar with the rules of standard Chess. Because Time Chess is a ‘chess variant’, it shares a substantial part of its setup and rules with Chess.
A.1 Board and Pieces Time Time Ch Ches esss piec pieces es are are clos closel elyy relat related ed to Ch Ches esss piec pieces es,, and shar sharee thei theirr name names, s, symsymbols bols,, appe appear aran ance ces, s, and and much much of thei theirr beha behavi viou our. r. If an aspe aspect ct of a piec piecee is not spec spec-ified in this document, it may be assumed that it shares that aspect with its equivalent in Chess. Time Chess is conceptually played on a standard Chess board, and could be played using one or more physical Chess boards, however this would be impractical. tical. Time Chess is only practically practically played on a computer, computer, which will generally generally model the game as a three dimensional object which can be thought of as a stack of Chess boards. Each layer of the stack archaeologically represents a turn of the game, and the stack becomes taller (or deeper) as the game progresses.
63
A.2 Objective The objective of Time Chess is broadly the same as that of Chess - To place the opponent’s King ‘under attack’, such that your opponent has no legal moves.
A.3 Movement Time Chess piece movements can be thought of as Chess movements generalised and extruded extruded into a higher dimension. dimension. As well as moving around the the board as normal normal,, pieces piecescan can move move both both forwar forward d and backwa backward rd in time. time. The Their ir time time travel travellin lingg movement options closely mirror their normal movement options. • A Rook in Chess may pick a direction, direction, x+, x−, y+ or y − and move any number of places places in that direction. direction. So a Time Rook may pick a direction, direction, and move move up to 7 of plac places es in that that dire direct ctio ion. n. Pososx+, x−, y +, y −, t+ or t−, and itive movement in the t dimension is movement forwards in time, negative movement in the t dimension is movement backwards in time. • A Bish Bishop op in Ch Ches esss pick pickss two two orth orthog ogon onal al dire direct ctio ions ns andmoves andmoves an equa equall numnumber of places in each of those directions, effectively moving diagonally. The same is true of a Time Bishop, but it also has the choice of t+ and t− as directions. See Figure A.1. ×
× ×
×
×
×
×
×
×
× ×
× t−1
×
× B
× ×
× t−2
× ×
×
× ×
t
× ×
t+1
t +2
Figure A.1: Movement of a Time Bishop (within a two place radius)
• A Knig Knight ht in Ch Ches esss pick pickss two two orth orthog ogona onall dire direct ctio ions ns,, and and move movess two two spac spaces es in one dimension and one space in the other. Again, this is extruded into the 64
higher dimension of time to provide the Time Knight movement shown in Figure A.2 ×
×
× ×
×
× ×
×
×
×
× × t−1
× ×
N
×
t−2
× ×
×
× ×
× ×
×
× t +1
t
t+2
Figure A.2: Movement of a Time Knight • A Queen in Chess picks either either one direction or two orthogonal directions, directions, and moves any number of places in those. This makes makes a Queen’s Queen’s possible possible move set effectively the union of the move sets of a Bishop and a Rook. The same is true of a Time Queen, as seen in Figure A.3. × ×
× × t−2
× ×
× × × × × t−1
× × × × × × ×Q× × × × × × × ×
× × × × × ×
t
t+1
×
×
×
× t +2
Figure A.3: Movement of a Time Queen (within a two place radius) • AKinginChesscanmoveonespaceineitheronedirectionorintwoorthogonal directions. The Time King’s movement is the same with possibility of forwards and backwards in time as directions.
× × × × ×
× × × × K × × × ×
× × × × ×
t−1
t
t+1
Figure A.4: Movement of a Time King
• Time Pawn Pawn movement movement is show in figure A.5. A.5. The Time Pawn Pawn can move to 65
1 if they are unoccupied, and to positions marked positions marked with 2 if the pawn has not moved before, and the target position and the with
1 position between the pawn and the target position are both unoccupied.
It can capture opposing pieces in positions marked with an ×. 2 × 1 × p
× 1 ×
2
t
t+1
t+2
Figure A.5: Movement of a Time Pawn
A.3.1 Blocking For all pieces other than the Knight, movement cannot be made through an occupied space. space. This applies applies in time as well - for a piece to move to a position, all the spaces in between must be empty. Thus the location location of pieces pieces in past turns decides which moves into the past are possible, and the locations of piece in the future determines what moves into the future are possible. p
p B
t−2
t−1
t
Figure Figure A.6: A.6: Block Blocking ing:: The The Bishop Bishop could could normal normally ly move move to point point p, but but can can’t in this this case because the Pawn is in the way.
A.4 Forward Time Travel Travel When a player declares that they are moving a piece forward in time, that piece is removed from the board. board. When the turn that the piece was moved to comes 66
around, at the end of that turn the piece is placed at its destination.
A.4.1 Appearance Order Order If two pieces are due to arrive from forward time travel in the same turn, the one which departed first arrives first. This is generally only significant if both pieces are arriving at the same square at the same time.
A.4.2 The ‘Lost in Time’ Rule The legality of a forwards time travelling move is not necessarily known at the time the move is made. This is because because the move may require certain certain spaces to be empty, but at the time the move is made, the state of the spaces is yet to be determined. determined. Thus it is possible possible to render a forward time travelling travelling move illegal after it has been made. If this happens, the ‘in transit’ time travelling piece is said to become ‘Lost ‘Lost in Time’. A piece that is Lost in Time is never returned to the board, and is hors de combat . Note that this makes something similar to an En Passant rule for Pawn time travel, since a Pawn moving two spaces into the future may become Lost in Time due to a piece moving into the space one turn ahead of it. If a king becomes Lost in Time, the owner of the king loses the game.
A.5 Backward Time Travel Travel When a piece moves backwards in time, it is removed from its present position, and placed at its destination position.
A.5.1 Taking Pieces Back in Time If a piece is captured in the past, all occurrences of the piece from the time it is captured captured to the present are removed from the game. Any consequences consequences caused caused by the taken piece in the time between its capture and the present (pieces it has taken, moves it has made possible etc.) remain unchanged. 67
A.5.2 Braindead Pieces and Steamrollering Steamrollering Sinc Sincee the the play player erss may may only only comm command and piec pieces es wh whic ich h are are in the the pres presen ent, t, wh when en a piec piecee moves into the past it cannot be given commands, and thus will not move. Such a piece is said to be ‘braindead’ in the time between its arrival in the past, and the present. It is propagated ‘upwards’ towards the present in a straight line. While a piece is braindead, any piece of either colour which moves into a space occupied occupied by it, destroys destroys it. Naturally Naturally if an opposing opposing piece happened, in the past, to move into a space occupied by a braindead piece, it would capture it, but the same is true of a piece of the same colour as the braindead braindead piece. This is called ‘steamrollering’. The steamrollering piece could not have been ordered to move into into an occu occupi pied ed spac space, e, but but the the spac spacee was was not occu occupi pied ed wh when en the the orde orderr was was give given, n, so the move goes ahead and the braindead piece is steamrollered.
A.6 Check Because pieces can be captured in the past, a King is in check if it can be attacked in the the pres presen entt or the the past past.. If any any past past inst instan ance ce of the the King King is unde underr atta attack ck,, the the King King is considered in check.
68
Appendix B
Time Chess Engine Communication Protocol Specification Thee Time Th Time Ch Ches esss Engi Engine ne Comm Commun unic icat atio ion n Prot Protoc ocol ol (TCE (TCECP CP)) is a simp simple le text text prot protoocol designed to facilitate communication between Time Chess engines and Time Chess GUIs. It is inspired by the Chess Engine Communication Protocol (CECP). The protocol works by exchanging single line messages. The GUI sends single linemessagestotheEngine. Someofthesemessagesrequiretheenginetorespond with a line of its own. The Engine does does not send messages to the GUI except except in response to a message from the GUI.
69
B.1 Messages Messages from the GUI to the Engine Engine new
Abandon any ongoing games and ‘make‘ a new game, as though though the system has just been started started up. Expects Expects no reply.
ping
(e.g.
)
a1t0
Check the engine is connected and responding. Requ Reques estt a list list of move movess poss possib ible le for for the the piec piecee at (See section 3.2.3).
(e.g.
)
a2t0a4t0
getState getState t
Attempt to make the move (See section 3.2.3). Get the current turn. In theory this need never be called, but a disagreement between the GUI and the Engine about what turn it is would be disastrous.
getState
Request the state of the board at turn
70
B.2 Messages Messages from the Engine Engine to the GUI pong
(Inreplyto ping )Confirmthattheengine gine is conn connec ecte ted d and and resp respon ondi ding ng by ponging ing the the same number you were pinged
moves ():
(In reply to ) [] is a list of
[]
moves possible for the piece at , as a valid JSON array of strings. (e.g. moves (a4t5): (a4t5): ["a4t5","a3t6"])
Move Move Resu Result lt
(In rep reply ly to to ) Either the string Success if the move worked, or an error message in the Illegal l move move () N>): : >. format Illega
(e.g. Illega Illegal l move move (Move (Move puts puts you in check) check): : a1t0a4t0)
getState t) An integer showing the (In reply to getState
current turn number state state () (): : [LIST] [LIST]
(In reply to getS etState tate
) [LIST]
is a list of pieces on the board at turn JSON array of arrays of the , as a JSO form each
[,,],
representing
a
piece.
(e.g.
[["c3t30","w","k"],["e7t30","b","k"], ["e8t30","b","q"]])
futureQueue: futureQueue: [LIST]
(In reply to getState getState futureQu futureQueue eue) [LIST] is a lis list of piec pieces es in the the futu future re queu queue, e, in the the same same forma ormatt at the the boar board d stat state. e. [["a1t5", [["a1t5", "w", "r"]])
71
(e.g.
72
Appendix C
Time Chess 3D Interface: User Guide C.1 C.1 Look Lookin ingg Arou Around nd Holdingdowntherightmousebuttonandmovingthemousewillrotatetheboard. Moving left and right spins the board horizontally, moving up and down tilts the board up and down. Holding down the middle mouse button and moving the mouse adjusts the zoom. Moving up zooms in, moving down zooms out.
C.2 Selec Selectin tingg Pieces Pieces You can select a piece by clicking on it if it is that side’s turn to move. Clicking on a Black piece when it is White’s turn (and vice versa) does nothing. To deselect a selected piece, click it again.
C.3 C.3 Movi Moving ng Piec Pieces es When a piece is selected, the places it can move to are shown by semitransparent red squares. squares. Click one of the red squares squares to move the selected piece piece to that
73
position.
C.4 Keyboar eyboard d Contro Controls ls Key Effec Effectt F
Hide all layers representing the f uture uture
P
Hide all layers representing the past
N
Hide all layers representing either the future or the past, showing only now.
S
Toggle red/blue red/ blue stereoscopic 3D, viewable with red/blue filter glasses
74