405
The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv, James Culpon, Hugh Gordan, Luqman Skye, Nunzio Thron Programming Languages and Translators: Professor Al Aho Columbia University Spring 2006

The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

  • Upload
    others

  • View
    19

  • Download
    0

Embed Size (px)

Citation preview

Page 1: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

The e2d Programming Language for

Two-Dimensional Spatial Relationship Games

The Five TansAdam Aviv, James Culpon, Hugh Gordan, Luqman Skye, Nunzio Thron

Programming Languages and Translators: Professor Al AhoColumbia University

Spring 2006

Page 2: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

ii

Page 3: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

Contents

1 The e2d Language: An Overview 1

2 e2d Tutorial 52.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2.1.1 HelloWorld . . . . . . . . . . . . . . . . . . . . . . . . . . 52.1.2 Commenting . . . . . . . . . . . . . . . . . . . . . . . . . 62.1.3 Piece Description . . . . . . . . . . . . . . . . . . . . . . . 72.1.4 Init Description . . . . . . . . . . . . . . . . . . . . . . . . 72.1.5 Pattern Description . . . . . . . . . . . . . . . . . . . . . 82.1.6 Turn Description . . . . . . . . . . . . . . . . . . . . . . . 82.1.7 End Description . . . . . . . . . . . . . . . . . . . . . . . 92.1.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2.2 Pieces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.2.1 Piece Example . . . . . . . . . . . . . . . . . . . . . . . . 102.2.2 Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.2.3 Shape Orientation . . . . . . . . . . . . . . . . . . . . . . 122.2.4 Attachments . . . . . . . . . . . . . . . . . . . . . . . . . 142.2.5 Illegal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142.2.6 .dec Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

2.3 Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142.3.1 Init Example . . . . . . . . . . . . . . . . . . . . . . . . . 142.3.2 Player Setup . . . . . . . . . . . . . . . . . . . . . . . . . 162.3.3 Board Setup . . . . . . . . . . . . . . . . . . . . . . . . . 172.3.4 Variable Declaration . . . . . . . . . . . . . . . . . . . . . 172.3.5 Global Mays and Maynots . . . . . . . . . . . . . . . . . . 17

2.4 Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182.4.1 Pattern Example . . . . . . . . . . . . . . . . . . . . . . . 182.4.2 legal and end Descriptions . . . . . . . . . . . . . . . . . 202.4.3 Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212.4.4 Referencing a Pattern . . . . . . . . . . . . . . . . . . . . 212.4.5 May and Maynot . . . . . . . . . . . . . . . . . . . . . . . 22

2.5 Turn and End . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222.5.1 Turn Example . . . . . . . . . . . . . . . . . . . . . . . . 222.5.2 Turn and End Descriptions . . . . . . . . . . . . . . . . . 24

iii

Page 4: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

iv CONTENTS

2.5.3 GameState . . . . . . . . . . . . . . . . . . . . . . . . . . 242.5.4 Flow of Control . . . . . . . . . . . . . . . . . . . . . . . . 242.5.5 Turn Assignment . . . . . . . . . . . . . . . . . . . . . . . 25

2.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252.7 Fun Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

2.7.1 Dominoes . . . . . . . . . . . . . . . . . . . . . . . . . . . 252.7.2 Domain . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272.7.3 Pentominoes .dec File . . . . . . . . . . . . . . . . . . . . 29

3 e2d Language Reference Manual 333.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

3.1.1 Purpose and Intended Audience . . . . . . . . . . . . . . 343.1.2 Stylistic Conventions . . . . . . . . . . . . . . . . . . . . . 34

3.2 Lexical Conventions . . . . . . . . . . . . . . . . . . . . . . . . . 343.2.1 Tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343.2.2 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 343.2.3 Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . 343.2.4 Keyword List . . . . . . . . . . . . . . . . . . . . . . . . . 353.2.5 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . 353.2.6 Integral Constants . . . . . . . . . . . . . . . . . . . . . . 353.2.7 Boolean Constants . . . . . . . . . . . . . . . . . . . . . . 353.2.8 String Constants . . . . . . . . . . . . . . . . . . . . . . . 35

3.3 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353.3.1 Basic Types . . . . . . . . . . . . . . . . . . . . . . . . . . 353.3.2 int . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363.3.3 bool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363.3.4 string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363.3.5 property . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363.3.6 shape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363.3.7 piece . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373.3.8 player . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373.3.9 User-defined Type: piece . . . . . . . . . . . . . . . . . . 373.3.10 Collection Types . . . . . . . . . . . . . . . . . . . . . . . 373.3.11 Set of . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383.3.12 The ... Construction . . . . . . . . . . . . . . . . . . . . . 383.3.13 Mixed Sets . . . . . . . . . . . . . . . . . . . . . . . . . . 383.3.14 Casting Rules . . . . . . . . . . . . . . . . . . . . . . . . . 38

3.4 Expressions and Statements . . . . . . . . . . . . . . . . . . . . . 383.4.1 Stylistic Conventions valid in this section only . . . . . . 393.4.2 Boolean Expressions . . . . . . . . . . . . . . . . . . . . . 393.4.3 ”Normal” boolean operators . . . . . . . . . . . . . . . . . 393.4.4 Logical Quantifiers . . . . . . . . . . . . . . . . . . . . . . 393.4.5 Set membership . . . . . . . . . . . . . . . . . . . . . . . 403.4.6 2d-relational Boolean Operators . . . . . . . . . . . . . . 403.4.7 may flags and equivalence . . . . . . . . . . . . . . . . . . 413.4.8 Flow control expressions . . . . . . . . . . . . . . . . . . . 41

Page 5: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

CONTENTS v

3.4.9 foreach ... in ... . . . . . . . . . . . . . . . . . . . . . . . 413.4.10 if ... else ... . . . . . . . . . . . . . . . . . . . . . . . . . . 413.4.11 Pattern calls . . . . . . . . . . . . . . . . . . . . . . . . . 423.4.12 choice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423.4.13 gameover . . . . . . . . . . . . . . . . . . . . . . . . . . . 423.4.14 Assignment Operators . . . . . . . . . . . . . . . . . . . . 423.4.15 Moving Pieces . . . . . . . . . . . . . . . . . . . . . . . . 433.4.16 Miscellaneous . . . . . . . . . . . . . . . . . . . . . . . . . 443.4.17 print . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443.4.18 Randomness . . . . . . . . . . . . . . . . . . . . . . . . . 44

3.5 Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443.5.1 Declaration of User-Defined Pieces . . . . . . . . . . . . . 443.5.2 Definition of Patterns . . . . . . . . . . . . . . . . . . . . 463.5.3 Declaring a Variable . . . . . . . . . . . . . . . . . . . . . 47

3.6 Game State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473.6.1 Global Variables . . . . . . . . . . . . . . . . . . . . . . . 473.6.2 Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . 473.6.3 Players . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483.6.4 Winners . . . . . . . . . . . . . . . . . . . . . . . . . . . 483.6.5 Bag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483.6.6 Board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483.6.7 Turn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483.6.8 currPlayer . . . . . . . . . . . . . . . . . . . . . . . . . . . 493.6.9 currPiece . . . . . . . . . . . . . . . . . . . . . . . . . . . 493.6.10 may and maynot . . . . . . . . . . . . . . . . . . . . . . . 493.6.11 hide and reveal . . . . . . . . . . . . . . . . . . . . . . . 493.6.12 The Magic of draw, play, move, and remove . . . . . . . 49

3.7 Program Organization . . . . . . . . . . . . . . . . . . . . . . . . 503.7.1 Define Properties . . . . . . . . . . . . . . . . . . . . . . . 503.7.2 Define Pieces . . . . . . . . . . . . . . . . . . . . . . . . . 503.7.3 Shortcut: The .dec file . . . . . . . . . . . . . . . . . . . 513.7.4 Define Initial State Values . . . . . . . . . . . . . . . . . . 513.7.5 Define Patterns . . . . . . . . . . . . . . . . . . . . . . . . 513.7.6 General Patterns . . . . . . . . . . . . . . . . . . . . . . 523.7.7 Pattern legal . . . . . . . . . . . . . . . . . . . . . . . . . 523.7.8 Pattern end . . . . . . . . . . . . . . . . . . . . . . . . . . 523.7.9 Define the Turn . . . . . . . . . . . . . . . . . . . . . . . . 523.7.10 Turn as a loop . . . . . . . . . . . . . . . . . . . . . . . . 533.7.11 Loop Turn versus game state variable Turn . . . . . . . . 533.7.12 Define the End . . . . . . . . . . . . . . . . . . . . . . . . 533.7.13 End behaviors . . . . . . . . . . . . . . . . . . . . . . . . 533.7.14 Winner . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

3.8 Scoping Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543.8.1 General scoping rules . . . . . . . . . . . . . . . . . . . . 543.8.2 Global scope . . . . . . . . . . . . . . . . . . . . . . . . . 543.8.3 Accessing specific parts of pieces . . . . . . . . . . . . . . 55

Page 6: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

vi CONTENTS

3.8.4 Namespace collisions . . . . . . . . . . . . . . . . . . . . . 553.9 Table of Reserved Keywords and Symbols . . . . . . . . . . . . . 55

3.9.1 Preprocessor . . . . . . . . . . . . . . . . . . . . . . . . . 553.9.2 Syntactic Delimiters . . . . . . . . . . . . . . . . . . . . . 553.9.3 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553.9.4 Game State . . . . . . . . . . . . . . . . . . . . . . . . . . 553.9.5 Data members . . . . . . . . . . . . . . . . . . . . . . . . 563.9.6 Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . 563.9.7 Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563.9.8 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563.9.9 Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563.9.10 Logic Predicates . . . . . . . . . . . . . . . . . . . . . . . 573.9.11 Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . 573.9.12 Piece Manipulation . . . . . . . . . . . . . . . . . . . . . . 573.9.13 Allowances . . . . . . . . . . . . . . . . . . . . . . . . . . 583.9.14 Defining Properties . . . . . . . . . . . . . . . . . . . . . . 583.9.15 Defining Pieces . . . . . . . . . . . . . . . . . . . . . . . . 583.9.16 Defining Init . . . . . . . . . . . . . . . . . . . . . . . . . 583.9.17 Defining Patterns . . . . . . . . . . . . . . . . . . . . . . . 583.9.18 Defining End . . . . . . . . . . . . . . . . . . . . . . . . . 583.9.19 Randomness . . . . . . . . . . . . . . . . . . . . . . . . . 593.9.20 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

3.10 Grammar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

4 Project Plan 69

5 Translator Architecture 71

6 Development Environment 736.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 736.2 The ANTLR-Java Interface . . . . . . . . . . . . . . . . . . . . . 736.3 Coding Standards . . . . . . . . . . . . . . . . . . . . . . . . . . 746.4 Platform for Development . . . . . . . . . . . . . . . . . . . . . . 746.5 Tools for Developer Coordination . . . . . . . . . . . . . . . . . . 756.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

7 Test Plan 77

8 Conclusions 798.1 Jamie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 798.2 Adam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 798.3 Nunzio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 808.4 Hugh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 808.5 Luke . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 808.6 As A Team . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 818.7 Our Advice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

Page 7: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

CONTENTS vii

A Source Code 83A.1 Lexer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83A.2 Parser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84A.3 Tree Walker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89A.4 Semantic Analyzer . . . . . . . . . . . . . . . . . . . . . . . . . . 121A.5 Front-End Return Types and Exceptions . . . . . . . . . . . . . . 134

A.5.1 e2dAttachType . . . . . . . . . . . . . . . . . . . . . . . . 134A.5.2 e2dPieceCode . . . . . . . . . . . . . . . . . . . . . . . . . 135A.5.3 e2dProgTypeBall . . . . . . . . . . . . . . . . . . . . . . . 135A.5.4 e2dShapeReturnType . . . . . . . . . . . . . . . . . . . . 135A.5.5 MalformedAlignmentException . . . . . . . . . . . . . . . 136

A.6 e2dCore . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136A.6.1 e2dAttachPoint . . . . . . . . . . . . . . . . . . . . . . . . 136A.6.2 e2dBasicShape . . . . . . . . . . . . . . . . . . . . . . . . 140A.6.3 e2dBoard . . . . . . . . . . . . . . . . . . . . . . . . . . . 147A.6.4 e2dFlags . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155A.6.5 e2dGame . . . . . . . . . . . . . . . . . . . . . . . . . . . 160A.6.6 e2dGameState . . . . . . . . . . . . . . . . . . . . . . . . 178A.6.7 e2dInteractor . . . . . . . . . . . . . . . . . . . . . . . . . 195A.6.8 e2dPiece . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199A.6.9 e2dPlayer . . . . . . . . . . . . . . . . . . . . . . . . . . . 224A.6.10 e2dProperty . . . . . . . . . . . . . . . . . . . . . . . . . . 229A.6.11 e2dSet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233A.6.12 e2dShape . . . . . . . . . . . . . . . . . . . . . . . . . . . 236A.6.13 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . 255

A.7 e2dGUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260A.7.1 GUIe2dBagViewPanel . . . . . . . . . . . . . . . . . . . . 260A.7.2 GUIe2dBoard . . . . . . . . . . . . . . . . . . . . . . . . . 263A.7.3 GUIe2dCurrentPiecePanel . . . . . . . . . . . . . . . . . . 286A.7.4 GUIe2dFrame . . . . . . . . . . . . . . . . . . . . . . . . . 288A.7.5 GUIe2dHandViewPanel . . . . . . . . . . . . . . . . . . . 307A.7.6 GUIe2dInteractor . . . . . . . . . . . . . . . . . . . . . . . 311A.7.7 GUIe2dPieceGraphicsPanel . . . . . . . . . . . . . . . . . 324A.7.8 GUIe2dPieceSelectionPanel . . . . . . . . . . . . . . . . . 331

A.8 e2d Test Programs . . . . . . . . . . . . . . . . . . . . . . . . . . 334A.8.1 Hello World . . . . . . . . . . . . . . . . . . . . . . . . . . 334A.8.2 Domain . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335A.8.3 Latin Squares . . . . . . . . . . . . . . . . . . . . . . . . . 337A.8.4 Tic-Tac-Toe . . . . . . . . . . . . . . . . . . . . . . . . . . 338A.8.5 Fill Piece . . . . . . . . . . . . . . . . . . . . . . . . . . . 340A.8.6 Fit Pieces . . . . . . . . . . . . . . . . . . . . . . . . . . . 341A.8.7 Strange Game . . . . . . . . . . . . . . . . . . . . . . . . 342

A.9 e2dCore and e2dGUI Tests . . . . . . . . . . . . . . . . . . . . . 343A.9.1 CanViewHandsTest . . . . . . . . . . . . . . . . . . . . . 343A.9.2 EqualsTest . . . . . . . . . . . . . . . . . . . . . . . . . . 347A.9.3 GUItest1 . . . . . . . . . . . . . . . . . . . . . . . . . . . 349

Page 8: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

viii CONTENTS

A.9.4 GUItest2 . . . . . . . . . . . . . . . . . . . . . . . . . . . 350A.9.5 GUItest3 . . . . . . . . . . . . . . . . . . . . . . . . . . . 351A.9.6 HelloWorldTest . . . . . . . . . . . . . . . . . . . . . . . . 353A.9.7 MakeChoiceTest . . . . . . . . . . . . . . . . . . . . . . . 353A.9.8 MoveFromBagTest . . . . . . . . . . . . . . . . . . . . . . 354A.9.9 MoveFromBoardTest . . . . . . . . . . . . . . . . . . . . . 359A.9.10 MoveFromCurrHandTest . . . . . . . . . . . . . . . . . . 363A.9.11 MoveFromSetTest . . . . . . . . . . . . . . . . . . . . . . 367A.9.12 MoveFromSomeHandTest . . . . . . . . . . . . . . . . . . 371A.9.13 MoveFromSomeHandToSomeHandTest . . . . . . . . . . . 376A.9.14 MoveToBoardAdjacencyTest . . . . . . . . . . . . . . . . 381A.9.15 PieceSelectionPanelTest . . . . . . . . . . . . . . . . . . . 385A.9.16 PieceTest . . . . . . . . . . . . . . . . . . . . . . . . . . . 388A.9.17 RemoveFromSetTest . . . . . . . . . . . . . . . . . . . . . 394A.9.18 RemovePieceFromBagTest . . . . . . . . . . . . . . . . . . 394

A.10 Semantic Analyzer Tests . . . . . . . . . . . . . . . . . . . . . . . 395A.11 Main . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396

Page 9: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

Chapter 1

The e2d Language: AnOverview

Introduction

The e2d (easy 2D) programming language provides a logical, clean mechanismfor describing games based on two-dimensional geometric relationships. Suchgames include simple favorites such as Dominoes or Tangrams as well as morecomplicated games such as Domain, Froop, Blockus, Tetris, and Bejeweled. e2dallows programmers to focus on rules and gameplay by simplifying the processof implementing these games on computers.

Why Use e2d, Not Some Other Language?

Many two-dimensional games are logically simple, yet, because most languagesdo not provide a concise way to describe the game from its basic building blocks,they are difficult to program. In most high-level languages, programmers need toworry about GUIs, complex objects for simple shapes, and careful spatial mathin order to write their games. Games based on simple shapes and relationships,instead of being simple, require hundreds of lines of code just to make a fewshapes appear on the screen. e2d eliminates this problem by handling everythingin common among these games, allowing the e2d programmer to focus on thehigh-level description of three aspects of the game: the shapes, the patterns,and the gameplay logic.

1

Page 10: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

2 CHAPTER 1. THE E2D LANGUAGE: AN OVERVIEW

e2d Features

Inherent GUI and Playing Interface

In other languages, even a basic GUI requires a disproportionate amount ofwork. By default, e2d provides a general high-level description of what a typi-cal game board should look like, so that the programmer need not be concernedwith the complicated and time consuming details of creating a GUI. This meansthat even the simplest e2d programs compile into usable GUI code, allowing theprogrammer to concentrate on what makes the game unique.

Mario just recently completed his data structures class and wanted to try to pro-gram one of his favorite games–tangrams. Mario tried programming tangramsin Java, but kept getting confused by things like ”swing”, ”beans”, or ”awt”. Heasked for help but the GUI and complicated objects for such a simple game keptgetting in the way. Then he found e2d. e2d automatically provided all the GUIelements he needed for his dominoes game. His e2d code displayed all the piecesand the game board with only the simplest guidelines from Mario.

Clear and Logical Piece Definition

The games e2d describe are similar in their use of pieces: some geometricalshapes that can be played on a two-dimensional board. e2d allows for simple,clear definition of pieces built up out of basic shapes (rectangles and right tri-angles) in intuitive ways. e2d abstracts out the variance among pieces with thesame shape by associating a property with each basic shape, where a propertycan be any unique identifier, like the numbers on dominoes pieces or colors ofDomain pieces.

Various built-in equivalence rules allow the programmer to deal with rela-tionships between the pieces without complicated sections of code dedicated todefining just what ”equals” means. The built-in equivalence rules can be usedto identify identical pieces–on or off the board–with or without regard to thepieces’ orientations, properties, or makeup.

Multiple two-dimensional relationship games share the same pieces and newgames can be created by changing only gameplay. Game programmers maywant to create two games that share a set of pieces without rewriting the shapedeclaration code. For this reason, e2d allows pieces to be declared in a .dec filewhich can be shared among various e2d programs. A .dec file can be comparedto a header file in C–it can be included at the beginning of the program to definethe pieces used later in that program.

Mario’s friend Luigi had an idea for a game using tangram pieces, but wasrunning into the same problems as Mario. When he came to Mario for help,they worked together in e2d to create a .dec file to define the pieces they needed,even though Luigi’s idea had little else in common with the standard Tangrams.

Page 11: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

3

Matching Patterns and Changing State

Every game has some amount of state information: the number of players,their hands, whose turn it is, and the pieces on the board. e2d organizes thisinformation in a hierarchical format that allows the programmer to examineand change elements easily. A common theme in two-dimensional relationshipgames is the concept of performing an action when some pattern is matched:a domino can be played next to a piece that matches its number; a Domainplace switches color when it is adjacent to a recently played piece. Much likethe AWK paradigm, e2d provides simple facilities for describing patterns andthe actions that should be taken when patterns are matched. Patterns canbe based upon any describable relationship within the state of the game, likeadjacency between two pieces. The actions triggered when a pattern is matchedcan change most aspects of the game state, from the whose turn it is to howmany pieces remain on the board.

Two patterns built into the e2d language are the patterns legal and endwhich must be defined in every program. The pattern legal matches any legalmove. e2d compiles this pattern into all of the code necessary to prevent illegalmoves. The pattern end matches the end-of-game state, and specifies how thewinner is determined. The .dec file for piece definitions can describe commonlyused patterns associated with the given pieces. A full .dec file can reduce theproblem of coding a new variation for a game to coding a few intuitive patternsdescribing how things happen differently in certain situations.

Luigi’s game used the same placement rule as normal Tangrams, so they in-cluded the legal pattern in their .dec file. Mario then realized that all he hadto do was to code the end pattern, describing the game-end pattern as whenthe pieces on the board had the outline of a mushroom. Mario had written asingle Tangram puzzle before Luigi had even left the room to start work on hisvariation.

Loop/Turn-Based Game Logic

After pieces and patterns have been described, the majority of the game def-inition is complete. The description of the pieces and patterns in e2d closelyparallel the manner in which people would describe the games to each other ina natural language. The third major section of an e2d program defines the ac-tions that occur on a player’s turn. e2d provides an automatic loop that rotatesamong successive players’ turns. The e2d programmer describes the details of aturn and any special rules for turn progression. A typical turn in many gamesconsists of drawing a piece, playing a piece, and then passing the turn to thenext player. These actions are easily described by e2d library functions thatmake the game loop trivial for typical games. As an example, in the game ofDominoes, most of the game is described by the pieces, the pattern legal, andthe pattern end. For the simplest game using dominoes, where all the dominoesstart in the player’s hands, and the first player out wins, the game loop only

Page 12: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

4 CHAPTER 1. THE E2D LANGUAGE: AN OVERVIEW

needs to specify that the domino pieces start randomly in the player’s hands,and that a turn consists of a player playing a piece from hand to board. Thiscompletes the coding of the game in e2d.

Luigi’s idea is for multi-player Tangrams, where each player has a secret shapethey want to create, and they all share pieces, each trying to get the pieces onthe board to match their secret shape. Luigi merely writes a slightly more com-plicated end pattern than Mario, and uses the game loop to specify that eachplayer can choose a piece from the board as well as from the unplayed pieces toplace. This simple extension proved to be uninteresting as a game, but at leastLuigi hadn’t wasted a lot of time before learning this.

What e2d is Not

e2d is not a language for describing all games or even all two-dimensional boardgames. e2d simplifies the description of relationships among simple geometricshapes, not the more complex interactions of games like Super Mario Bros. e2dis not intended to be general purpose. Though many games can be representedin e2d, some of these, like Go, Checkers, and Chess, may be better describedin another language. e2d is not intended to be a GUI editor though it doesproduce GUI output.

Princess Toadstool, Mario’s girlfriend, got wind of what Mario and Luigi weredoing in e2d. Jealous that her two boys were able to write such complicated codeso easily, she decided to one-up them. She set out to write a full 3d versionof her favorite game Super Mario Brothers 3, all in e2d. The effort was anabsolute failure–even before Bowser kidnapped her yet again.

Page 13: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

Chapter 2

e2d Tutorial

2.1 Introduction

The e2d (easy 2D) programming language provides clear and easy-to-use con-structs for describing games based on two-dimensional geometric relationships.In this tutorial, we introduce the basic terminology and constructs of the e2dlanguage using several real examples. In Chapter 1 we describe the Hello Worldprogram and provide information about program organization and basic fea-tures. Chapter 2 describes piece definitions. In Chapter 3, we show how touse global variables and initialize the game in the Init section. Chapter 4 is fo-cused on patterns, the e2d predicate-like constructs. In Chapter 5, we describethe imperative Turn and End sections of the program. Finally, in Chapter 6,we present some sample e2d programs and a sample .dec file, a mechanism forreusing piece definitions.

2.1.1 HelloWorld

The best way to learn a new programming language is to study a sequenceof basic examples that incrementally introduce new features. Since the dawnof the programmer, the first program studied in a new programming languagehas been the ”Hello World” program. In accordance with this long-standingtradition, we present to you ”Hello World” in e2d.

/******************************** HelloWorld.e2d** A player plays a piece to the* board and receives a "Hello* World" message.*******************************/

piece hello[

5

Page 14: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

6 CHAPTER 2. E2D TUTORIAL

square(1);]

Init[Players += p1;Bag := hello;

]

pattern legal[true;

]

pattern end[

not(exists piece p in Bag);]

Turn[play from Bag;

]

End[print("Hello World");Winners := Players;

]

2.1.2 Commenting

At the very beginning of the Hello World program,

/********************************HelloWorld.e2d**A primitive program in e2d with one piece,*and prints "Hello World" when the game ends*by placing the piece on the board*******************************/

is a comment. As in C, C++, and Java, multi-line comments in e2d beginwith ”/*” and end with ”*/”. Single-line comments beginning with ”//” arealso supported. Comments are not compiled and do not affect the flow of theprogram.

Page 15: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

2.1. INTRODUCTION 7

2.1.3 Piece Description

Following the comment we have the definition of a piece named ”hello.”

piece hello[

square(1);]

The piece is defined within brackets. In this example there is only one statementwithin the brackets, ”square(1);”. This statement says that piece ”hello” iscomposed of a 1 × 1 square. e2d also supports a construct ”rect()” to describerectangles. ”square(1)” is identical to ”rect(1,1)”.

2.1.4 Init Description

The next part of the HelloWorld program is the Init section.

Init[Players += p1;Bag := hello;

]

The Init section, a required part of every e2d program, initializes the game. Inthis example, there are two statements in the Init section. The first

Players += p1;

initializes the players for the game to include just one player named p1. ”Play-ers” is a keyword that represents the set of all players in a given e2d game. The”+=” operator adds a player to the Players set which is initially empty. If therewere two players, one named p1 and the other named p2, an additional line

Players += p2;

would add p2 to the Players set. Another way to add players to the Players setis by assigning a set of players to Players using the assignment operator ”:=”.For example,

Players := {p1,p2};

would also create a two-player game between p1 and p2.The second statement in the Init section is

Bag := hello;

”Bag” is a keyword that refers to the set of pieces that can be chosen by theplayers. For example, in Scrabble, ”Bag” would be the bag of Scrabble piecesfrom which players pick at the end of their turns. Like ”Players”, ”Bag” isa set that is initially empty. In this example, ”Bag” is initialized with one

Page 16: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

8 CHAPTER 2. E2D TUTORIAL

piece: the ”hello” piece described in the piece description. Note that thereare no braces around ”hello.” This is because a piece name refers to the setof all distinct types of pieces that match the piece definition. In this ”HelloWorld” example, there is only one type of piece that matches the ”hello” piecedefinition, i.e., the 1 × 1 square. Some piece definitions may allow for differentcombinations of property assignments to the shapes that compose the piece.When this happens, the name of the piece refers to the set that includes oneelement with each allowable combination of properties. The ”+=” operator canalso be used between two sets where it assigns the union of the two sets to theset on the left-hand side. Thus, ”Bag += hello” is equivalent to ”Bag := hello”when ”Bag” is empty.

2.1.5 Pattern Description

A pattern in e2d tests a condition, returns true or false accordingly, and possiblytriggers a corresponding action. In the HelloWorld.e2d program there are onlytwo patterns.

pattern legal[true;

]

pattern end[not(exists piece p in Bag);

]

These happen to be the two patterns that every e2d program must include: thepatterns legal and end.

The legal pattern is checked whenever a piece is played. It describes thelegal moves for the game. In our example, legal always returns ”true” so allmoves are legal.

In e2d we use the math constructs of First Order Logic (FOL). The booleanoperations ”and”, ”or”, and ”not” are standard. The universal quantifier in e2dis ”forall” and the existential quantifier is ”exists”.

Our example includes the predicate ”not(exists piece p in Bag)”. The innerportion of this predicate is of the form ”exists <type> <name> in <set>”.The ”set” must contain items of type ”type”. The name ”name” is given to anobject that matches the existentially quantified predicate if such an object isfound. The ”not” operator then negates the return value of the inner portionof the predicate. Thus, end is looking for a piece which it will name ”p” in theset ”Bag”. If it finds one, it will return false; otherwise, it will return true.

2.1.6 Turn Description

Turn

Page 17: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

2.1. INTRODUCTION 9

[play from Bag;

]

”Turn”, a required section and the heart of the program where the game playis described, defines the actions that make up a player’s turn. In our example,”Turn” consists of one statement, ”play from Bag”. This statement allows aplayer to take a piece from the bag and play it on the board. There are anumber of other constructs that control the flow of the game. Examples include”gameover” (end the game), ”draw” (draw a piece from the Bag), ”move” (movea piece from one piece set to another), and ”play” (play a piece from the player’shand to the board). ”play from Bag” is equivalent to the two statements ”draw;play;” so that ”Turn” could also be defined as

Turn [draw;play;

]

The ”Turn” section is a basic loop. The game will continue to loop until the endpattern is matched. With multiple players, one can change to the next player byreaching the end of the loop or by explicitly assigning a player to the variable”Turn” which causes the ”Turn” loop to repeat immediately as the assignedplayer’s turn.

2.1.7 End Description

The final section of the ”Hello World” program is the ”End” section.

End[print("Hello World");Winners := Players;

]

Control switches to the ”End” section when the end pattern is matched. Thefirst statement

print("Hello World");

displays the message ”Hello World” to the user. The second statement

Winners := Players;

is a construct that defines who won the game. Like ”Players”, ”Winners” is aset of players. Any player in the ”Winners” set wins the game. Therefore, thisstatement says that all the players won. In this ”Hello World” example, thereis only one player and that players wins. An equivalent statement is

Winners += p1;

Page 18: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

10 CHAPTER 2. E2D TUTORIAL

2.1.8 Summary

Now that we have examined each line of the program, we can see that the gamedescribed by this program is, indeed, the e2d variant of the standard ”HelloWorld” program. The setup is one piece in the bag and one player. The playerplays the piece anywhere on the board. Once the piece is played, the end patternis matched and control transfers to the ”End” section where ”Hello World” isprinted and the player is added to the Winners set. It is impossible to lose and”Hello World” is always printed.

2.2 Pieces

2.2.1 Piece Example

This chapter examines in more detail the constructs provided by e2d for piecedefinitions. In this sample game, two players are competing against each otherto ”fit” together more pieces then the other.

/******************************** Example1.e2d** Two Players compete to "fit"* together more pieces than* the other*******************************/

Properties +={Black, White);

Black.image := black;White.image := white;

piece bot {x,y}[

rect(2,1) property x alias R;u>: rect (1,1) property y alias U;illegal: x=y;

]

piece top {x,y}[rect(2,1) property x alias R;d<: rect(1,1) property y alias D;illegal: x = y;attachment: D(ur,y) <-> bot.U(dl,y);

]

Page 19: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

2.2. PIECES 11

Init[Players += {p1, p2};p1.score := 0;p2.Score := 0;maynot flip;maynot rotate;Bag += top(white, black)*10;Bag += top(black, white)*10;Bag += bot(black, white)*10;Bag += bot(white, black)*10;

]

pattern legal[not(exists piece p in Board

p.x != currPiece.x and not(p attaches currPiece));]

pattern end[empty(Bag);

]

filled_piece[exists piece p

p attaches currPiece and p.x = currPiece.x;action a:

if currPiece.x=white[p1.score+=1;

]else[p2.score+=1;

]]

Turn[draw;if currPlayer = p1[currPiece.x := white;

Page 20: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

12 CHAPTER 2. E2D TUTORIAL

]else[currPiece.x := black;

]play;filled_piece.a;

]

End[if p1.score < p2.score[Winners += p2;

]else[if p1.score > p2.score[Winners += p1;

]]

]

2.2.2 Properties

Properties are an important part of the e2d language. Their main use is todifferentiate different types of pieces or different types of shapes within a piece.A property can be associated with a given color for display purposes. Propertiesare defined at the beginning of the program. At the beginning of our sampleprogram, we have the property declaration statement

Properties +={Black, White};

Like ”Players” and ”Winners”, ”Properties” is a set, so both the ”+=” operatorand the ”:=” operator are defined on it. In this example, two properties, Blackand White, are added to the ”Properties” set. Black and White become variablesof type property and thus image values that can be set for them. The nextstatements in our example

Black.image := black;White.image := white;

set the image values of the properties to the colors black and white.

2.2.3 Shape Orientation

In this section we will look at how rectangular shapes are combined to forma piece. e2d provides an intuitive way of performing this operation. In our

Page 21: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

2.2. PIECES 13

example, we define the pieces with the code

piece bot {x,y}[

rect(2,1) property x alias R;u>: rect (1,1) property y alias U;illegal: x=y;

]

piece top {x,y}[rect(2,1) property x alias R;d<: rect(1,1) property y alias D;illegal: x = y;attachment: D(ur,y) <-> bot.U(dl,y);

]

When defining the shapes that constitute a given piece, it is important to con-struct the piece in an intuitive way. The first shape declared in a piece decla-ration is always the pivot shape, the shape about which the other shapes areoriented. In piece ”bot” the orientation piece is rect(2,1) which is given thealias ”R”. The next shape declared is rect(1,1), given the alias ”U,” and ithas an alignment argument of u>. This means that U is placed below R andright-aligned. In ASCII art the two pieces looks like

bot: top:-- -- --

|y | |x |x |-- -- -- --

|x |x | |y |-- -- --

This is the complete set of alignment arguments that can be used.

u -- up placementd -- down placementr -- right placementl -- left placement> -- align right< -- align left^ -- align up_ -- align down

The alignment values must appear after a proper placement argument. < and >can only appear after u or d, while and can appear only after r or l. Looking atthe ASCII art, we could also have defined the shapes of the piece ”top” withoutusing the alignment operators as

square(1); u:square(1); ur:square(1);

Page 22: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

14 CHAPTER 2. E2D TUTORIAL

In piece ”bot”, R is assigned property x and U is assigned property y. x andy are variables for arguments passed into the piece during its construction. A”bot” piece can be constructed as ”bot(White, Black)” or ”bot(Black, White)”where x and y get replaced by the corresponding property passed into the piece.The alias for the shape is a mechanism for referring to a particular shape. Torefer to U in piece bot, one can call bot.U.

2.2.4 Attachments

Now we look at the attachment declaration in the piece. The attachment sectiondescribes how pieces fit together. Later in the program one can query if twopieces can attach by using the predicate ”p attaches q.” In the ”top” piece, theattachment section is

attachment: D(ur, y) <-> bot.U(dl, y);

This says that the D shape of top can connect its upper-right side to the Ushape of bot’s lower-left side provided both of these sides have the same property(specified by the reuse of ”y”). The < − > construct is used to mean ”attaches”.It is not necessary to include a property in the attachment description if thereis no restriction on the property.

2.2.5 Illegal

The illegal section of the piece declaration is used to restrict the type of piecesthat can be created. In our example the illegal statement in both pieces are:

illegal: x = y;

which restricts the possible pieces to ones where the property x does not equalthe property y. If one attempts to construct a piece that does not obey theillegal command, a compile-time error will occur.

2.2.6 .dec Files

Everything described in this section for the piece declaration and property as-signment can be placed into a special file with a .dec extension. The .dec filethen can be imported to a number of different games that could use the samepiece and property declarations. Suppose the .dec file is named Connecters.dec.Then to import it into another game it is as simple as

import "Connectors.dec";

2.3 Init

2.3.1 Init Example

For the sake of variety, we present a new program for which we will describe the”Init” section in detail. Details of the other sections of the previous program

Page 23: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

2.3. INIT 15

that are not immediately clear will be clear to the reader after finishing thetutorial. In this new sample game, three players are given pieces of their owncolor. Players take turns placing pieces on the board until one player placesthree pieces of one color in a straight line.

/************************************ Example2.e2d** Players take turns placing* pieces on the board until* one player places three pieces* of one color in a straight line************************************/

Properties += {blueProp, greenProp, yellowProp};

blueProp.image := blue;greenProp.image := green;yellowProp.image := yellow;

piece block {x}[

rect(2,1) property x;]

piece goal {x}[

rect(6,1) property x;]

Init[Players += {bluePlayer, greenPlayer, yellowPlayer};bluePlayer.hand += block(blueProp);greenPlayer.hand += block(greenProp);yellowPlayer.hand += block(yellowProp);Board.width = 10;Board.height = 10;int count := 0;may rotate;

]

pattern legal[forall piece p in Board not(p overlaps currPiece);

]

Page 24: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

16 CHAPTER 2. E2D TUTORIAL

pattern end[exists piece p in goal

p within Board;]

Turn[play;if currPlayer = bluePlayer[currPlayer.hand += block(blueProp);

]if currPlayer = greenPlayer[currPlayer.hand += block(greenProp);

]if currPlayer = yellowPlayer[currPlayer.hand += block(yellowProp);

]counter+=1;

]

End[print "Game over. The game took " + count + "turns";if goal(greenProp) within Board[Winners += greenPlayer;

]if goal(blueProp) within Board[Winners += bluePlayer;

]if goal(yellowProp) within Board[Winners += yellowPlayer;

]]

2.3.2 Player Setup

In the sample program, we add players and define player properties with thestatements

Page 25: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

2.3. INIT 17

Players += {bluePlayer, greenPlayer, yellowPlayer};bluePlayer.hand += block(blueProp);greenPlayer.hand += block(greenProp);yellowPlayer.hand += block(yellowProp);

On the first line we are declaring that there will be three players, named blue-Player, greenPlayer, and yellow Player. We do this by adding bluePlayer, green-Player and yellowPlayer to the set Players using the ”+=” operator. The nextthree lines add pieces to each player’s hand. We wish to differentiate the piecesof each player by color. The line

bluePlayer.hand += block(blueProp);

adds one piece of type block with the property ’blueProp’ to the blue player’shand. The rest of the lines are trivial modifications of that one. Basically,these first few lines of this Init statement add three players and assign themblocks with different color properties, allowing the users to visually differentiatebetween each other’s pieces.

2.3.3 Board Setup

The next two lines of the program define a board:

Board.width = 10;Board.height = 10;

Here we are defining a 10 × 10 board. One can also put pieces on the board tostart the game. See the Reference Manual for more details.

2.3.4 Variable Declaration

The next line defines an integer variable:

int count := 0;

The integer type is 32 bits long and holds a signed integer. Here we use the :=operator to initialize the value of count to 0. One can also define variables oftype piece, shape, player, boolean and int. All variables that are global mustbe defined in Init. Global variables can be used as counters (to see how manytimes something has happened), or as boolean flags, or as other game relatedobjects.

2.3.5 Global Mays and Maynots

The final line in this Init section changes the global may and maynot rules:

may rotate;

Page 26: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

18 CHAPTER 2. E2D TUTORIAL

may and maynot are very useful. The default for every game is maynot rotate,maynot flip. This basically says that when comparing two pieces, one maynot rotate or flip them. By putting may rotate into the program, we tell thecomputer that it is okay to rotate the pieces when checking for equality and thatthe player may rotate them when putting them onto the board. If one wouldlike to limit rotation to certain pieces, one could define a locally scoped rotatestatement for any piece that is defined.

2.4 Patterns

2.4.1 Pattern Example

Here we return to the game with the ”top” and ”bot” pieces and examine thepatterns that are used in it. We repeat the program here to refresh your memory.

/******************************** Example1.e2d** Two Players compete to "fit"* together more pieces than* the other*******************************/

Properties +={Black, White);

Black.image := black;White.image := white;

piece bot {x,y}[

rect(2,1) property x alias R;u>: rect (1,1) property y alias U;illegal: x=y;

]

piece top {x,y}[rect(2,1) property x alias R;d<: rect(1,1) property y alias D;illegal: x = y;attachment: D(ur,y) <-> bot.U(dl,y);

]

Init[Players += {p1, p2};

Page 27: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

2.4. PATTERNS 19

p1.score := 0;p2.Score := 0;maynot flip;maynot rotate;Bag += top(white, black)*10;Bag += top(black, white)*10;Bag += bot(black, white)*10;Bag += bot(white, black)*10;

]

pattern legal[not(exists piece p in Board

p.x != currPiece.x and not(p attaches currPiece));]

pattern end[empty(Bag);

]

filled_piece[exists piece p

p attaches currPiece and p.x = currPiece.x;action a:

if currPiece.x=white[p1.score+=1;

]else[p2.score+=1;

]]

Turn[draw;if currPlayer = p1[currPiece.x := white;

]else[

Page 28: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

20 CHAPTER 2. E2D TUTORIAL

currPiece.x := black;]play;filled_piece.a;

]

End[if p1.score < p2.score[Winners += p2;

]else[if p1.score > p2.score[Winners += p1;

]]

]

2.4.2 legal and end Descriptions

The two required patterns in e2d are legal and end.

pattern legal[not(exists piece p in Board

p.x != currPiece.x and not(p attaches currPiece));]

pattern end[empty(Bag);

]

Legal describes legal moves in the game. It follows the typical pattern structureand is tested after every play in the game. If it returns false, the move is notpermitted and the play is started over again. In this game the only thing thatlegal does is return true or false. There are no associated actions. Let’s analyzethe FOL expression in legal. First we note the not operator is the first logicaloperator in the FOL expression. This operator negates the FOL expressionwithin the parentheses. Next we look for a piece, p, on the board such thatthe property x of p (p.x) is not the same as the current piece’s property x andsuch that p does not attach to the current piece. In other words, a legal moveis defined as any move so long as two pieces with a different property x do not

Page 29: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

2.4. PATTERNS 21

attach (’fit’) together. This means that a player cannot attempt to fit a pieceinto another player’s piece.

The end pattern describes how the game comes to an end. It is worthmentioning here that the only way that a game can come to an end withoutmatching the end pattern is by an explicit call to gameover as an action. Acall to gameover ends the game and transfers control immediately to the ”End”block without any pattern checking. Here the pattern end is very simple: thegame will end once the bag of pieces, filled elsewhere, is empty. Since there areno calls to gameover in this game, the only way for the game to be over is forthe end pattern to be matched (i.e. all pieces must be out of the bag and playedon the board).

2.4.3 Actions

Here we look at a semantic action that is called when a pattern is true.

filled_piece[exists piece p

p attaches currPiece and p.x = currPiece.x;action a:

if currPiece.x=white[p1.score+=1;

]else[p2.score+=1;

]]

In the pattern filled piece, first we have a FOL expression that defines whetheror not the pattern is true. If the pattern is true, then the action, defined onthe next line, can be run if it is explicitly called. The action ”a” implementsa score-keeping variable that is associated with each player. It says that ifthe current piece is white, increment the white player’s score by one, otherwiseincrement the black player’s score by one. Since this action is within the filledpiece pattern, when called, it has the effect of increasing the players’ scores byone every time they match two pieces together.

2.4.4 Referencing a Pattern

Now we look at how a pattern can be called from inside the Turn loop. It shouldbe noted that a pattern can also be called in the same manner from inside anaction that is defined inside a pattern (i.e. patterns can be called recursively).

Turn

Page 30: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

22 CHAPTER 2. E2D TUTORIAL

[draw;if currPlayer = p1[currPiece.x := white;

]else[currPiece.x := black;

]play;filled_piece.a;

]

Here we called ’filled piece.a’ after the play is finished for the turn. Play consistsof drawing a random piece from the bag, coloring it appropriately for the playerthat drew it, and allowing the player to place the piece on the board according topattern legal. When this is finished, we first call the pattern ’filled piece’ whichchecks to see if a piece was filled in the just completed play. If ’filled piece’returns true, then we call the action a which, as discussed in the last section,increments the score for the appropriate user. If the pattern ’filled piece’ returnsfalse, nothing is done and the next turn takes place.

2.4.5 May and Maynot

Although there is no example of local may and maynot use in the exampleprogram, it seems prudent to mention the possibility here. A local may or maynot can be used in patterns to add or take away rotation and/or flip capabilitiesfor equality-testing in a pattern.

2.5 Turn and End

2.5.1 Turn Example

In this game, we create an strangely shaped piece, then present the user withrectangles. The user attempts to place the rectangles inside the strangely shapedpiece in order to fill out the shape. The pieces are stored in a bag, then placedinto the user’s hand, then placed on the board.

Properties += {strange, normal};

piece strangeshape[

rect(3,2) property strange;r_: [square(1) property strange;

u<: [square(2) property strange;

Page 31: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

2.5. TURN AND END 23

r^: [rect(3,1) property strange;u>: rect(4,1) property strange;]]]

]

piece toplay[rect(3,1) property normal;

]

Init[Players += p1;piece s := strangeshape;piece r;s.loc.x := 0;s.loc.y := 0;Board += s;Bag += toplay*6;may rotate;

]

pattern legal[currPiece within Board;action add: r := r join currPiece;

]

pattern end[empty(Bag);

]

Turn[draw;play;legal.add;

]

End[if s within r[Winners += p1;

]else

Page 32: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

24 CHAPTER 2. E2D TUTORIAL

[print "Try to do better next time."

]]

2.5.2 Turn and End Descriptions

In e2d, ”Turn” and ”End”, the heart of the game, define the code that is runwhen the game is being played. The turn loop

Turn[draw;play;legal.add;

]

is executed in the order which the statements are placed. When executionreaches the end of a turn, the pattern end is checked. If end is matched, thenexecution transfers to the ”End” section of the code,

End[if s within r[Winners += p1;

]else[print "Try to do better next time."

]]

is called, which, in this case, is self-explanatory.

2.5.3 GameState

GameState keeps track of the state of the game. Much useful information isstored in GameState such as the Players, Winners, Bag, Board, Turn, cur-rPlayer, and currPiece. Many of these values are set before the Turn loop. ThecurrPlayer and currPiece of GameState are updated after every turn.

2.5.4 Flow of Control

e2d provides some standard flow of control mechanisms that can be used inthe Turn and End sections to control how the game is played and terminated.The if-else clause has the same meaning as in C, C++, and Java. It allows fordifferent actions to occur for different situations of the game. In the example

Page 33: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

2.6. CONCLUSION 25

above, either you win, or ”Try to do better next time.” is printed to the screen.Another useful control-flow is the the ”foreach” clause that will iterate over theelements of a set. An example is

foreach p in Pieces [/*do something*/]

2.5.5 Turn Assignment

e2d has a mechanism for switching to an arbitrary player. If one were to assigna player to the special variable ”Turn”, like

Turn[draw;play;if not(foo)[Turn := currentPlayer;

]]

a jump occurs to the beginning of the ”Turn” loop with the player assigned to”Turn” playing. This is the only time in e2d where an assignment causes theside effect of a jump in the execution. In the example provided above, if pattern”foo” is not matched, then the currentPlayer plays again. Note, if there is noassignment to ”Turn,” the normal iteration over the ”Players” set continues.

2.6 Conclusion

Having examined the basic features of some simple games, the next step is tostart writing games in e2d yourself. If you have questions or run into difficulties,the Language Reference Manual contains a detailed description of all languagefeatures. In the following section, we have included some sample games thatyou can test and modify. We hope that you enjoy writing programs in e2d asmuch as we enjoyed defining the language and writing its compiler.

2.7 Fun Examples

2.7.1 Dominoes

Properties += {0-6};

piece domino {x,y}[

square(2) property x alias L;r: square(2) property y alias R;

Page 34: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

26 CHAPTER 2. E2D TUTORIAL

illegal: x > y;attachments: L(l,p), R(r,p) <-> L(l,p), R(r,p),

all(L(ur,p),R(ul,p)), all(L(dr,p),R(dl,p));]

Init[Bag += domino;Players += {1...3};

]

pattern playable {piece p}[/*there exists a piece that p can attatch toor there are no pieces on the board*/

(exists piece q in Board p attaches q)or not(exists piece q in Board);

]

pattern legal[playable(currPiece);

]

pattern canPlay {player pi}[exists piece p in pi.hand playable(p);

]

pattern end[empty(currPlayer.hand)or (forall player pi in Players not canplay(pi)) ;

]

Turn[if not canplay(currPlayer) and not empty(Bag)[draw;Turn := currPlayer; //this restarts the turn]if canPlay(currPlayer) [play;]

]

End

Page 35: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

2.7. FUN EXAMPLES 27

[int count;foreach player p in Players[ if empty(p.hand)[Winners += p;

] else[count := 0;foreach player po in Players po != p[if p.hand.size < po.hand.size [count += 1;]

]if count = Players.size - 1 [ Winners += p;]

]]

]

2.7.2 Domain

Properties += {black, white};

piece cross {property x}[

rect(3,1) property x;u: square(1) property x;d: square(1) property x;

]

piece largeT {property x}[

rect(1,4) property x;r^: square(1) property x;l^: square(1) property x;

]

piece longbar {property x}[rect(1,4) property x;

]

piece square {property x}[square(2) property x;

]

Page 36: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

28 CHAPTER 2. E2D TUTORIAL

piece smallT {property x}[

rect(1,3) property x;r^: square(1) property x;l^: square(1) property x;

]

piece angle {property x}[rect(1,3) property x;

]

piece mediumbar {property x}[rect(1,3) property x;

]

piece smallbar {property x}[rect(1,2) property x;

]

Init[Board.height := 9;Board.width := 9;Bag += cross(black)*2;Bag += largeT(black)*2;Bag += longbar(black)*2;Bag += square(black)*2;Bag += smallT(black)*2;Bag += angle(black)*2;Bag += mediumbar(black)*2;Bag += smallbar(black)*2;Players += {blackplayer, whiteplayer};reveal Bag;

]

pattern legal[not (exists piece p in Board (p overlaps currpiece));

]

pattern end[forall piece p in Bag (not playable p);

Page 37: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

2.7. FUN EXAMPLES 29

]

Turn[property color;if currplayer = blackplayer [color := black;]else [color := white;]foreach piece p in Bag[p.x := color;

]

draw from Bag;

play;

foreach piece p in Board[

if currpiece adjacent p[p.x := color]

]]

End[int blackscore;int whitescore;foreach shape s in Board[if s.x = black [blackscore += 1;]else [whitescore += 1;]

]

if blackscore > whitescore [Winners += blackplayer]else [Winners += whiteplayer]

]

2.7.3 Pentominoes .dec File

piece p1[rect(5,1);

]

piece p2[

Page 38: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

30 CHAPTER 2. E2D TUTORIAL

rect(4,1);u>:rect(1,1);

]

piece p3[rect(3,1);u>:rect(2,1);

]

piece p4[rect(2,1);u:rect(2,1);uu>:rect(1,1);

]

piece p5[rect(3,1);u>:rect(1,1);d>:rect(1,1);

]

piece p6[rect(3,1);u>:rect(1,1);d<:rect(1,1);

]

piece p7[rect(3,1);u>:rect(1,1);d:rect(1,1);

]

piece p8[rect(3,1);u:rect(1,1);d:rect(1,1);

]

piece p9

Page 39: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

2.7. FUN EXAMPLES 31

[rect(3,1);u>:rect(1,1);u<:rect(1,1);

]

piece p10[rect(2,1);d>:rect(1,1);u<:rect(1,2);

]

piece p11[rect(2,1);r_:rect(1,2);rr:rect(1,1)

]

piece p12[rect(1,1);u:rect(1,1);d:rect(1,1);r:rect(1,1);l:rect(1,1);

]

Page 40: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

32 CHAPTER 2. E2D TUTORIAL

Page 41: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

Chapter 3

e2d Language ReferenceManual

3.1 Introduction

The e2d (easy 2D) programming language provides a logical, clean mechanismfor describing games based on two-dimensional geometric relationships. Suchgames include simple favorites such as Dominoes or Tangrams as well as morecomplicated games such as Domain, Froop, Blockus, Tetris, and Bejeweled. e2dallows programmers to focus on rules and gameplay by simplifying the processof implementing these games on computers.

Many two-dimensional games are logically simple, yet, because most languagesdo not provide a concise way to describe the game from its basic building blocks,they are difficult to program. In most high-level languages, programmers needto worry about GUIs, complex objects for simple shapes, and careful spatialmath in order to write their games. Games based on simple shapes and rela-tionships, instead of being simple, require hundreds of lines of code just to makea few shapes appear on the screen. e2d eliminates this problem by handling ev-erything in common among these games, allowing the e2d programmer to focuson the high-level description of the game.

e2d is a strongly-typed language loosely modeled on natural-language descrip-tions of two-dimensional relationship games. e2d breaks the description of gamesinto three parts: the pieces used in the game, the play of a turn, and end con-dition of the games. To facilitate simple yet flexible description of game playelements, e2d uses the notion of ”patterns,” a function-like construct whichperforms actions based on the evaluation of a quantified boolean expression.These quantified boolean expressions are very similar to first-order predicatelogic statements. e2d provides a few useful predicates as language features andprogrammers can add their own predicates by defining patterns.

33

Page 42: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

34 CHAPTER 3. E2D LANGUAGE REFERENCE MANUAL

3.1.1 Purpose and Intended Audience

This document provides a technical specification of the e2d programming lan-guage. It includes sections describing all of e2d’s major features, with a grammarat the end of the document which can be used as a guide when implementingan e2d compiler. It does not provide complete sample e2d programs, althoughsome e2d code is included for illustrative purposes.

This reference manual is intended both as a point of reference for e2d’s gram-mar and specification of the language. It is primarily intended for those whowish to implement an e2d compiler which is in full compliance with all e2dstandards. It can also enhance an experienced e2d programmer’s understandingof the language and refresh the programmer’s memory about specific languagefeatures.

3.1.2 Stylistic Conventions

In this document, syntactic categories appear in italics and literal code or termsappear in fixed width. Longer examples occur

verbatim

in the document. When used, the key words ”MUST”, ”MUST NOT”, ”RE-QUIRED”, ”SHALL”, ”SHALL NOT”, ”SHOULD”, ”SHOULD NOT”, ”REC-OMMENDED”, ”MAY”, and ”OPTIONAL” in this document are to be inter-preted as described in RFC 2119.

3.2 Lexical Conventions

3.2.1 Tokens

Tokens are either identifiers, keywords, constants, operators, or other separa-tors. White space is ignored except as it separates identifiers, keywords, andconstants. White space includes spaces, tabs, newlines, formfeeds, and com-ments.

3.2.2 Comments

Comments have two forms. One begins with /*, consists of a sequence of symbolsnot including */, and ends with */. The other begins with // and MUST endat the appropriate newline construct for the system. The GNU C use of \ toextend // comments across multiple lines SHALL NOT be allowed.

3.2.3 Identifiers

An identifier is a sequence of letters, numbers, and . An identifier begins witha letter or and can be arbitrarily long. Identifiers are case sensitive, so foo,Foo, and FOO are all different identifiers.

Page 43: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

3.3. TYPES 35

3.2.4 Keyword List

The following keywords are reserved in e2d and cannot be used by the program-mer as identifiers.

import piece shape property int player bool string PropertiesPlayers Winners Bag Board Turn currPlayer currPiece matchedunmatched and or not forall exists true false overlaps adjacentwithin attaches elementof playable foreach in if else game_overchoice join rotate flip_over_x flip_over_y draw play from moveremove to at may maynot flip hide reveal hands rgb square rect aliasillegal attachment all Init pattern action End random print

3.2.5 Constants

Constants are integers, booleans, and strings.

3.2.6 Integral Constants

An integral constant is a sequence of digits, 0 to 9, which is interpreted as abase ten integer.

3.2.7 Boolean Constants

The boolean constants are the tokens true and false.

3.2.8 String Constants

A string constant is the character " followed by a sequence of printable charac-ters terminated by a ". If the string contains a " it must be preceded by \. \‘‘is interpreted as the character ‘‘ within the string constant. \\ is the character\ in the string, and \ n is a newline in the string. \ followed by any characterother than ", \, or n is undefined and MAY be reserved as a different escape.

3.3 Types

Identifiers can refer to variables. A variable is a location for storage of data thathas a type. The type a set of possible values and guides interpretation. e2d isa strongly-typed language, so all variables MUST be created with a type.

3.3.1 Basic Types

The following are the basic types defined.

Page 44: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

36 CHAPTER 3. E2D LANGUAGE REFERENCE MANUAL

3.3.2 int

The int type stores signed integers of implementation-dependent size, butMUST be at least 32 signed bits. These integers behave as expected underthe arithmetic operations +,−, ∗. Division, denoted /, is the floor of the di-vision. The comparison operators <,>,<=, >=,=, ! = are defined betweenintegers. On declaration without initialization the value SHOULD be 0.

3.3.3 bool

The bool type stores boolean values, ie true or false which behave as ex-pected under and, or, and not. On declaration without initialization the valueSHOULD be true.

3.3.4 string

The string type stores a sequence of printable characters. String concatenationuses +. The empty string MUST be defined and equal to the string constant "".On declaration without initialization the value SHOULD be the empty string.

3.3.5 property

The property type stores properties. Conceptually, a property can be anything,but is usually the property of a shape or piece. Any property can be identifiedby an identifier or a number. Properties are ordered by time of creation sothat properties created earlier are less and not equal to any properties createdlater. Thus the comparison operators <,>,<=, >=,=, ! = are defined betweenproperties. Each property also has an image which can be set to determine howshapes with that property appear on screen. The implementation MUST definea default property which only the implementation may have access to. It MAYNOT be accessible to the e2d program. On declaration without initializationthe value SHOULD be this default property.

3.3.6 shape

The shape type is a basic building block for a piece. A shape is a rectan-gle, possibly with a location. Each shape MUST have a property, so if one isnot defined, the implementation MUST set the shape’s property to the defaultproperty. A shape also MUST have an integer width and height. If not defined,the implementation SHOULD initialize them as it initializes integers. Shapescan be tested for equality, subject to the restrictions on flipping and rotating.On declaration without initialization the value SHOULD be the shape with thedefault property and width and height of 0.

Page 45: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

3.3. TYPES 37

3.3.7 piece

The piece type can be any of the user-defined types in section 3.2. On decla-ration without initialization it SHOULD be the empty piece.

3.3.8 player

The player type stores a player. A player is identified by an identifier ora number. Players are equal if they are identified by the same identifier ornumber. Every player has a hand, which is a set of pieces, and a name, whichis a string. The hand MUST be initialized as the empty set. On declarationwithout initialization the value of name SHOULD be the empty string. Whenthe player type is assigned a value, the name MUST become the identifier ornumber that identifies the player.

3.3.9 User-defined Type: piece

The user can define specific piece types, which are collections of shapes withcertain rules. Logically, a piece type is a collection of shapes with the samerelative location but different properties. A classic example is the set of dominopieces, with each number of dots on a piece as the property of the shape. Piecescan be joined together to create conglomerate pieces, flipped, and rotated. Theycan also be compared to each other with equals, under the restrictions on flippingand rotation. Pieces also define how they can attach to one another, which ischecked later with the attaches construct. Can also check if two pieces overlapor are adjacent, if a piece is playable, or if a piece is within another. Pieces canalso have a location defined.

3.3.10 Collection Types

Each of the 7 basic types and user defined types can also be elements of sets.Sets are typed, so that a set cannot contain elements of multiple types, un-less they are type-casted to the same type. Sets are multisets in that they cancontain multiples of the same object. The implementation MAY keep just onecopy of each with a count of how many are in the set. Sets are ordered; theyMUST maintain the order in which elements were added to them. The opera-tions defined on sets are adding elements and sets, removing elements and sets,and performing the union of sets (denoted by the + operator). One can alsocheck if something is an element of a set. This is always false if the types donot match, if the element cannot be typecast to the set type, or if the elementand set are not pieces or user-defined specifications of pieces. On declarationwithout initialization all sets SHOULD be initialized to the empty set.

All sets may be specified using {} surrounding a comma-delimited list of in-dividual items in that type. All sets have an element size of integer type whichMUST always be defined and equal to the cardinality of the set.

Page 46: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

38 CHAPTER 3. E2D LANGUAGE REFERENCE MANUAL

3.3.11 Set of

set of is the language construct to declare a variable of the type set of somebasic type. For example:

set_of int scores := {1, 8, 10};

3.3.12 The ... Construction

Sets of ordered types (integers and properties) can also define a range within theset, by using lower value...higher value. This can be included with otherelements of the set, for example:

scores += {5...7, 11, 51...99};

3.3.13 Mixed Sets

When the special gamestate variables Properties or Players are on the lefthand side of the expression, special sets, called mixed sets, are allowed on theright hand side at certain points in the code, specifically, at the top of theprogram during definition of properties for the game and in the Init blockwhen defining players. These sets consist of both integers and identifiers, wherethe identifiers are to be reserved from then on to identify a specific player orproperty. For instance, if the set {1...10, hi} was added to Players in Init,the identifier ”hi” would refer to a specific player for the remainder of theprogram.

3.3.14 Casting Rules

There are no explicit typecasts. However, the following typecasts can occur inthe evaluation of certain operators:

• A player to a string (looks up the player’s name)

• A piece to a set of shapes (where the set is just all shapes that made upthe piece)

• An integer to a string (change the value to the digit representation base10 to display)

• A bool to a string (the text ”true” or ”false”, as appropriate)

3.4 Expressions and Statements

Generally, e2d expressions and statements are modeled off of C’s; the syntaxloosely follows K&R C. All statements must be terminated with a ;.

Page 47: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

3.4. EXPRESSIONS AND STATEMENTS 39

3.4.1 Stylistic Conventions valid in this section only

For this section’s examples: [[ and ]] are used to indicate optional parts. (( and)) are used to indicate a choice, with choices separated by |. Note that [[, ]], ((,and )) are not meaningful symbols within e2d and should not be confused with[, ], (, and ).

3.4.2 Boolean Expressions

e2d has an extensive set of expressions which evaluate to boolean values. Theseinclude the expected standard boolean-logical operators and, or, and not andthe standard comparators: =, <, <=, >, >=. e2d further extends these opera-tors with a set of operators based on first order logic.

3.4.3 ”Normal” boolean operators

e2d supports the standard boolean operators to form boolean expressions. Theseare generally similar to C’s boolean operators, except:

• Instead of &&, e2d uses and.

• Instead of ||, e2d uses or.

• Instead of !, e2d uses not.

• There is no ==; e2d uses = for equivalence and := for assignment.

The exact semantics of = can be modified through the use of may and maynot,described below.

3.4.4 Logical Quantifiers

e2d includes logical quantifiers which MUST act similarly to their equivalentsin first order logic: ”forall Type Identifier in Set boolean-expression” and”exists Type Identifier in Set boolean-expression”. Both forall and existsmay modify another boolean expression. For forall, the entire expressionSHALL evaluate to true only if the boolean expression evaluates true for allmembers of the appropriate type in the set. For exists, the entire expressionSHALL evaluate to true only if the boolean expression evaluates to true for atleast one member of the appropriate type in the set.

Additionally, exists may be used without modifying a boolean expression:

exists ((Type Identifier | Identifier)) in Set

This construction MUST evaluate to true if a member of Set is equivalent tothe Identifier (ie, the member of the set = Identifier). If the Identifier has beendeclared here (ie, the Type Identifier construction), it MUST return true if amember of Set is of the same type defined here.

Page 48: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

40 CHAPTER 3. E2D LANGUAGE REFERENCE MANUAL

Within a pattern, these quantifiers MUST have the side effect of defining thematched set for this pattern.

3.4.5 Set membership

e2d includes elementof to test for membership in a set:

Item elementof Set

This expression MUST evaluate to true if and only if Item is a member of theSet.

3.4.6 2d-relational Boolean Operators

e2d also contains some specific boolean-valued operators which model specificpossible relationships between e2d pieces

• overlaps: MUST evaluate to true if and only if one of the argumentsoverlaps the other. If neither piece is on the board (ie, a member of theset Board), then the expression MUST evaluate to false and the programMUST generate a run-time warning.

piece-or-shape overlaps piece-or-shape

• adjacent: MUST evaluate to true if and only if one of the arguments isadjacent to the other. If neither piece is on the board (ie, a member of theset Board), then the expression MUST evaluate to false and the programMUST generate a run-time warning.

piece-or-shape adjacent piece-or-shape

• within: MUST evaluate to true if and only if the left-hand side can becontained within the right-hand side. For most sets, this is equivalent toelementof; however, if Board is the right-hand side, within MUST firstcheck if the left-hand side is elementof Board, then, if that check fails,check if the perimeter of the left-hand side can be fitted within the board.

piece-or-shape within piece-or-shape-set

• attaches: MUST evaluate to true if and only if the left-hand side canattach to the right-hand side. This is evaluated based on the attachmentsection of the piece declaration.

Piece attaches Piece

Page 49: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

3.4. EXPRESSIONS AND STATEMENTS 41

• playable: MUST evaluate to true if and only if its argument can belegally placed on the board. In the case of arbitrarily large boards, theimplementation MAY try for a given upper bound before evaluating theexpression to false; if it does so, a non-fatal runtime error SHOULD begenerated.

playable piece

3.4.7 may flags and equivalence

The may construct modifies the behavior of most piece-relational operators. Theconstruct, and its negation, maynot, can be used to define whether or not piece-relational operations can freely rotate and/or reflect pieces:

may flip_over_x; //allow reflection over x axismay flip_over_y; //as above, with y axismay flip; //allow reflection over either x or y axismay rotate; //allow rotationmaynot flip; //disallow flip// etc.

3.4.8 Flow control expressions

3.4.9 foreach ... in ...

foreach [[Type]] Identifier in Set [loop-command...loop-command

]

MUST run the block of code with Identifier set to each of the elements of Set. Setis some set of one of the given type, and the types must match. This commandis similar to C’s for or a very stripped-down version of Perl’s foreach.

3.4.10 if ... else ...

if(BooleanExpression) [Block of code

] [[ else [Block of code

] ]]

This construct is identical to standard C/Java style if-else statements.

Page 50: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

42 CHAPTER 3. E2D LANGUAGE REFERENCE MANUAL

3.4.11 Pattern calls

PatternName[[(list of arguments)]][[.action]]

e.g. surrounded.kill; above(12).change;

where the pattern call is split into two parts: the pattern to check, and whichaction the pattern should take if it matches (these actions being defined withthe patterns). After completing the pattern and possibly performing an action,the flow of control returns to the caller and the expression evaluates to eithertrue or false, depending on whether or not the pattern matched.

3.4.12 choice

choice [[ Title ]] [ Choice1 : command...command

...ChoiceN : command

...command

]

This construct MUST present a choice to the current player. The implementa-tion MAY choose the exact method of displaying this choice and determiningthe user’s decision (telepathy recommended), but the Title MUST display as atitle or explantation for the choice and the user MUST be able to choose oneand only one of the choices delimited by the Choice1 ... ChoiceN. Once theuser’s input is received, the construct acts similarly to C’s switch statement,executing the commands under that choice label in order. Commands MUSTNOT ”fall through” as in C, and therefore no break is defined.

3.4.13 gameover

gameover

ends the game, jumping immediately to the End loop. gameover is called im-plicitly as the action of pattern end.

3.4.14 Assignment Operators

Identifier := ValueIdentifier += ValueIdentifier -= Value

:= MUST set the value stored by Identifer to Value. Types MUST match, ifnot, a fatal compile-time error MUST be generated. + = and − = have their

Page 51: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

3.4. EXPRESSIONS AND STATEMENTS 43

normal (C) meaning if operating on integers. However, if the Identifier is of aset type, then the Value MUST be added to (or removed from) that set. ValuesMUST be added to the end of the set in order given by the right-hand side topreserve the order of e2d sets. Duplicates may be added. The types MUSTmatch except where casting can occur.

In general, assignment to any of the special game state variables has specialside effects. See the appropriate section for more information on the exactrepercussions of modifying game state variables.

3.4.15 Moving Pieces

move [[Piece]] from Set to Setremove [[Piece]] from Setdraw [[from Set]]play [[from Set]]

draw is simply shorthand for move from Bag to currPlayer.hand and play is justshorthand for move from currPlayer.hand to Board.

For move and remove, if Piece isn’t specified, the current player must choose.The implementation MAY choose how to allow this choice. If Piece is specified,it MUST be an element of the ”from Set”. remove destroys the piece. moveplaces the piece in the ”to Set”. If the ”to Set” is the Board, the player MUSTbe able to choose the location where it goes. Note that play and moves to BoardMUST automatically call pattern legal.

move (and remove) always moves (or removes) the pieces from a bag, hand,or board. For example:

pattern draw_blue[exists piece p in Bag(exists shape s in p

(s.prop = blue));

action choose: draw from matched(p);foreach piece r in matched(p)[ foreach shape t in r[ if s.property = blue[ s.property := white;]

]]

]

Called as draw blue.choose, this will, if there are any pieces with blue in theBag, allow the current player to draw one of them, and change all the remainingblue parts of pieces in the bag to white.

Page 52: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

44 CHAPTER 3. E2D LANGUAGE REFERENCE MANUAL

The effects of move and remove could be achieved through assignments toand from the set, but generally, play, draw, move, and remove are preferred astheir intent is clearer.

Some modifications of game state, such as forcing the location (more thanthe legal pattern already restricts it) requires using the assignment constructsdefined above.

3.4.16 Miscellaneous

3.4.17 print

print (("sequence of ASCII characters"| Identifier | mathematical expession))

[[ + more of the same]]

print MUST display a message to the user; the implementation MAY specifyhow this occurs. print MUST convert Identifiers and mathematical expressionsto an appropriate representation (like the name of a player, or the digits of thenumber), and MAY do this through typecasting to a string.

3.4.18 Randomness

Any set in e2d can be prefixed by the keyword random to select a randomelement from that set (e.g. Turn := random Players;). The implementationMAY choose the method of randomization but MUST preserve the order of theset passed as an argument.

3.5 Declarations

3.5.1 Declaration of User-Defined Pieces

User-defined pieces define a type. The type, which is a set, contains all possibleinstantiations of pieces with the same shape orientation but possibly differentproperties.

The syntax is as follows:

piece PieceName {property-list}[ shape-def prop-def alias-def;shape-spec : shape-def prop-def alias-def ;...shape-spec : shape-def prop-def alias-def;illegal: boolean-expression;attachment: attach-set <-> attach-set;

...attach-set <-> attach-set;

]

Page 53: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

3.5. DECLARATIONS 45

PieceName is an identifier. Property-list is a list of identifiers. All of theseidentifiers are implicitly of type property and scoped only to the definition ofthis piece. These property identifiers can be used later to refer to elements ofthe piece. A shape-def is either a square(int) or a rect(int, int), e.g. square(4) orrect(6,2) for a 4x4 square or a 6x2 rectangle, respectively. prop-def is optional,but expands to ”property x”, where ”x” is an identifier or number that identifiesthe property, or one of the identifiers from property-list. alias-def is optional,and expands to ”alias x”, where ”x” is an identifier that can be used to refer tothat shape within the piece while within the scope of the piece. The first shapedefined in a piece definition is special, and is referred to as the pivot. It deter-mines what the piece rotates around. The center of rotation SHOULD be in thecenter of the shape and the implementation MUST choose some disambiguationwhen rotating around the exact center would create an impossible piece. ThisMAY be some metric like defining the basic grid as 1/2 the unit square.

A shape-spec is a list of the symbols u, d, l, and r, meaning up, down, left,and right respectively. If the list ends in u or d, the programmer can append< or > to justify the added shape to align with the left or right edge of theshape, respectively. Specifying neither requires a centering of the shape. If thisis impossible, the implementation MUST choose a disambiguation. This MAYbe some metric like defining the basic grid as 1/2 the unit square. Similarly,and after r and l specify alignment up and down, and the implementationMUST choose a disambiguation when neither is given and the shape cannot becentered. u and d step by the height of the pivot shape, and l and r step bythe width. Thus a single symbol will always place the shape-def adjacent to thepivot shape. After a shape-spec one can also, instead of specifying a shape-def,specify a whole new block of shape-defs, where the first shape-def in the blockacts as the pivot for that block. For example:

piece test {x, y, z} [ square(2) property x alias B;u> [ square(1) property x;

r: square(1) property y;]

r_: rect(4,1) property z;]

This creates the piece (with squares marked by their property) as follows inASCII art:

xyxx xxzzzz

The declaration of the shapes in a piece is followed by the optional illegal andthe optional attachment. illegal is followed by a boolean-expression whereterminals are expanded to identifiers for properties, which are either names ornumbers. For example:

illegal: (x=y) or (x=z) or (y=z);

Page 54: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

46 CHAPTER 3. E2D LANGUAGE REFERENCE MANUAL

If the illegal expression is true, that combination of properties does not actuallycreate a piece. If the program later tries to refer to such a piece explicitlythe implementation MUST generate a fatal error. attachment is followed bya list of attachments. Attachments define how pieces can fit together. If noattachments are defined, all attachments are valid. The only valid attachmentsare at eight points around a shape, namely, the middle of the right, left, top, andbottom, and the four corners. If attaching at the exact center of the sides createsimpossible configurations, the implementation MUST choose a disambiguation.This MAY be some metric like defining the basic grid as 1/2 the unit square.Each attachment is specified by

alias(corner [, prop]) | all(alias(corner [,prop]) ... ) ...<-> alias(corner [, prop]) | all(alias(corner [,prop]) ... ) ...

where alias is either an alias of a shape within the piece, or the name of anotherpiece declaration followed by a ”.” followed by the alias of some shape in thatpiece. Corner is one of ”ur”, ”u”, ”ul”, ”l”, ”dl”, ”d”, ”dr”, and ”r” which arethe eight attachment points starting at the upper-right corner and proceedinganticlockwise. Prop is an identifier for a property that is only used within theattachment expression to force certain attachments to work only if the propertiesmatch, by requiring they have the same property identifier. all is a keywordin e2d that requires all of the attachment points in the list in parentheses afterall match to count as a successful attachment. < − > is the e2d operatorthat specifies an attachment of its two arguments. When each side is a commadelimited list, < − > is the same as requiring that every element on the right-hand side attaches to every element on the left-hand side. Note that attachmentis symmetric.

3.5.2 Definition of Patterns

Patterns are functions with special properties and syntax. If a pattern is calledby name alone it matches the first-order logical expression and returns a boolthat is the truth value of this expression. An implementation MAY short-circuit this expression. If the pattern is called with an attached action, eitherthe logic doesn’t match and nothing happens, or the logic matches and theaction is executed. Although an implementation MAY short-circuit the booleanlogic, the quantifiers in the first-order logic expression MUST be carried outcompletely to fully create the matched and unmatched sets, which are logicallysets of references into the set they matched or didn’t match. If the sets matchedor unmatched are changed (e.g. by draw, play, move, or remove) the sets fromwhich they are derived change as well.

pattern patternId { pattern-arg-list } (may-flag-list) [FOL-Expression;action ActId: action-command;

...action-command;

Page 55: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

3.6. GAME STATE 47

...action ActId: action-command;

...action-command;

]

patternId is an identifier for the pattern. pattern-arg-list is a list of typedparameters. The may-flag-list is a list of terms of the form may may term ormaynot may term, where may term is one of flip, rotate, flip over x, orflip over y. These terms define which flips and rotates are allowed for thepieces, both in terms of play and equality.

FOL-Expression is an expression in first-order logic, which is boolean logic sup-plemented with forall and exists, which behave logically as the math expressions”for all” and ”there exists” with the side affect that they create two sets indexedby the identifier for the quantified variable, called matched(identifier) andunmatched(identifier) which are all elements of the set that were true andfalse in the expression, respectively. This expression is followed by zero or moreactions, each specified by an identifier. Each action is a series of commands withthe full power of the Turn loop, with the addition of being able to reference thematched and unmatched sets.

3.5.3 Declaring a Variable

All variables declare as

Type Identifier [ := expression] ;

Where Type is any defined type, Identifier is an identifier, and expression issome e2d expression that evaluates to an appropriate value.

3.6 Game State

3.6.1 Global Variables

3.6.2 Properties

This is a global variable of type set of property. It contains all properties,except the default property which MUST be invisible to the program. It MUSTbe initialized to the empty set before any code of the program is run. This setwill never contain the default property. This set should be initialized at thebeginning of the e2d program by assigning mixed sets or individual numbersor identifiers. Since each property has an image, if the program wishes tospecify the image it must also do so here, by putting the property.image onthe left-hand side of an assignment and assigning to it keywords for color orstrings (which MAY be defined by the implementation) or gb(number, number,number) (which MUST be defined by the implementation). Note that after

Page 56: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

48 CHAPTER 3. E2D LANGUAGE REFERENCE MANUAL

creation of a property referred to by a number, for the sake of disambiguation,it must be referenced later as property(Number).

3.6.3 Players

This is a global variable of type set of player. It contains all players in thegame, and it MUST be initialized to the empty set before any code of theprogram is run. This set should never become empty after Init. In this case, aruntime error SHOULD be generated. After creation, referring to a player, inorder to disambiguate, is accomplished by player(Number).

3.6.4 Winners

This is a global variable of type set of player. It contains all the winners ofthe game (note that there may be multiple winners) and after the End loop isfinished this information MUST be conveyed to the user. winners MUST beinitialized to the empty set before any code of the program runs.

3.6.5 Bag

This is a global variable of type set of pieces. The Bag is, logically, all of thepieces that can be drawn by the players. Bag MUST be initialized to the emptyset before any code of the program runs.

3.6.6 Board

This is a global variable of special type. Depending on how it is referenced, it canbe either of type set of shape or of type set of piece. Essentially it matcheswhichever is more specific to what it is being compared to. Logically, it is thepieces that have already been played. Board has data members Board.heightand Board.width which set the size of the board, and can only appear on theleft-hand side of an assignment in Init. If not specified in Init, the Boardis assumed to be infinite where the compiler may choose any sufficiently largevalue for infinity. If these bounds are set, the pattern legal is only true whenplayed pieces fall completely within the bounds of the board.

3.6.7 Turn

Turn is a global variable of type player. Turn only appears on the left-handside of assignment expressions which have special syntax and semantics, sincechanging Turn immediately, as a jump, breaks out of the current turn andstarts the turn of the player to which Turn was set. In addition to the normalassignment, one can also use Turn+=Number or Turn-=Number to shift the turnforward or backward that number of steps, where turn order is determined bytreating Players as a circular queue.

Page 57: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

3.6. GAME STATE 49

3.6.8 currPlayer

currPlayer is a global variable of type player. It cannot appear on the left-hand side of any assignment. It MUST always be equal to the player who’s turnit currently is during the Turn loop or any pattern called from the Turn loop.

3.6.9 currPiece

currPiece is a global variable of type piece. It cannot appear on the left-handside of an assignment. currPiece is always equal to the last piece manipulatedby a move, draw, or play command. It MUST be undefined until the first suchcommand, and the implementation MUST generate an error if it is accessedbefore being defined.

3.6.10 may and maynot

Within Init, may and maynot can be used to specify whether pieces can berotated or flipped. This affects the meaning of certain structures in e2d. Specif-ically, it allows the player on play or move, when the target is Board, to performthe allowed transformations on his piece (e.g. rotate). It also makes the = op-erator between pieces and within be true when the pieces match under allowedtransformations (e.g. rotation).

3.6.11 hide and reveal

Within Init, the programmer can hide and reveal certain features of theGameState, namely Bag and player’s hands. By default, all are hidden. Thevisible or hidden attribute affects whether they can be seen on the GUI, whichMUST show to the player everything that is revealed and nothing that is hidden.Also, draw, move, remove, or play from a hidden location is always uniformlyat random.

3.6.12 The Magic of draw, play, move, and remove

These four commands change pieces in Bag, Board, and player’s hands. draw,play, and move move a piece from one of these sets to another, while removedestroys a piece in one of these sets. draw [from Set] draws a piece to hand,from Bag by default but this can be overridden by ”from”. play [from Set]plays a piece to the Board, from the current player’s hand by default, but thiscan be overridden by ”from”. Anytime any of these four commands moves anunspecified piece from a hidden set (see previous section), the piece is chosenuniformly at random. If the piece is chosen from a revealed set, the currentplayer gets a choice. If a piece is attempted to be moved from an empty set,the implementation MUST generate an error. play always gives the currentplayer the choice of where to place the piece on the board. The more generalversion of draw and play is move, which is of the form move [piece-spec]from Set to Set. Without specifying the piece-spec, play and draw are just

Page 58: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

50 CHAPTER 3. E2D LANGUAGE REFERENCE MANUAL

special cases of move, which acts the same way for moving from hidden orrevealed sets and moving to Board. If the piece is specified in the move, thenthe player has no choice in the piece, although if the ”to set” is Board, theplayer can still get a choice of where to play. If the piece is moved to Board,there exists the construct Board at (coordinate x, coordinate y) to forcethe location where the piece will go. Thus a fully specified move will move apiece without any player interaction. remove is the same as move except thatinstead of moving the piece somewhere it gets destroyed. The magical part isthat if a matched or unmatched set is out of Bag, Board, or a player’s hand, onecan draw, play, move, or remove from these sets and the sets the matched andunmatched came from will be changed as well. For example:

pattern fun [ exists piece p in Bag p.x = property(0);action a1: draw from matched(p);

]

The draw will draw a piece from Bag to hand, but only one that matched (i.e.had property(0)).

3.7 Program Organization

e2d programs MUST be ordered as follows:

3.7.1 Define Properties

The declaration of the Property set MUST occur before any other part of theprogram. The Property list declaration MAY be omitted, but any shape MUSThave the default property if Property does contain any elements.

Property may not be edited after this section finishes. The compiler MUST en-sure that no modification of Property occurs outside of this section, preferablywith a fatal compile error. The Property definition section of any e2d programends at the beginning of the first piece definition.

3.7.2 Define Pieces

Definition of all pieces used in an e2d program MUST follow the addition ofmembers to the Property set, if any occur. If no modification of Propertyoccurs, piece definition MUST be the first section of the e2d program.

Restrictions on the order of piece definitions SHALL NOT be enforced bythe compiler; however, the compiler MUST ensure that any piece type referredto in the attachment section of a piece declaration actually exists. The com-piler MAY choose to do this with a second pass through piece declarations orMAY use any other method, provided that references to invalid or undeclaredpiece definitions are recognized and rejected. References to undefined or invalidpiece types MUST trigger a fatal compile error.

Page 59: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

3.7. PROGRAM ORGANIZATION 51

3.7.3 Shortcut: The .dec file

In order to reduce the number of redundant piece definitions across multiple e2dprograms, e2d allows property and piece declarations to be placed in a separatefile which SHOULD use the extension .dec. The .dec file can be included inan e2d file using the import directive followed by the full or relative path to thefile to be included:

import "file.dec"

The path MAY be interpreted according to the semantics of the host operatingsystem.

The compiler MUST treat an import directive as if the file referenced by thestatement were included inline in the e2d program. The compiler MAY accom-plish this by treating the import construct as a preprocessor action or MAYchoose any other method, provided that the semantics of the statement are pre-served.

Note that these semantics mean that a .dec file may be included after somemodifications to the Property set or after some piece definitions provided thatthe ordering of Property and piece statements are preserved. ProgrammersMAY wish to signify that a .dec file contains only Property modifications orpiece declarations through the following convention:

"file_props.dec" for files which include ONLY Property modifications"file_pieces.dec" for files which include ONLY piece modifications

3.7.4 Define Initial State Values

All initial values of the game state must be initialized within the Init block ofthe e2d program:

Init [init-command...init-command

]

This block MUST be included in any e2d program to ensure that at least oneplayer is added to the game. The compiler MAY issue a compile-time errorif no player is added to the game in this section or MAY allow this to bea runtime error. Any variables declared or values set in this block MUST beglobally scoped. No variables may be scoped locally to Init.

3.7.5 Define Patterns

All patterns for a given e2d program MUST be defined after Init to ensurethat game state elements and global variables used by the patterns are properlyinitialized. The special patterns legal and end MUST be defined in this section.

Page 60: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

52 CHAPTER 3. E2D LANGUAGE REFERENCE MANUAL

Patterns MUST only be defined between the Init and Turn blocks of thee2d programs. Specifications of patterns outside of this region MUST trigger afatal compile-time error.

3.7.6 General Patterns

All general purpose patterns SHALL be defined in this section of the e2d pro-gram. The compiler SHALL NOT place any restrictions on the order of decla-ration of patterns within the program.

3.7.7 Pattern legal

The special pattern legal defines what piece placements are legal within thegame defined by this e2d program. The legal pattern SHALL be automati-cally called whenever a piece is placed on the board through the play or movecommands. This behavior SHOULD NOT require any extra code on the partof the e2d programmer.

The legal pattern MAY include actions, but the automatic legal call afterplay or move MUST NOT trigger any actions.

3.7.8 Pattern end

The special pattern end defines what board configuration automatically causesthe end of the game. When the FOLogcExpr in end evaluates to true. The endpattern SHALL be automatically called at the end of each turn; this behaviorSHOULD NOT require any extra code on the part of the e2d programmer.

The end pattern MAY include actions, but the automatic end call at the end ofa turn MUST trigger an action equivalent to gameover. The action triggeredby the automatic end call SHOULD NOT be defined by the programmer.

3.7.9 Define the Turn

The Turn block is the heart of any e2d program. It MUST follow all patterndefinitions and MUST precede the End block. In general, the Turn block is:

Turn [loop-command...loop-command

]

where loop-command is a choice, flow control statement such as if or foreach,declaration of a local variable, assignment, pattern call, or call to one of the e2d-defined commands like print, play, or draw.

Page 61: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

3.7. PROGRAM ORGANIZATION 53

3.7.10 Turn as a loop

An e2d program executes the commands in Turn repeatedly, for each playerin the order given by the Players set. This behavior MUST be automatic.The turn loop may be terminated and control passed to the End block via thegameover command or when the end pattern matches after one iteration throughTurn.

After each iteration through the Turn block, all variables defined within theTurn block MUST BE automatically removed by e2d and the declarations inTurn are executed again. This means that each iteration of the Turn block hasa fresh copy of all variables. Any variables which must persist across multipleiterations of Turn MUST be declared within global scope. This SHOULD beaccomplished by declaring the variables within Init.

3.7.11 Loop Turn versus game state variable Turn

Execution of the Turn loop may be modified by changing the Turn game statevariable. After modification of the Turn variable, the Turn loop MUST restartat the start of the Turn loop.

3.7.12 Define the End

The End section includes all commands which must be performed at the end ofthe e2d game, such as tabulating scores, determining a winner, and any clean-up. e2d MUST automatically manage storage, so the e2d programmer doesnot need to do any pedantic and silly cleanup tasks such as tracking down andrecovering all memory allocated during the execution of the e2d program. (Anye2d implementation which requires the e2d programmer to think of this sort ofthing MUST be destroyed.)

The End block looks as follows:

End [end-command...end-command

]

3.7.13 End behaviors

end-command can be any of the following: a choice, flow control statementsuch as if or foreach, declaration of a local variable, assignment, booleanexpressions, or a call to print. Patterns MAY NOT be called within End. Aend-command MAY change the game state, except for Turn, which MUSTNOT be modified in End. Most of the e2d-defined commands like play or drawaffect the game state and MAY NOT be called from the End block.

Page 62: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

54 CHAPTER 3. E2D LANGUAGE REFERENCE MANUAL

3.7.14 Winner

After all other commands in End are executed, e2d MUST display a messagedeclaring that all players in the Winners set have won the game. Specific im-plementations MAY choose to pass on this notification in the most appropriateway for the specific implementation.

3.8 Scoping Rules

In general, e2d scopes identifiers to the most specific lexical unit, usually denotedby the [ and ] symbols. This means that variables defined within a given blockare only valid within that block. Code may refer to identifiers in scopes of alexically higher order than its own, but not in any sub-block, as per C. Globalscope is the highest possible scope.

3.8.1 General scoping rules

e2d identifiers SHOULD scope to the current block except for the variablesdeclared in Init. For example, variables defined within Turn may only bereferenced within Turn. Usually a block is delimited by [ and ], but the followinglanguage constructs create their own lexical scope without [ and ] :

• Any statements in the attachment section of a piece definition MUSTreceive their own scope. Each individual statement may include a throw-away property restriction identifier which is specific to that statementalone. To allow the reuse of identifiers here, the statement needs its ownscope.

• Each action in a pattern statement MUST receive its own scope. Eachaction is akin to a different function and needs its own scope for variablesthat may be specific to the given action. Note that each action can stillaccess variables defined in its parent pattern. This ensures that matchedis valid and has the same meaning for each action within a given pattern

• Each labeled section within a choice MUST receive its own scope. Thisallows specific choices to have their own variables if necessary.

3.8.2 Global scope

All items described in game state MUST have global scope in order to be refer-enced elsewhere in the e2d program. Additionally, all variables defined in InitMUST receive global scope. This SHOULD be the only way for variables toreceive global scope.

Page 63: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

3.9. TABLE OF RESERVED KEYWORDS AND SYMBOLS 55

3.8.3 Accessing specific parts of pieces

As with their analogous C structure, struct, individual elements of a piececan be referenced from a specific instance of the piece. If the piece definesan alias for one of its shapes, the shape can be accessed by referring to piecevariable . alias name, e.g. foo.bar. This construct is available wherever apiece could be referenced, which MUST include at least:

• Inside of attachment

• In any section after piece definitions where variables can be declared orforeach can be used.

3.8.4 Namespace collisions

If a new variable uses an identifier that conflicts, i.e., is the same as, an identifierwhich is valid in its scope, the e2d compiler MUST produce a fatal compile-timeerror.

3.9 Table of Reserved Keywords and Symbols

3.9.1 Preprocessor

import

3.9.2 Syntactic Delimiters

[ ]{ }( );:

3.9.3 Types

pieceshapepropertyintplayerboolstring

3.9.4 Game State

PropertiesPlayers

Page 64: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

56 CHAPTER 3. E2D LANGUAGE REFERENCE MANUAL

WinnersBagBoardTurncurrPlayercurrPiece

3.9.5 Data members

(Set).size(player).hand(player).name(piece).loc.x(piece).loc.y(shape).loc.x(shape).loc.y(shape).property(shape).width(shape).heightBoard.widthBoard.height

3.9.6 Assignment

:=+=-=

3.9.7 Math

+-*/

3.9.8 Sets

...,matchedunmatched

3.9.9 Logic

andor

Page 65: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

3.9. TABLE OF RESERVED KEYWORDS AND SYMBOLS 57

notforallexiststruefalse

3.9.10 Logic Predicates

overlapsadjacentwithinattacheselementofplayable=!=<><=>=

3.9.11 Control Flow

foreachinifelsegame_overchoice

3.9.12 Piece Manipulation

joinrotateflip_over_xflip_over_ydrawplayfrommoveremovetoat

Page 66: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

58 CHAPTER 3. E2D LANGUAGE REFERENCE MANUAL

3.9.13 Allowances

maymaynotfliphiderevealhands

3.9.14 Defining Properties

rgb

3.9.15 Defining Pieces

squarerectaliasudlr^_<>urdruldlillegalattachment<->all

3.9.16 Defining Init

Init

3.9.17 Defining Patterns

patternaction

3.9.18 Defining End

End

Page 67: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

3.10. GRAMMAR 59

3.9.19 Randomness

random

3.9.20 Output

print

3.10 Grammar

S->D Init P L

/* Definition of Properties */D -> Prop PiecesProp -> epsilon

| Prop Prop1| Prop Propcol

Prop1 -> Properties += PropDec ;PropDec -> { Elems }

| {}| Elem

Elems -> Elem| Elem , Elems

Elem -> Name| Number| Number ... Number

Propcol -> epsilon| Propcol Propcol1

Propcol1 -> Name.image := Image ;| Property( Number ).image := Image ;

Image -> Name| rgb(Number, Number, Number)

/* Definition of Pieces */Pieces -> Pieces Piecedef

| PieceDefPieceDef -> piece Name Params

[ ShapeSpec ShapeSpecList IllegalList AttachList ]Params -> epsilon

| { ParamList }ParamList -> Name

| ParamList , NameShapeSpec -> square ( MathExprI) SProp SAlias ;

| rect(MathExprI, MathExprI) SProp SAlias;SProp -> epsilon

| property Name

Page 68: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

60 CHAPTER 3. E2D LANGUAGE REFERENCE MANUAL

| property NumberSAlias -> epsilon

| alias NameShapeSpecList -> epsilon

| Sprefix [ ShapeSpec ShapeSpecList ]| Sprefix : ShapeSpec

SPrefix -> DListud Orientud| DListrl Orientrl

DListud -> Udrl DList| u| d

DListrl -> Udrl DList| r| l

Udrl -> u | d | r | lOrientud -> < | > | epsilonOrientrl-> ^|_|epsilonIllegalList -> epsilon | illegal BoolExprIAttachList -> attachment: AttachExprListAttachExprList -> AttachExpr

| AttachExprList AttachExprAttachExpr -> AttachSet <-> AttachSet ;AttachSet -> AttachSet1

| AttachSet , AttachSet1AttachSet1 -> AttachSetId

| all( AttachSetIdList )AttachSetIdList -> AttachSetId

| AttachSetIdList , AttachSetIdAttachSetId -> Name ( AttachLoc AttachProp )

| Name . Name ( AttachLoc AttachProp )AttachLoc -> u | d | r | l | ul | dl | ur | drAttachProp -> epsilon

| , Name| , Number

BoolExprI -> BoolTermI2| BoolExprI or BoolTermI2

BoolTermI2 -> BoolTermI3| BoolTermI2 and BoolTermI3

BoolTermI3 -> BoolTermI4| not BoolTermI3

BoolTermI4 -> true| false| (BoolExprI)| PropExprI

PropExprI -> PropI MathComb PropIPropI -> Name | Number

Page 69: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

3.10. GRAMMAR 61

/* Initializing state of game */Init -> Init [ InitCommands ]InitCommands -> epsilon

| InitCommands InitCommand ;InitCommand -> foreach Type Name in Set [ InitCommands ]

| foreach Name in Set [ InitCommands ]| if BoolExpr [ InitCommands ]| if BoolExpr [ InitCommands ] else [ InitCommands ]| Declaration| Assignment| TurnChange| SetBoardSize| AddPlayerProp| MayCommand| print String| choice [ ChoicesInit ]| choice String [ ChoicesInit ]| HidingStuff

BoolExpr -> BoolTerm2| BoolExpr or BoolTerm2

BoolTerm2 -> BoolTerm3| BoolTerm2 and BoolTerm3

BoolTerm3 -> BoolTerm4| not BoolTerm3

BoolTerm4 -> Predicate| (BoolExpr)

Declaration -> Type Name| Type Name := Call| set_of Type Name| set_of Type Name := Call

Type -> shape| piece| int| property| player| bool| string| Name

TurnChange -> Turn := PlayerCall| Turn += MathExpr| Turn -= MathExpr

Assignment -> Lhs += Rhs| Lhs := Rhs| Lhs -= Rhs

Lhs -> Name

Page 70: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

62 CHAPTER 3. E2D LANGUAGE REFERENCE MANUAL

| Bag| Board| PlayerCall.Name| Winners| Players

Rhs -> Call| Set

Call -> PieceCall| ShapeCall| MathExpr| PropertyCall| PlayerCall| BoolExpr| String

Set -> PieceSet| ShapeSet| MathSet| PropertySet| PlayerSet| BoolSet| StringSet

SetBoardSize -> Board.width := MathExpr| Board.height := MathExpr

AddPlayerProp -> Type player.Name| Type player.Name := Rhs

MayCommand -> may MayTerm| maynot MayTerm

MayTerm -> flip| rotate| flip_over_x| flip_over_y

ChoicesInit -> epsilon| ChoicesInit ChoiceInit

ChoiceInit -> String : InitCommandsHidingStuff -> hide HideTerm

| reveal HideTermHideTerm -> hands

| Bag| PlayerCall.hand

/* Useful expansions */PieceCall -> PieceTerm1

| PieceCall join PieceTerm1PieceTerm1 -> PieceTerm2

| PieceTerm2 rotate MathExprPieceTerm2 -> PieceTerm3

Page 71: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

3.10. GRAMMAR 63

| flip_over_x PieceTerm3| flip_over_y PieceTerm3

PieceTerm3 -> PieceTerm4| PieceTerm4 at PieceLoc

PieceTerm4 -> PieceByName| (PieceCall)

PieceByName -> Name(PropArglist)| currPiece| Board| Name| random PieceSet| ShapeSet| PlayerCall . Name

PropArgList -> epsilon| PropArgList , PropertyCall

PieceLoc -> ( MathExpr , MathExpr )ShapeCall -> Name

| PieceByName. Name| random ShapeSet| PlayerCall . Name

PropertyCall -> Name| property ( Number )| PlayerCall . Name| random PropertySet| ShapeCall . property| PieceByName . Name

PlayerCall -> Name| player ( Number )| random PlayerSet| currPlayer| PlayerCall . Name

String -> StringTerm| String + StringTerm

StringTerm -> Name| Number| StringConst| PlayerCall . Name

MathExpr -> MathTerm1| MathExpr + MathTerm1| MathExpr - MathTerm1

MathTerm1 -> MathTerm2| MathTerm1 * MathTerm2| MathTerm1 / MathTerm2| MathTerm1 % MathTerm2

MathTerm2 -> MathTerm3| - MathTerm2

Page 72: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

64 CHAPTER 3. E2D LANGUAGE REFERENCE MANUAL

MathTerm3 -> Name| Number| PieceByName.loc.x| PieceByName.loc.y| (MathExpr)| PlayerCall.Name| random MathSet| Set.size| ShapeCall.loc.x| ShapeCall.loc.y| Board.width| Board.height| ShapeCall.width| ShapeCall.height

PieceSet -> PieceSet1| PieceSet + PieceSet1

PieceSet1 -> PieceSet2| PieceSet2 * MathExpr

PieceSet2 -> Board| Bag| PlayerCall.hand| {PieceList}| {}| matched( Name )| unmatched( Name )

PieceList -> PieceCall| PieceList , PieceCall

ShapeSet -> ShapeSet1| ShapeSet + ShapeSet1

ShapeSet1 -> {ShapeList}| {}| matched( Name )| unmatched( Name )

ShapeList -> ShapeCall| ShapeList , ShapeCall

MathSet -> MathSet1| MathSet + MathSet1

MathSet1 -> {MathList}| {}| matched( Name )| unmatched( Name )

MathList -> MathSetTerm| MathList , MathSetTerm

MathSetTerm -> MathExpr| MathExpr ... MathExpr

PropertySet -> PropertySet1

Page 73: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

3.10. GRAMMAR 65

| PropertySet + PropertySet1PropertySet1 -> {PropertyList}

| {}| Properties| matched( Name )| unmatched( Name )

PropertyList -> PropertySetItem| PropertyList , PropertySetItem

PropertySetItem -> PropertyCall| PropertyCall ... PropertyCall

PlayerSet -> PlayerSet1| PlayerSet + PlayerSet1

PlayerSet1 -> {PlayerList}| {}| Players| matched( Name )| unmatched( Name )| Winners

PlayerList -> PlayerCall| PlayerList , PlayerCall

StringSet -> StringSet1| StringSet + StringSet1

StringSet1 -> {StringList}| {}| matched( Name )| unmatched( Name)

StringList -> String| StringList , String

BoolSet -> BoolSet1| BoolSet + BoolSet1

BoolSet1 -> {BoolList}| {}| matched( Name )| unmatched( Name )

BoolList -> BoolExpr| BoolList , BoolExpr

/* Defining patterns */P -> Pattern | P PatternPattern -> pattern Name PParams MayList [ FOLogExpr ; ActionList ]PParams -> epsilon

| { PParamsList }PParamsList -> PParam

| PParamsList , PParamPParam -> Type NameMayList -> epsilon

Page 74: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

66 CHAPTER 3. E2D LANGUAGE REFERENCE MANUAL

| (MayList1)MayList1 -> MayCommand

| MayList1 , MayCommand

/* The first-order logical expression within patterns */FOLogExpr -> FOTerm1

| Quantifier FOTerm1Quantifier -> QTerm Type Name in SetQTerm -> forall

| existsFOTerm1 -> FOTerm2

| FOTerm1 or FOTerm2FOTerm2 -> FOTerm3

| FOTerm2 and FOTerm3FOTerm3 -> FOTerm4

| not FOTerm3FOTerm4 -> Predicate

| (FOLogExpr)Predicate -> true

| false| PatternCall| MathCombExpr| PropExpr| PSCall overlaps PSCall| PSCall adjacent PSCall| PSCall within ShapeSet| PSCall within PieceSet| PieceCall attaches PieceCall| Rhs = Rhs| Rhs != Rhs| Call elementof Set| playable PieceCall

PatternCall -> Name(ArgList)| Name

ArgList -> Call| ArgList , Call

MathCombExpr -> MathExpr MathComb MathExprMathcomb -> <

| >| <=| >=| =| !=

PropExpr -> PropertyCall MathComb PropertyCallPSCall -> PieceCall

| ShapeCall

Page 75: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

3.10. GRAMMAR 67

/* The actions within patterns */ActionList -> epsilon

| ActionList ActionAction -> action Name: ActionCommandsActionCommands -> epsilon

| ActionCommands ActionCommand ;ActionCommand -> foreach Type Name in Set [ ActionCommands ]

| foreach Name in Set [ ActionCommands ]| if BoolExpr [ ActionCommands ]| if BoolExpr [ ActionCommands ] else [ ActionCommands ]| Declaration| Assignment| TurnChange| print String| PatternCall . Name| gameover| PieceMove| choice [ ChoicesAction ]| choice String [ ChoicesAction ]

ChoicesAction -> epsilon| ChoicesAction ChoiceAction

ChoiceAction -> String : ActionCommands

/* The main game loop */L -> Loop EndLoop ->Turn [ LoopCommands ]LoopCommands -> epsilon

| LoopCommands LoopCommandLoopCommand -> foreach Type Name in Set [ LoopCommands ]

| foreach Name in Set [ LoopCommands ]| if BoolExpr [ LoopCommands ]| if BoolExpr [ LoopCommands ] else [ LoopCommands ]| Declaration| Assignment| TurnChange| print String| PatternCall . Name| gameover| PieceMove| choice [ ChoicesLoop ]| choice String [ ChoicesLoop ]

PieceMove -> Draw| Play| Move| Remove

Page 76: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

68 CHAPTER 3. E2D LANGUAGE REFERENCE MANUAL

Draw -> draw| draw from Set

Play -> play| play from Set

Remove -> remove PieceByName from Set| remove from Set

Move -> move from Set to Set| move PieceByName from Set to Set

ChoicesLoop -> epsilon| ChoicesLoop ChoiceLoop

ChoiceLoop -> String : LoopCommands

/* What is done when the game ends */End -> epsilon

| End [ EndCommands ]EndCommands -> epsilon

| EndCommands EndCommandEndCommand -> foreach Type Name in Set [ EndCommands ]

| foreach Name in Set [ EndCommands ]| if BoolExpr [ EndCommands ]| if BoolExpr [ EndCommands ] else [ EndCommands ]| Declaration| Assignment| print String| choice [ ChoicesEnd ]| choice String [ ChoicesEnd ]

ChoicesEnd -> epsilon| ChoicesEnd ChoiceEnd

ChoiceEnd -> String : EndCommands

Page 77: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

Chapter 4

Project Plan

Processes Used: We modeled our project around the idea of modular develop-ment: splitting the team into smaller more focused groups. From the beginning,we aimed to have weekly meetings where we touched base and discussed thepending issues with the language. These meetings usually lasted an hour to twohours, and were held in the CS Lounge. Although we often used both a Wikiand Google Group for communication, the face-to-face meetings proved veryuseful for much of the post-whitepaper brainstorming. The main approach todevelopment was modular and incremental design: work from simple, skeletalcode and fill it out with more functionality. At times, the incremental approachbroke down: the e2dCore, for example, was not easily testable until three ofthe most complicated classes in that module were ready. In order to facilitateindependent work on the project, the group split up into sub teams for sectionsof the code based on personal affinity and skills. For example, Luke and Nunziofocused heaviest on the ANTLR code, while Adam and Hugh focused on theGUI, and Jamie, Nunzio, and Adam coordinated the Core code. We tried tokeep teams of at least two people working on each module to ensure that knowl-edge did not become overly compartmentalized. Unfortunately, that goal wasnot entirely realized.

Roles and Responsibilities:

• Jamie Culpon: Project Manager

• Hugh Gordon: Language Editor

• Nunzio Thron: System Architect

• Luqman Skye: System Integrator

• Adam Aviv: Tester

Of course, original responsibilities shifted. In terms of roles played:

• Luke: ANTLR: lexer, parser, treewalker, semantic analyzer

69

Page 78: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

70 CHAPTER 4. PROJECT PLAN

• Nunzio: ANTLR: symbol table, treewalker, code generation/incorporationwith Core. Language guru.

• Jamie: e2dCore, code generation target

• Adam: GUI, GUI Testing

• Hugh: GUI, Core Testing, final report, server admin

Timeline/Project Log

• February 2 Brainstorming w/ 2d games

• January 30 Elections

• February 4 Concept definitions

• February 9 Weekly Meeting/set the core language features of e2d

• February 23 Weekly Meeting

• February 24 Whitepaper cleanup

• February 26 Whitepaper finalization

• February 27 Syntax Draft

• March 2 Weekly Meeting

• March 20-25 LRM and LT Prep/Early Draft

• March 26 e2d CFG Set

• March 27 LRM and LT Editing Party

• March 30 Final Work Assignments/post-editing

• March 31 ”Throw away the first”

• April 5 Prototypes of GUI, Core, and ANTLR on CVS

• April 6 Weekly Meeting

• April 13 Weekly Meeting

• April 17 Presentation Finalization

• April 18 Presentation Revision

• April 20 Weekly Meeting

• April 27 Weekly Meeting

• April 28-29 Prep Code and Testing

• April 30 Final Paper Generation

• May 5 Demo

Page 79: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

Chapter 5

Translator Architecture

As shown above, the architecture uses ANTLR to create a lexer, parser, andtree walker that transformed e2d code into Java code, which called upon anextensive e2d library of core and GUI functions.

71

Page 80: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

72 CHAPTER 5. TRANSLATOR ARCHITECTURE

Page 81: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

Chapter 6

Development Environment

6.1 Introduction

To deliver a quality e2d working system, the various e2d system modules, de-veloped by various members of the team, were integrated into a final product.Integration consisted of defining and maintaining a clear ANTLR-Java interface,a coherent set of coding standards, a suitable platform for development, and aconvenient suite of tools for group relations. Defining and maintaining a clearANTLR-Java interface provided a contract between concurrent ANTLR devel-opment and Java development. A coherent set of coding standards providedimproved code readability and development with fewer errors. Establishing andmaintaining a suitable platform for development provided consistency betweenproject modules in various stages of completeness. Choosing a convenient suiteof tools for group relations provided the resources for effectively combining thework of group members without duplication of code. Integrating the variouscomponents of e2d into a quality final product required clear definitions, vigi-lance, and high-quality tools for maintenance.

6.2 The ANTLR-Java Interface

e2d is a high-level language. The e2d compiler uses Java as a target language. AsJava is an extensible language, by defining classes and interfaces, Java code canbe developed at the level of e2d language constructs. Defining and maintaininga contract between the output of the ANTLR system and the input of theJava system was essential to effectively integrate the primary modules of thesystem. We decided that the output code of our compiler would be readable Javacode. To this end, we developed a set of Java classes, the e2d core classes, thatimplemented the basic constructs used in e2d: piece, shape, property, board,hand, and pattern. These classes provided the interface between our ANTLRcode: the lexer, parser, tree walker, semantic analyzer, and code generator; andour Java code. The core classes were integrated with the GUI using IPC so

73

Page 82: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

74 CHAPTER 6. DEVELOPMENT ENVIRONMENT

that the ANTLR code and the GUI did not need to be directly integrated. Amore detailed description of this interface can be found in the section on e2darchitecture.

6.3 Coding Standards

To make it possible for all members to understand and develop system code,clear coding standards were defined and maintained. Javadoc comments werecreated for all Java code. All code used UML-style naming conventions and aconsistent indentation scheme. Functions were short and embedded in clearly-named classes. Comments were created for any sections of code that could notbe easily understood by reading the code and the Javadoc comments. Becauseof the difficulty of locating ANTLR errors, all ANTLR code lined correspond-ing open and closed braces and corresponding open and closed parentheses inthe same columns. When a section of code remained incomplete, we used theconvention of including clear marker comments explaining the logic that wasyet to be implemented.

6.4 Platform for Development

After experimenting with NetBeans and Emacs, we decided to use Eclipse asour platform for development. Eclipse provides a plug-in for ANTLR devel-opment that identifies a subset of ANTLR errors. Programming in ANTLRremained difficult; e2d ANTLR developers compared programming in ANTLRto programming in assembly language or C before the development of gooderror-detecting compilers. If a programmer were to forget one brace or paren-thesis, the Eclipse platform would likely issue only one error message: at thevery end of the file would be the error message ”unexpected end-of-file.” Locat-ing the line with the error would be difficult and time-consuming. A platformthat provided matching of corresponding open and closed braces and parenthe-ses would have improved the rate of development. None of the platforms weencountered provided this feature for ANTLR code.

We maintained a consistent version of the e2d system on a shared serverrunning CVS. Members would check-out a module of the code, develop it further,and then check-in a stable version of the module. Developers were instructednot to check-in unstable versions that would not integrate with other modulesof the system. CVS provided the ability to undo unstable edits when necessary.Even using CVS, integrating files that members had been developing at thesame time, when developers had made different design decisions, often proveddifficult. Sometimes the best method for integration was to meet in person,examine the code, and through discussion, decide which edits should be keptand which should be abandoned.

Page 83: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

6.5. TOOLS FOR DEVELOPER COORDINATION 75

6.5 Tools for Developer Coordination

We used a Wiki page and a Google group to coordinate the activity of groupmembers. The Wiki page at https://www.coolerweb.com/e2dWiki/index.php,which requires a member login, provided a central repository for our drafts,sketches, and comments. In order for all group members to contribute, wedeveloped our white paper, language reference manual, tutorial, and final reporton the Wiki, converting it to another format only when ready for submission.The Google group, at http://groups.google.com/group/e2d-devel/, provided aconvenient group email list and archive which tracked our progress throughoutthe semester. We posted notes of all group meetings to the group archive.

6.6 Conclusion

Successfully integrating the development activities of team members requiredcode modularization and standardization, a good platform for development, andcommunication. While developing e2d, we established guidelines and providedtools to ease integration of the various components of the system. Even withthese aids, integration was not an easy task. It is very possible that more timeand effort was spent on integration than on development itself. Integrating alarge project is an exciting challenge and a good learning experience.

Page 84: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

76 CHAPTER 6. DEVELOPMENT ENVIRONMENT

Page 85: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

Chapter 7

Test Plan

Testing for this project was a project all on to its own. We broke the testingdown into three sections: testing the generated code, testing the GUI and testingthe core. To test the generated code, we included a large amount of error testingand specific exception generation in the e2d core. First, we compiled code,and then, once it compiled, we ran it, checking the semantics ourselves whileusing exceptions in the core to ensure that our generated code (which extendsthe core) never put the program into an unstable state. If the semantics ofthe game worked and the game never threw an exception, we considered thegenerated code correct. We had a two phase plan to test the core. First,individual programmers wrote test code to test difficult or confusing parts oftheir code rigorously. Then, the testers wrote a test program for each classwhich systematically tested every method in every class going from simple casesto more complicated ones. It should be noted that our tests were not aimed totest the limits of the JAVA environment (i.e. we, for instance, did not see whathappened when we added more than MAX INT number of pieces to a hand)but to test the validity of the e2d language. Testing the GUI was difficult. Aftersearching, we could find no reliable way to generate mouse clicks automatically.So, we tested the GUI ourselves, implementing it in an independent mannerand testing that first before connecting it to the core. It should be noted that,due to significant, unexpected, implementation problems with the attachmentpoints, we have not fully tested our implementation of the e2d compiler.

77

Page 86: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

78 CHAPTER 7. TEST PLAN

Page 87: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

Chapter 8

Conclusions

8.1 Jamie

• Gnat charts are your friend.

• Earlier compiler targets would make life much easier. Coverage Matriceswould’ve been better incorporated earlier in the project, as they would’velikely made some of the later complications appear as needing more timeearlier.

• Clear, concise, and agreed-upon semantics make life a lot easier.

• Next time, require writing sample target language code, rather than justdemonstrating the source language syntax/semantics, for all major lan-guage features.

• Java generics are evil, evil, evil. There is no reason why you shouldn’t beable to override all methods in a generic class, but you can’t. Not evenimportant language features like equals()!

8.2 Adam

I learned that I have the capability to build from a scratch a complex and robustgraphical interface. I have written GUI’s before, but none with the needs forthis project. I put my mind to it, and from the dust, as God created Adam,I created a viable resource. For this, I have great pride. I have also learned alot about working with a group of people, when everyone has different needs atdifferent times. This requires a lot of patience and trust. Patience to wait forwhat you need to get done, and trust that it will be done. One thing for sure, Ihave a lot of trust in everyone in my group, and although my patience has runthin at times, it has never expired. It is an experience I will always remember.

79

Page 88: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

80 CHAPTER 8. CONCLUSIONS

8.3 Nunzio

Work early, work often. Meet as a team, and with your advisor. Also, no matterhow good the idea is on paper, try to test it, at least in your mind, so that theimplementation isn’t impossible.

8.4 Hugh

I learned many things while doing this project. First and foremost, the value ofstrong communication and group planning was revealed to me in a big way. Wecould not have attempted such a big project without our consistent communi-cation. It also became apparent that our product would have been far superiorhad we planned things out more in advance. I also learned that working witha group of all talented people is a difficult proposition. Everyone has strongopinions of what should be done which leads to a lot of religious disputes and alot of potentially wasted time. Programmers are often very individualistic andputting five together is a difficult proposition at best. This became ever moreapparent to me over the course of the semester. Finally, I learned (well, at leastmade a dent in learning) not to overextend myself. I was heavily involved inextracurricular this semester which made it necessary for me to do a very tightbalancing act between my commitments to different groups. While I am gladthat I worked on both projects, it was frustrating for me not to be able to putmy full energies to work on e2d. If I were to give advice to a future team, itwould consist of two main points: First, plan ahead and stick to your plan,keeping in mind that everything will take longer than you think it will. Second,do a small project well; don’t try to do too much in a single semester.

8.5 Luke

Being part of a team designing a large project is an exciting, yet challenging,experience. In order for contributions of ideas and code to make their way intothe final product, it is necessary to work at the team’s pace. Maintaining goodgroup relations is often as important to success as developing good ideas andhigh-quality code.

Serving as the System Integrator provided its own lessons. I learned thatit’s more difficult to read, understand, and correct someone else’s code thanto correct one’s own because of variations in coding styles. Developers havedifferent approaches to code development: some design and develop programsmore methodically, spending less time in error-detection and correction, whileothers prefer to sketch designs quickly in code and then debug. Working withteam members who have different approaches to code development can be agood learning experience. Synchronization, even with CVS, can be difficult andtime-consuming. It’s frustrating to lose large amount of time, work, and codewhen one’s design decisions are different from the design decisions of other teammembers.

Page 89: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

8.6. AS A TEAM 81

I learned that, while one can accomplish a considerable amount with a loom-ing deadline, the quality of the final product would likely be much higher if de-velopment were to start well in advance of deadlines. A regular schedule wouldbe a good aid to high-quality development. I learned that team members usu-ally rise or fall with their team. Most importantly, being part of this group, Ilearned, more than before, that other people play a huge role in the happinessof one’s life and the quality of one’s productivity.

8.6 As A Team

Our team learned a lot. First, we learned that JAVA generics are a deranged,deceptive hack on top of the Java language. Not only do they fail to providethe minimum functionality of templated types, they also break the fundamen-tal contracts of the Java language, making it impossible to effectively overridemethods in subclasses. Generics essentially remove the object-oriented natureof Java. We learned that the various communication tools out there, like Wikisand CVS are wonderful. They save a significant amount of time, especially theWiki for Documentation. We also learned that modular design can be a bighindrance as well as a help: knowledge becomes very compartmentalized whichmakes it hard for team members to help one another. Even with tools likeJavadoc and CVS update notes, it was difficult to work on any code outsideof one’s module. It quickly became apparent that grand ideas for automagiclanguage features (i.e. attachments) are worthless without an early, clear def-inition. We learned, the hard way, that its good to start working in advance;you can’t work well without sleep.

8.7 Our Advice

As far as advice goes, we would like to say shoot high but dont promise morethan you can give. Start early, keep up an even pace during the semester.Realize that making a compiler is a very large project and that there are a lotof things about it that take orders of magnitude more time than you expect.

Page 90: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

82 CHAPTER 8. CONCLUSIONS

Page 91: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

Appendix A

Source Code

A.1 Lexer

/* e2dLexerAuthor: Luqman Skye

*/

class e2dLexer extends Lexer;

options{k=2;charVocabulary=’\u0000’..’\u007F’;

}

STRING : ’"’! (~(’"’|’\n’|’\r’))* ’"’!;ARROW : ’<’ ’-’ ’>’;RANGE : DOT DOT DOT;ASS : ’:’ ’=’;SEMI : ’;’;LPAREN : ’(’;RPAREN : ’)’;LBRACE : ’{’;RBRACE : ’}’;LBRACKET : ’[’;RBRACKET : ’]’;COMMA : ’,’;COLON : ’:’;PLUSEQ : ’+’ ’=’;MINEQ : ’-’ ’=’;PLUS : ’+’;MINUS : ’-’;

83

Page 92: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

84 APPENDIX A. SOURCE CODE

STAR : ’*’;DIV : ’/’;DOT : ’.’;EQ : ’=’;NEQ : ’!’ ’=’;LT : ’<’;GT : ’>’;LTE : ’<’ ’=’;GTE : ’>’ ’=’;ALIGNUP : ’^’;ALIGNDOWN : ’_’;QUOTE : ’"’;NUM : (DIGIT)+;NAME : LETTER (LETTER2 | DIGIT)*;protected LETTER : ’a’..’z’

| ’A’..’Z’;protected LETTER2 : ’a’..’z’

| ’A’..’Z’| ’_’;

protected DIGIT : ’0’..’9’;WS : ( ’ ’

| ’\r’ {newline();}| ’\r’ ’\n’ {newline();}| ’\n’ {newline();}| ’\t’ {newline();}) {$setType(Token.SKIP);};

SL_COMMENT : (’/’ ’/’ (~(’\n’|’\r’))* (’\n’|’\r’(’\n’)?)) {$setType(Token.SKIP); newline();};

ML_COMMENT : ’/’ ’*’(options {generateAmbigWarnings=false;}: { LA(2)!=’/’ }? ’*’| ’\r’ ’\n’ {newline();}| ’\r’ {newline();}| ’\n’ {newline();}| ~(’*’|’\n’|’\r’))* "*/"

{$setType(Token.SKIP);};

A.2 Parser

/* ANTLR grammar for e2dAuthors: Luqman Skye, Nunzio Thron

*/

Page 93: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.2. PARSER 85

header { package e2dParser; import java.util.ArrayList; }

class e2dParser extends Parser; options {k = 4;buildAST=true;

}

tokens {ADDPLPROP; ALIGNMENT; ASSIGNMENT; ATTACHEXP; ATTACHLOC; ATTACHPROP;CALL; CHINITS; CHINIT; CHOICELOOP;DECLARATION; DECS;E2DPROG; END; EXPRESSION; EXPR_FOL; EXPR_OR; EXPR_AND; EXPR_NOT;EXPR_ROTATE; EXPR_FLIP; EXPR_COMPARE; EXPR_ADD; EXPR_MULT;EXPR_UNMINUS; EXPR_PAREN;FOLOGEXPR;IMAGE; IMGNAMEASS; IMGNUMASS; INIT; INITCMDS;LOGIC;MATHCMPEXPR; MAYCMD; MAYCOMMAND; MAYLIST; MAYTERM;PARAMS; PATTERN; PATTERNS; PIECES; PPARAM; PPARAMS;PROPEXPR; PROPIMAGE; PROPNAME; PROPNUM; PROPPLUSEQ; PROPS;QUANTIFIER;SET; SETBSIZE; SHAPE; SHAPES; SIZE; SUBSHAPE;TURN; TURNCH; TURNCOMMANDS; TYPE;

PARAMCALL; NAMECALL; PARAMLIST; ELEMENT;

ATTACHSET; ATTACHID; PROPCOLASS; ADDPLAYERS;}

e2dprog : decs init patterns logic{#e2dprog = #(#[E2DPROG,"e2dprog"],e2dprog);};

decs : props pieces{#decs = #(#[DECS,"decs"],decs);};

props : (proppluseq | propcolass)*{#props = #(#[PROPS,"props"],props);};

proppluseq : "Properties"! PLUSEQ! simpledec SEMI!{#proppluseq = #(#[PROPPLUSEQ,"proppluseq"],proppluseq);};

simpledec : LBRACE! elems RBRACE!| elem;

elems : elem (COMMA! elem)*; elem : NAME^| NUM^ (RANGE^ NUM)?;

propcolass : (NAME DOT! "image"! ASS! NAME SEMI!| "Property"! LPAREN! NUM RPAREN! DOT! "image"! ASS! NAME SEMI!)

{#propcolass = #(#[PROPCOLASS,"propcolass"],propcolass);};pieces : (piecedef)+

{#pieces = #(#[PIECES,"pieces"],pieces);};

Page 94: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

86 APPENDIX A. SOURCE CODE

piecedef : "piece"! NAME^ (params)? LBRACKET! shapes (illegal)?(attach)? RBRACKET!;

params : LBRACE! NAME (COMMA! NAME)* RBRACE!{#params = #(#[PARAMS,"params"],params);};

shapes : shape SEMI! (subshape)*{#shapes = #(#[SHAPES,"shapes"],shapes);};

squaresize: LPAREN! expression RPAREN!{#squaresize = #(#[SIZE,"size"],squaresize);};

rectsize : LPAREN! expression COMMA! expression RPAREN!{#rectsize = #(#[SIZE,"size"],rectsize);};

sprop : "property"^ (NAME|NUM); salias : "alias"^ NAME;subshape : alignment (COLON! shape SEMI! | LBRACKET! shapesRBRACKET!)

{#subshape = #(#[SUBSHAPE,"subshape"],subshape);};alignment : (NAME)+ (LT | GT | ALIGNUP | ALIGNDOWN)?

{#alignment = #(#[ALIGNMENT,"alignment"],alignment);};shape : "square"^ squaresize (sprop)? (salias)?

| "rect"^ rectsize (sprop)? (salias)?;illegal : "illegal"^ COLON! expression SEMI!;

// ATTACHMENTSattach : "attachment"^ COLON! (attachexpr)+;attachexpr : attachset ARROW^ attachset SEMI!;attachset : attachset1 (COMMA! attachset1)*

{#attachset = #(#[ATTACHSET,"attachset"],attachset);};attachset1: attachid | "all"^ LPAREN! attachidlst RPAREN!;attachidlst: attachid (COMMA! attachid)*;attachid : NAME(DOT!NAME)? LPAREN! attachloc (attachprop)? RPAREN!

{#attachid = #(#[ATTACHID,"attachid"],attachid);};attachloc : NAME

{#attachloc=#(#[ATTACHLOC,"attachloc"],attachloc);};attachprop: COMMA! (NAME | NUM)

{#attachprop = #(#[ATTACHPROP,"attachprop"],attachprop);};

// EXPRESSIONexpression: expr_fol

{#expression = #(#[EXPRESSION,"expression"],expression);};expr_fol: (expr_or | quantifier (expr_or)?)

{#expr_fol = #(#[EXPR_FOL,"expr_fol"],expr_fol);};quantifier : qterm type NAME "in"! (namecall | set)

{#quantifier = #(#[QUANTIFIER,"quantifier"],quantifier);};qterm : "forall"^ | "exists"^; expr_or: expr_and ("or"! expr_and)*

{#expr_or = #(#[EXPR_OR,"expr_or"],expr_or);};expr_and: expr_not ("and"! expr_not)*

{#expr_and = #(#[EXPR_AND,"expr_and"],expr_and);};expr_not: ("not")* expr_compare

Page 95: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.2. PARSER 87

{#expr_not = #(#[EXPR_NOT,"expr_not"],expr_not);};expr_compare: (expr_rotate ((GT|LT|GTE|LTE|EQ|NEQ|"overlaps"

|"adjacent"|"attaches"|"elementof") expr_rotate)?| "playable" expr_rotate){#expr_compare = #(#[EXPR_COMPARE,"expr_compare"],expr_compare);};

expr_rotate: expr_flip (("rotate"^) expr_flip)?{#expr_rotate = #(#[EXPR_ROTATE,"expr_rotate"],expr_rotate);};

expr_flip: ("flip_over_x"^|"flip_over_y"^)? expr_add{#expr_flip = #(#[EXPR_FLIP,"expr_flip"],expr_flip);};

expr_add: expr_mult ((PLUS | MINUS) expr_mult)*{#expr_add = #(#[EXPR_ADD,"expr_add"],expr_add);};

expr_mult: expr_unminus ((DIV|MOD|STAR) expr_unminus)*{#expr_mult = #(#[EXPR_MULT,"expr_mult"],expr_mult);};

expr_unminus: (MINUS)* expr_paren{#expr_unminus = #(#[EXPR_UNMINUS,"expr_minus"],expr_unminus);};

expr_paren: call | LPAREN! expression RPAREN!;

// TYPEStype : (type2 | "set_of" type2)

{#type = #(#[TYPE, "type"],type);};type2 : "shape"^ | "piece"^ | "int"^ | "property"^ | "player"^

| "bool"^ | "string"^ | NAME^;call: (element | set)

{#call = #(#[CALL,"call"],call);};element: namecall | paramcall | NUM | STRING | "random" set

{#element = #(#[ELEMENT,"element"],element);};paramcall: NAME LPAREN! paramlist RPAREN! (DOT! NAME)?

{#paramcall = #(#[PARAMCALL,"paramcall"],paramcall);};namecall: (NAME|"Players") (DOT! NAME)*

{#namecall = #(#[NAMECALL,"namecall"],namecall);};set: (LBRACE! (elementlist)? RBRACE!

| "matched"^ LPAREN! NAME RPAREN!| "unmatched"^ LPAREN! NAME RPAREN!)

{#set = #(#[SET,"set"],set);};elementlist: range (COMMA! range)*;range: expression (RANGE^ expression)?;paramlist: expression (COMMA! expression)*

{#paramlist = #(#[PARAMLIST,"paramlist"],paramlist);};

// INITinit : "Init"! LBRACKET! initcmds RBRACKET!

{#init = #(#[INIT,"init"],init);};initcmds : (initcmd)*;initcmd : "foreach"^ (type)? NAME "in"! (namecall|set)

LBRACKET! initcmds RBRACKET!| initifelse

Page 96: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

88 APPENDIX A. SOURCE CODE

| initcmd2 SEMI!;initifelse : "if"^ expression LBRACKET! initcmds RBRACKET! (initelse)?;initelse: "else"^ LBRACKET! initcmds RBRACKET!;initcmd2 : declaration

| ("Players") => addplayers| assignment| maycommand| hidecommand| "print"^ expression;

declaration : type NAME (ASS expression)?{#declaration=#(#[DECLARATION,"declaration"],declaration);};

assignment : namecall (PLUSEQ^ | ASS^ | MINEQ^) expression{#assignment = #(#[ASSIGNMENT,"assignment"],assignment);};

addplayers : "Players"! PLUSEQ! simpledec{#addplayers = #(#[ADDPLAYERS,"addplayers"],addplayers);};

hidecommand : ("hide"^ | "reveal"^) NAME;

// PATTERNSpatterns: (pattern)+

{#patterns = #(#[PATTERNS,"patterns"],patterns);};pattern : "pattern"! NAME^ (pparams)? (maylist)? LBRACKET!

expression SEMI! actionlist RBRACKET!;pparams: LBRACE! pparamslist RBRACE!

{#pparams = #(#[PPARAMS,"pparams"],pparams);};pparamslist : pparam (COMMA! pparam)*;pparam : type NAME

{#pparam = #(#[PPARAM,"pparam"],pparam);};maylist: LPAREN! maylist1 RPAREN!

{#maylist = #(#[MAYLIST,"maylist"],maylist);};maylist1 : maycommand (COMMA! maycommand)*;maytype: "may" | "maynot";mayterm: "flip" | "rotate" | "flip_over_x" | "flip_over_y";maycommand: maytype mayterm

{#maycommand = #(#[MAYCOMMAND,"maycommand"],maycommand);};actionlist: (action)*; action : "action"^ NAME COLON! actioncommands;actioncommands : (actioncommand)*;actioncommand : "foreach"^ (type)? NAME "in"!

(namecall|set) LBRACKET! actioncommands RBRACKET!| actionifelse| actioncommand2 SEMI!;

actioncommand2: declaration | nameassign| "print"^ expression | "gameover" | piecemove;

actionifelse : "if"^ expression LBRACKET! actioncommands RBRACKET! (actionelse)?;actionelse: "else"^ LBRACKET! actioncommands RBRACKET!;nameassign: paramcall | namecall

( (ASS^|PLUSEQ^|MINUSEQ^) expression //left-factoring

Page 97: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.3. TREE WALKER 89

{#nameassign = #(#[ASSIGNMENT,"assignment"],nameassign);}

)?;

// LOGIClogic : turn end {#logic = #(#[LOGIC,"logic"],logic);};turn : "Turn"^ LBRACKET! turncommands RBRACKET!;turncommands : (turncommand)*;turncommand : "foreach"^ (type)? NAME "in"!

(namecall|set) LBRACKET! turncommands RBRACKET!| turnifelse| turncommand2 SEMI!;

turnifelse : "if"^ expression LBRACKET! turncommands RBRACKET! (turnelse)?;turnelse: "else"^ LBRACKET! turncommands RBRACKET!;turncommand2 : declaration | nameassign

| "print"^ expression | "gameover" | piecemove;piecemove : "draw"^ ("from" call)?

| "play"^ ("from" call)?| "remove"^ (call)? "from" call| "move"^ (call)? "from" call "to" call;

end : ("End"^ LBRACKET! endcommands RBRACKET!)?;endcommands : (endcommand)*;endcommand : "foreach"^ (type)? NAME "in"!

(namecall|set) LBRACKET! endcommands RBRACKET!| endifelse| endcommand2 SEMI!;

endifelse : "if"^ expression LBRACKET! endcommands RBRACKET! (endelse)?;endelse: "else"^ LBRACKET! turncommands RBRACKET!;endcommand2 : declaration | assignment

| "print"^ expression | "gameover" | piecemove;

A.3 Tree Walker

/* e2dTreeWalkerAuthors: Luqman Skye, Nunzio Thron

*/

class e2dTreeWalker extends TreeParser;{

int currentline = 0;String errmsg=""; // for holding errors from sa//for holding forall and exists functionsArrayList<String> table_funcs = new ArrayList<String>();ArrayList<String> table_funcArg = new ArrayList<String>();ArrayList<String> table_shapeNames = new ArrayList<String>();

Page 98: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

90 APPENDIX A. SOURCE CODE

ArrayList<e2dAttachType> all_attachments = new ArrayList<e2dAttachType>();ArrayList<e2dPieceCode> piece_code = new ArrayList<e2dPieceCode>();// our symbol tablee2dSymbolTable symbolTable = new e2dSymbolTable();// our functions for semantic analysis using the symbol tablee2dSemanticAnalyzer sa = new e2dSemanticAnalyzer(symbolTable);// the universal propertiesArrayList<String> universalProps = new ArrayList<String>();//flags to determine where we are in codeboolean inInit=false;boolean inPieces=false;

}

e2dprog[String classname] returns [String prog]{ prog=""; String d = "", i = "", p="", l = "";}

: #(E2DPROG d=decs i=init p=patterns l=logic){

prog = "import java.util.ArrayList;\nimport e2dCore.*;"+ "\nimport e2dGUI.*;\nimport java.awt.Color;"+"\n\npublic class "+classname+" extends e2dGame\n{\n" + d+ "\n" + i + "\n" + p+ "\nboolean _gameover=false;\n" + l+ "\n\npublic void _run() throws Exception"+ "\n{\n\t_props();\n\t_pieces();"+ "\n\t_init();\n\tgs.initOver();\n\t"+"changeTurn(gs.getPlayers().get(0));\n\tgs.gameName=\""+classname+"\";\n\t"+"tgt=new GUIe2dInteractor(gs);\n\t"+"_logic();\n\ttgt.tellGameOver(gs.getWinners());\n}\n"+"public static void main(String[] args) "+"throws Exception\n{\n "+classname+" _mg = new "+classname+"();\n_mg._run();\n}\n}\n";

if (errmsg != "")System.err.println(errmsg);

};

decs returns [String decs]{decs=""; String p = "", r = "";}

: #(DECS p=props r=pieces) {decs = p + "\n" + r + "\n";};

props returns [String props]{props="public void _props(){\n"; String p = "";}

: #(PROPS ((p=proppluseq | p=propcolass){props += p;})*

){props+="}\n";};

Page 99: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.3. TREE WALKER 91

proppluseq returns [String proppluseq]{proppluseq=""; String p = "";}

: #(PROPPLUSEQ (#(a:NAME{ proppluseq += "gs.addProperty(\""

+ a.getText() + "\");\n";symbolTable.put(a.getText(),"property");universalProps.add(a.getText());

})|#(b:NUM {proppluseq += "gs.addProperty(\""

+ b.getText() + "\");\n";universalProps.add(a.getText());})

|#(RANGE c:NUM d:NUM{proppluseq += "gs.addPropertyRange("

+ c.getText() + "," + d.getText()+ ");\n";

try{for(int i=Integer.parseInt(c.getText());i<Integer.parseInt(d.getText()); i++)

universalProps.add(""+i);}catch(Exception e){errmsg+="ADDING PROPERTY RANGE:"+"Trying to add non-integers to Properties"+ "as a range\n";}})

)+);

propcolass returns [String propcolass]{propcolass=""; String n="", p="";}

:#(PROPCOLASS (n1:NAME {n=n1.getText();}| n2:NUM {n=n2.getText();}) n3:NAME)

{propcolass = "gs.getPropertyByName(\""+n+"\").setColor(Color."+n3.getText()+");\n";};

pieces returns [String pieces]{pieces=""; inPieces=true;}

: #(PIECES (piece)+){for(e2dPieceCode pc : piece_code){

for(e2dAttachType at : all_attachments){

if(pc.name.equals(at.name)){

Page 100: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

92 APPENDIX A. SOURCE CODE

String x,y,b;x=new String("0.0");y=new String("0.0");b=new String("false");if(at.align.contains("u"))

y=at.shape+".getHeight()-.5";if(at.align.contains("d"))

y="-.5";if(at.align.contains("l"))

x="-.5";if(at.align.contains("r"))

x=at.shape+".getWidth()-.5";if(!(at.prop.equals("")) && at.prop.equals(at.prop2))

b="true";pc.code+="addAttach(\""+at.name+at.shape

+at.align+at.prop+"\","+"\""+at.name2+at.shape2+at.align2+at.prop2+"\","+at.shape+".getOffX(),"+at.shape+".getOffY(),"//offset of attach point in piece+at.shape+".getOffX()+"+x+","+at.shape+".getOffY()+"+y+","+b+");\n"; //true if properties must be the same

}}//now need to add end code to piecepc.code+="}\n}\n";

}//now add all piece code to return stringfor(e2dPieceCode pc : piece_code){

pieces+=pc.code+"\n";}//Now going to generate a function to call// to generate the sets of piecespieces+="\npublic void _pieces()\n{\n";for(e2dPieceCode pc : piece_code){

pieces+=pc.name+" _temp"+pc.name+" = new "+pc.name+"();\n";pieces+=pc.name+" = _temp"+pc.name+"._all()"+(symbolTable.isSet(symbolTable.getType(pc.name))?"":".get(0)")+";\n";

}pieces+="}\n\n";inPieces=false;

};

Page 101: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.3. TREE WALKER 93

piece {e2dPieceCode pc=new e2dPieceCode(); String b="", c="false", construct="";ArrayList<String> a = new ArrayList<String>();table_shapeNames=new ArrayList<String>();}:#(n:NAME (a=params)? b=shapes[0,0,0,0,-1]

(c=illegal)? (attach[n.getText()])?){ if(symbolTable.isType(n.getText()))

errmsg+="ERROR: Redefinition of type "+n.getText();symbolTable.addType(n.getText());pc.name=n.getText();if(a.size()>0){

pc.code += "e2dSet<"+n.getText()+"> "+n.getText()+";\n";//global set of all pieces of this namesymbolTable.add(n.getText(), "set_of "+n.getText());

}else{

pc.code += n.getText() +" "+ n.getText()+";\n";symbolTable.add(n.getText(), n.getText());

}symbolTable.add(n.getText(), (a.size()>0?"set_of ":"")+n.getText());pc.code += "public class "+n.getText()+" extends e2dPiece\n{\n";for(int i=0; i<a.size(); i++){

symbolTable.add("["+n.getText()+"]."+a.get(i), "property");symbolTable.add("[piece]."+a.get(i), "property"); //HACK!pc.code+= ((i==0)?"public e2dProperty ":" , ") + a.get(i);

}if(a.size()!=0)pc.code+=";\n";for(int i=0; i<table_shapeNames.size(); i++){

symbolTable.add("["+n.getText()+"]."+table_shapeNames.get(i), "shape");symbolTable.add("[piece]."+table_shapeNames.get(i), "shape");pc.code+= ((i==0)?"public e2dShape ":" , ")+ table_shapeNames.get(i);

}if(table_shapeNames.size()!=0)pc.code+=";\n";pc.code+="\n";//variables to hold for param changesfor(int i=0; i<a.size(); i++)

pc.code+="ArrayList<e2dShape> _prop_"+a.get(i)+";\n";//functions to update propertiesfor(int i=0; i<a.size(); i++)

pc.code+="public void _set_"+a.get(i)+"(e2dProperty _p)\n{\nfor(int i=0; i<_prop_"+a.get(i)

Page 102: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

94 APPENDIX A. SOURCE CODE

+".size(); i++)\n{\n_prop_"+a.get(i)+".get(i).setProperty(_p);\n}\n}\n";

//function to generate all of these piecespc.code+="public e2dSet<"+n.getText()+"> _all()\n"

+"{\n"+"\te2dSet<"+n.getText()+"> _rvalue = new e2dSet<"+n.getText()+">();\n";

for(int i=0; i<a.size(); i++){

pc.code+="for(e2dProperty _i"+i+" : gs.getProperties() ){\n";}pc.code+="try{_rvalue.add(new "+n.getText()+"(";for(int i=0; i<a.size(); i++){

pc.code+= (i==0?"":",")+"_i"+i;}pc.code+="));}\ncatch(Exception e){}\n";for(int i=0; i<a.size(); i++){

pc.code+="}";}pc.code+="\nreturn _rvalue;\n}\n\n"; //ends function _all//copy constructorpc.code+="public "+n.getText()+"("+n.getText()+" _cp)\n{\nsuper(_cp);\n";pc.code+="for(int i=0; i<shapes.size(); i++)\n{\n";for(int i=0; i<table_shapeNames.size(); i++)

pc.code+="if(_cp."+table_shapeNames.get(i)+"==_cp.shapes.get(i)) "+table_shapeNames.get(i)+"=shapes.get(i);\n";

pc.code+="}\n";for(int i=0; i<a.size(); i++){

pc.code+=a.get(i)+" = _cp."+a.get(i)+";\n_prop_"+a.get(i)+"=new ArrayList<e2dShape>();\n"+"for(int i=0; i<_prop_"+a.get(i)+".size(); i++)\n{\n"+"_prop_"+a.get(i)+".add(_cp._prop_"+a.get(i)+".get(i));\n}\n";

}

pc.code+="}\n\n"; //end copy constructor//constructorif(a.size()>0) //have to create a default constructor

pc.code+="public "+n.getText()+"(){super(gs.getFlags());}\n\n";pc.code+="public "+n.getText()+"(";for(int i=0; i<a.size(); i++){

pc.code+= (i==0?"":",")+"e2dProperty n" + a.get(i);

Page 103: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.3. TREE WALKER 95

}pc.code+=") throws IllegalArgumentException\n{\n\tsuper(gs.getFlags());\n";for(int i=0; i<a.size(); i++){

pc.code+= "\t"+a.get(i)+" = n" + a.get(i) + ";\n"+"_prop_"+a.get(i)+"=new ArrayList<e2dShape>();\n";

}pc.code+=b; //shapes are now addedpc.code+="if("+c+"){throw new IllegalArgumentException();}\n";if(a.size()>0) //have to add constructor call to symbol table{

construct+=n.getText()+"(";for(int i=0; i<a.size(); i++)

construct+=(i==0?"":",")+"[property]";construct+=")";symbolTable.add(construct, n.getText());

}table_shapeNames=new ArrayList<String>(); //clean up//leaving space for attachmentspiece_code.add(pc);

};

params returns [ArrayList<String> params]{params=new ArrayList<String>();String s="";}

: #(PARAMS a:NAME (b:NAME {params.add(b.getText());})*){params.add(0, a.getText());};

shapes[int x, int y, int w, int h, int al] returns [String shapes]{shapes=""; String b="";

e2dShapeReturnType a = new e2dShapeReturnType();}: #(SHAPES a=shape[x,y,w,h,al] {shapes += a.rvalue + "\n";}

(b=subshape[a.x,a.y,a.width,a.height]{shapes += b + "\n"; })*

);

shape[int x, int y, int w, int h, int al] returns [e2dShapeReturnType shape]//NOTE! properties added MUST be called by name{shape=new e2dShapeReturnType(); String a="", b="", c="";ArrayList<String> aa=new ArrayList<String>();}

: #("square" a=squaresize (b=sprop)? (c=salias)?{

shape.width = Integer.parseInt(a);shape.height = Integer.parseInt(a);if(al==0){y+=h-shape.height;}

Page 104: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

96 APPENDIX A. SOURCE CODE

else if(al==2){x+=w-shape.width;}else if(al==5){y+=(h-shape.height)/2;}else if(al==4){x+=(w-shape.width)/2;}shape.x=x;shape.y=y;shape.rvalue = ((c.equals(""))?"":c+" = ")+ "addShape("+new Integer(x)+","+new Integer(y)+","+a+","+a

+ ((b.equals(""))?"":","+b) + ")";if(!b.equals(""))

shape.rvalue="_prop_"+b+".add("+shape.rvalue+");\n";else

shape.rvalue+=";\n";}

)| #("rect" aa=rectsize (b=sprop)? (c=salias)?

{shape.width = Integer.parseInt(aa.get(0));shape.height = Integer.parseInt(aa.get(1));if(al==0){y+=h-shape.height;}else if(al==2){x+=w-shape.width;}else if(al==5){y+=(h-shape.height)/2;}else if(al==4){x+=(w-shape.width)/2;}shape.rvalue = ((c.equals(""))?"":c+" = ") + "addShape("

+new Integer(x)+","+new Integer(y)+","+aa.get(0)+","+aa.get(1)+((b.equals(""))?"":","+b) + ")";

if(!b.equals(""))shape.rvalue="_prop_"+b+".add("+shape.rvalue+");\n";

elseshape.rvalue+=";\n";

});

subshape[int x, int y, int w, int h] returns [String subshape]{subshape="";ArrayList<Integer> a=new ArrayList<Integer>(); int ax, ay;String c = ""; e2dShapeReturnType b = new e2dShapeReturnType();}

: #(SUBSHAPE a=alignment{

ax = x+a.get(0).intValue()*w;ay = y+a.get(1).intValue()*h;

Page 105: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.3. TREE WALKER 97

}(b=shape[ax, ay, w, h, a.get(2)]{subshape=b.rvalue;}

|c=shapes[ax, ay, w, h, a.get(2)]{subshape=c;}

));

squaresize returns [String squaresize]{squaresize=""; e2dProgTypeBall e;}

: #(SIZE e=expression){squaresize += e.prog;

{ try{sa.verifySizeTypes(e.type);}catch(Exception ex){errmsg+=ex.getMessage()+"\n";}

}};

rectsize returns [ArrayList<String> rectsize]{rectsize=new ArrayList<String>(); e2dProgTypeBall e1, e2;}

: #(SIZE e1=expression e2=expression){ rectsize.add(e1.prog);

rectsize.add(e2.prog);try{sa.verifySizeTypes(e1.type); sa.verifySizeTypes(e2.type);}catch(Exception ex){errmsg+=ex.getMessage()+"\n";}

};

sprop returns [String sprop]{sprop="";}

: #("property"(a:NAME {sprop += a.getText();

symbolTable.put(a.getText(),"property");}| b:NUM {sprop += b.getText();}

));

salias returns [String salias]{salias="";}

: #("alias" a:NAME) {salias += a.getText();table_shapeNames.add(a.getText());};

alignment returns [ArrayList<Integer> alignment]{alignment=new ArrayList<Integer>();String bb=""; String recent="";alignment.add(new Integer(0));alignment.add(new Integer(0));}

: #(ALIGNMENT(a:NAME

Page 106: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

98 APPENDIX A. SOURCE CODE

{try{recent = sa.calculateOffset(recent, a.getText(), alignment);}catch(MalformedAlignmentException e){System.err.println(""+e);}}

)+((b:LT{a=b;}|c:GT{a=c;}|d:ALIGNUP{a=d;}|f:ALIGNDOWN{a=f;}){try{recent = sa.calculateOffset(recent, a.getText(), alignment);}catch(MalformedAlignmentException e){System.err.println(""+e);}})?

){if(recent.equals("^"))

{alignment.add(new Integer(0));}else if(recent.equals("<"))

{alignment.add(new Integer(1));}else if(recent.equals(">"))

{alignment.add(new Integer(2));}else if(recent.equals("_"))

{alignment.add(new Integer(3));}else if(recent.equals("u") || recent.equals("d"))

{alignment.add(new Integer(4));}else if(recent.equals("l") || recent.equals("r"))

{alignment.add(new Integer(5));}};

illegal returns [String illegal]{illegal=""; e2dProgTypeBall e;}

: #("illegal" e=expression) {illegal += e.prog;};

// ATTACHMENTSattach[String s] : #("attachment" (attachexpr[s])+);attachexpr[String s]{ArrayList<e2dAttachType> as1 = new ArrayList<e2dAttachType>();

ArrayList<e2dAttachType> as2 = new ArrayList<e2dAttachType>();}: #(ARROW as1=attachset[s] as2=attachset[s]){

e2dAttachType temp;for(e2dAttachType t1 : as1){

for(e2dAttachType t2 : as2){

temp = new e2dAttachType();temp.name = t1.name;temp.shape = t1.shape;temp.align = t1.align;temp.prop = t1.prop;temp.name2 = t2.name;temp.shape2 = t2.shape;temp.align2 = t2.align;temp.prop2 = t2.prop;

Page 107: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.3. TREE WALKER 99

all_attachments.add(temp);

temp = new e2dAttachType();temp.name = t2.name;temp.shape = t2.shape;temp.align = t2.align;temp.prop = t2.prop;temp.name2 = t1.name;temp.shape2 = t1.shape;temp.align2 = t1.align;temp.prop2 = t1.prop;all_attachments.add(temp);

}}

};

attachset[String s] returns[ArrayList<e2dAttachType> attachset]{attachset = new ArrayList<e2dAttachType>();e2dAttachType as=new e2dAttachType();}

: #(ATTACHSET (as=attachset1[s] {attachset.add(as);})+);

attachset1[String name] returns[e2dAttachType attachset1]{attachset1 = new e2dAttachType(); attachset1.name=name;}

:#(ATTACHID p:NAME {attachset1.shape = p.getText();}(p2:NAME {attachset1.name = attachset1.shape;

attachset1.shape = p2.getText();})?#(ATTACHLOC n:NAME {attachset1.align = n.getText();})(#(ATTACHPROP (n1:NAME {attachset1.prop=n1.getText();}

|n2:NUM {attachset1.prop=n2.getText();})))?);

// EXPRESSION

expression returns[e2dProgTypeBall expression]{expression = new e2dProgTypeBall();}

:#(EXPRESSION expression=expr_fol);

expr_fol returns[e2dProgTypeBall expr_fol]{ expr_fol= new e2dProgTypeBall();

e2dProgTypeBall o = new e2dProgTypeBall();e2dProgTypeBall t = new e2dProgTypeBall();e2dProgTypeBall c = new e2dProgTypeBall();String func="", q = "";o.prog="true";

Page 108: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

100 APPENDIX A. SOURCE CODE

}:#(EXPR_FOL ( o=expr_or

{ expr_fol.prog += o.prog;expr_fol.type = o.type;

}| #(QUANTIFIER q=qterm t=type n:NAME (c=namecall|c=set))

{ expr_fol.type = "bool";expr_fol.prog += " _fol."+q+"_"+n.getText()+"("+c.prog+") ";func="public boolean "+q+"_"+n.getText()+"("+sa.typeInJava(c.type)+" _set) throws Exception\n{\n\tboolean _r=";if(q.equals("forall")){func+="true";}else{func+="false";}func+=";\n\tfor("+sa.typeInJava(t.type)

+" "+n.getText()+" : _set)\n\t{\n\t\tboolean _tb = ";

if(symbolTable.inTable(n.getText()))errmsg+="ERROR: redeclaring var "+n.getText()+" in quantified expresson\n";

elsesymbolTable.add(n.getText(), t.type);

}(o=expr_or

{ try{sa.verifyFOLTypes(o.type);}catch(Exception ex){errmsg+=ex.getMessage()+"\n";}

})?{ func+=o.prog+";\n\t\t_r = _r ";if(q.equals("forall")){func+=" && ";}else{func+=" || ";}func+="_tb;\n\t\tif(_tb) _matched_"+n.getText()+".add("+n.getText()+");\n"

+"\t\telse _unmatched_"+n.getText()+".add("+n.getText()+");\n"+"\t}\t\treturn _r;\n}\n";

symbolTable.add("matched("+n.getText()+")", "set_of piece");symbolTable.add("unmatched("+n.getText()+")", "set_of piece");table_funcs.add(func);table_funcArg.add(n.getText());

})

);

qterm returns[String qterm]{qterm="";}

: "forall" {qterm="forall";}| "exists" {qterm="exists";};

Page 109: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.3. TREE WALKER 101

expr_or returns[e2dProgTypeBall expr_or]{expr_or= new e2dProgTypeBall(); e2dProgTypeBall s, o;}

:#(EXPR_OR s=expr_and{ expr_or.prog += s.prog;

expr_or.type = s.type;}

(o=expr_and{ expr_or.prog += " || " + o.prog;

expr_or.type = "bool";try{sa.verifyOrTypes(s.type,o.type);}catch(Exception ex){errmsg+=ex.getMessage()+"\n";}

})*

);

expr_and returns[e2dProgTypeBall expr_and]{expr_and= new e2dProgTypeBall(); e2dProgTypeBall s, o;}

:#(EXPR_AND s=expr_not{ expr_and.prog += s.prog;

expr_and.type = s.type;}

(o=expr_not{ expr_and.prog += " && " + o.prog;

expr_and.type = "bool";try{sa.verifyAndTypes(s.type,o.type);}catch(Exception ex){errmsg+=ex.getMessage()+"\n";}

})*

);

expr_not returns[e2dProgTypeBall expr_not]{expr_not= new e2dProgTypeBall(); e2dProgTypeBall o;}

:#(EXPR_NOT ("not"{ expr_not.prog+="!";

expr_not.type = "bool";})*o=expr_compare{ expr_not.prog += o.prog;

if (expr_not.type.equals("bool")){ try{sa.verifyNotTypes(o.type);}

catch(Exception ex){errmsg+=ex.getMessage()+"\n";}}else expr_not.type = o.type;

Page 110: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

102 APPENDIX A. SOURCE CODE

});

expr_compare returns[e2dProgTypeBall expr_compare]{expr_compare= new e2dProgTypeBall(); e2dProgTypeBall s, o;}

:#(EXPR_COMPARE("playable" s=expr_rotate

{ expr_compare.prog += "playable("+s.prog+")";try{sa.verifyPlayableTypes(s.type);}catch(Exception ex){errmsg+=ex.getMessage()+"\n";}expr_compare.type="bool";

}| s=expr_rotate {expr_compare.prog += s.prog; expr_compare.type=s.type;}

( ( GT o=expr_rotate{ expr_compare.prog += ">" + o.prog;

try{sa.verifyCmpTypes(s.type,o.type,">");}catch(Exception ex){errmsg+=ex.getMessage()+"\n";}

}| LT o=expr_rotate

{ expr_compare.prog += "<" + o.prog;try{sa.verifyCmpTypes(s.type,o.type,"<");}catch(Exception ex){errmsg+=ex.getMessage()+"\n";}

}| GTE o=expr_rotate

{ expr_compare.prog += ">=" + o.prog;try{sa.verifyCmpTypes(s.type,o.type,">=");}catch(Exception ex){errmsg+=ex.getMessage()+"\n";}

}| LTE o=expr_rotate

{ expr_compare.prog += "<=" + o.prog;try{sa.verifyCmpTypes(s.type,o.type,"<=");}catch(Exception ex){errmsg+=ex.getMessage()+"\n";}

}| EQ o=expr_rotate

{if(s.type.equals("int") || s.type.equals("bool"))

expr_compare.prog += "==" + o.prog;else

expr_compare.prog +=".equals("+o.prog+")";try{sa.verifyCmpTypes(s.type,o.type,"==");}catch(Exception ex){errmsg+=ex.getMessage()+"\n";}

}| NEQ o=expr_rotate

{ if(s.type.equals("int") || s.type.equals("bool"))expr_compare.prog += "!=" + o.prog;

else

Page 111: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.3. TREE WALKER 103

expr_compare.prog ="!("+expr_compare.prog+".equals("+o.prog+"))";

try{sa.verifyCmpTypes(s.type,o.type,"!=");}catch(Exception ex){errmsg+=ex.getMessage()+"\n";}

}| "overlaps" o=expr_rotate

{ expr_compare.prog += ".overlaps(" + o.prog+")";try{sa.verifyOverlapsTypes(s.type,o.type);}catch(Exception ex){errmsg+=ex.getMessage()+"\n";}

}| "adjacent" o=expr_rotate

{ expr_compare.prog += ".adjacent(" + o.prog+")";try{sa.verifyAdjacentTypes(s.type,o.type);}catch(Exception ex){errmsg+=ex.getMessage()+"\n";}

}| "attaches" o=expr_rotate

{ expr_compare.prog += ".attaches(" + o.prog+")";try{sa.verifyAttachesTypes(s.type,o.type);}catch(Exception ex){errmsg+=ex.getMessage()+"\n";}

}| "elementof" o=expr_rotate

{ expr_compare.prog = o.prog+".contains("+expr_compare.prog+")";

try{sa.verifyElementOfTypes(s.type,o.type);}catch(Exception ex){errmsg+=ex.getMessage()+"\n";}

}){expr_compare.type = "bool";}

)?)

);

expr_rotate returns[e2dProgTypeBall expr_rotate]{expr_rotate= new e2dProgTypeBall(); e2dProgTypeBall s, o;}

:#(EXPR_ROTATE s=expr_flip {expr_rotate.prog += s.prog; expr_rotate.type=s.type;}( "rotate" o=expr_flip

{ expr_rotate.prog+=".rotate("+o.prog+"/90)";expr_rotate.type = "piece";try{sa.verifyRotateTypes(s.type,o.type);}catch(Exception e){errmsg+=e.getMessage()+"\n";}

})?

);

expr_flip returns[e2dProgTypeBall expr_flip]

Page 112: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

104 APPENDIX A. SOURCE CODE

{ expr_flip= new e2dProgTypeBall();e2dProgTypeBall s;boolean flipx = false;boolean flipy = false;

}:#(EXPR_FLIP ("flip_over_x" {flipx = true;} | "flip_over_y" {flipy = true;})?

s=expr_add{ if (flipx)

{ expr_flip.prog+=s.prog + ".flipX()";expr_flip.type = "piece";try{sa.verifyFlipTypes(s.type);}catch(Exception ex){errmsg+=ex.getMessage()+"\n";}

}else if (flipy){ expr_flip.prog+=s.prog + ".flipY()";

expr_flip.type = "piece";try{sa.verifyFlipTypes(s.type);}catch(Exception ex){errmsg+=ex.getMessage()+"\n";}

}else{ expr_flip.prog = s.prog;

expr_flip.type = s.type;}

});

expr_add returns[e2dProgTypeBall expr_add]{expr_add= new e2dProgTypeBall(); e2dProgTypeBall s, o;}

:#(EXPR_ADD s=expr_mult {expr_add.prog += s.prog; expr_add.type=s.type;}( PLUS o=expr_mult

{ if(symbolTable.isSet(s.type)){

if(symbolTable.isSet(o.type))expr_add.prog+=".addAllR("+o.prog+")";

elseexpr_add.prog+=".addR("+o.prog+")";

}else

expr_add.prog += "+"+o.prog;try{sa.verifyAddTypes(s.type,o.type);}catch(Exception e){errmsg+=e.getMessage()+"\n";}

}| MINUS o=expr_mult

{ if(symbolTable.isSet(s.type)){

if(symbolTable.isSet(o.type))

Page 113: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.3. TREE WALKER 105

errmsg+="SUBTRACTION: Cannot subtract "+ "a set from a set\n";

elseexpr_add.prog+=".removeR("+o.prog+")";

}else

expr_add.prog += "-"+o.prog;try{sa.verifyMinusTypes(s.type,o.type);}catch(Exception e){errmsg+=e.getMessage()+"\n";}

})*

);

expr_mult returns[e2dProgTypeBall expr_mult]{expr_mult= new e2dProgTypeBall(); e2dProgTypeBall s, o;}

:#(EXPR_MULT s=expr_unminus {expr_mult.prog += s.prog; expr_mult.type=s.type;}( DIV o=expr_unminus

{ expr_mult.prog += "/" + o.prog;try{sa.verifyDivTypes(s.type,o.type);}catch(Exception e){errmsg+=e.getMessage()+"\n";}

}| MOD o=expr_unminus

{ expr_mult.prog += "%" + o.prog;try{sa.verifyModTypes(s.type,o.type);}catch(Exception e){errmsg+=e.getMessage()+"\n";}

}| STAR o=expr_unminus

{ try{sa.verifyMultTypes(s.type,o.type);}catch(Exception e){errmsg+=e.getMessage()+"\n";}if(symbolTable.isSet(s.type)) //fun and games{

int count=0;try{count=Integer.parseInt(o.prog);}catch(Exception e){errmsg+="MULTIPLY: Cannot multiply a set "

+ "by a non-constant\n";}String temp = expr_mult.prog;expr_mult.prog

= "((new e2dSet<"+sa.typeInJava2(expr_mult.type.substring(7))+">())";

for(int i=0; i<count; i++)expr_mult.prog+=".addAllR("+temp+")";

expr_mult.prog+=")";}else

Page 114: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

106 APPENDIX A. SOURCE CODE

expr_mult.prog += "*" + o.prog;}

)*);

expr_unminus returns[e2dProgTypeBall expr_unminus]{ expr_unminus= new e2dProgTypeBall();

e2dProgTypeBall s;String a="";

}:#(EXPR_UNMINUS

(p:MINUS { expr_unminus.prog+=p.getText();a="minus";

})*( s=call {expr_unminus.prog+=s.prog; expr_unminus.type=s.type;}| s=expression {expr_unminus.prog+="("+s.prog+")";

expr_unminus.type=s.type;}){ if (a.equals("minus"))

{try{sa.verifyUnminusTypes(s.type);}catch(Exception e){errmsg+=e.getMessage()+"\n";}

}}

);

type returns[e2dProgTypeBall type]{type=new e2dProgTypeBall(); String b,p,e; p=b=e="";}

:#(TYPE ("set_of" {b="e2dSet<";e=">"; type.type="set_of ";})?( "shape" {p="shape"; type.type += "shape";}| "piece" {p="piece"; type.type += "piece";}| "int" {p="int"; type.type += "int";}| "property" {p="property"; type.type += "property";}| "player" {p="player"; type.type += "player";}| "bool" {p="bool"; type.type += "bool";}| "string" {p="string"; type.type += "string";}| n:NAME { p=n.getText();

try {type.type += sa.getType(p);}catch(Exception ex) {errmsg+=ex.getMessage() + "\n";}

})

){type.prog=sa.typeInJava(b+p+e);};

call returns[e2dProgTypeBall call]

Page 115: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.3. TREE WALKER 107

{call=new e2dProgTypeBall();}:#(CALL (call=element | call=set));

element returns[e2dProgTypeBall element]{element=new e2dProgTypeBall(); e2dProgTypeBall st=new e2dProgTypeBall();

e2dProgTypeBall nc=new e2dProgTypeBall(); String s="", p="";}:( n:NUM {element.prog+=n.getText();element.type="int";}

| q:STRING {element.prog+=’\"’+q.getText()+’\"’;element.type="string";}| "random" st=set {element.prog+=st.prog+".random()";

element.type=st.type.substring(7);}| nc=namecall {element = nc;}| nc=paramcall {element = nc;}

);

paramcall returns[e2dProgTypeBall paramcall]{paramcall=new e2dProgTypeBall(); ArrayList<String> pl=new ArrayList<String>();String p="", n="";}

:#(PARAMCALL n1:NAME pl=paramlist {p=pl.get(0);}(n2:NAME {n=n2.getText();p="\""+n2.getText()+"\""+(p.equals("")?"":",")+p;})?){ paramcall.prog = n1.getText()+"("+p+")";

paramcall.type = symbolTable.getType(n1.getText()+"("+pl.get(1)+")"+n);

if(paramcall.type.equals(""))errmsg+="ERROR: Reference to "

+paramcall.prog+" not in symbol table\n";else if(paramcall.type.equals("action")){

if(n2.getText().equals(""))errmsg+="PATTERN-ACTION: Trying to call pattern "

+n1.getText()+" as an action with no action specified\n";else

paramcall.prog="if(!"+n1.getText()+"(\""+n2.getText()+(p.equals("")?"\"":"\",")+p+")return false;";

}if(symbolTable.isNewType(paramcall.type))

paramcall.prog="(new "+paramcall.prog+")";};

paramlist returns[ArrayList<String> paramlist]{paramlist=new ArrayList<String>(); e2dProgTypeBall e=new e2dProgTypeBall();}

:#(PARAMLIST e=expression {paramlist.add(e.prog);paramlist.add("["+e.type+"]");}

(e=expression {paramlist.add(0,paramlist.remove(0)+","+e.prog);

Page 116: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

108 APPENDIX A. SOURCE CODE

paramlist.add(1,paramlist.remove(1)+",["+e.type+"]");})*);

namecall returns[e2dProgTypeBall namecall]{ namecall=new e2dProgTypeBall();

namecall.prog="";String name="", first="", rest="", temp="", temp2="";

}:#(NAMECALL ((n:NAME

{ temp=n.getText();temp2=temp;if(n.getText().equals("Board"))

temp2="gs.getBoard().getPieces()";else if(n.getText().equals("Bag"))

temp2="gs.getBag()";else if(n.getText().equals("Winners"))

temp2="gs.getWinners()";else if(n.getText().equals("Properties"))

temp2="gs.getProperties()";else if(n.getText().equals("currPlayer"))

temp2="gs.getCurrPlayer()";else if(n.getText().equals("currPiece"))

temp2="gs.getCurrPiece()";else if(symbolTable.getType(n.getText()).equals("player"))

temp2="gs.getPlayerByName(\""+n.getText()+"\")";else if(symbolTable.getType(n.getText()).equals("property")

&& universalProps.contains(n.getText()))temp2="gs.getPropertyByName(\""+n.getText()+"\")";

namecall.prog=temp2;name+=n.getText();

})|"Players" {namecall.prog="gs.getPlayers()"; name+="Players";}

)(n2:NAME

{ namecall.prog+="."+n2.getText();name+="."+n2.getText();if(name.equals("Board.width"))

namecall.prog="gs.getBoard().getWidth()";else if(name.equals("Board.height"))

namecall.prog="gs.getBoard().getHeight()";if(first.equals(""))

first = new String(n2.getText());else

rest+="."+new String(n2.getText());}

)*

Page 117: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.3. TREE WALKER 109

){ try{namecall.type=sa.getType(name);}

catch(Exception e){errmsg+=e.getMessage() + "\n";}if(namecall.type.equals("action")){

int index = namecall.prog.indexOf(".");if(index==-1)

errmsg+="PATTERN-ACTION: Patterncall "+namecall.prog+" attempted without specifying an action\n";

else{

String str = new String(namecall.prog);namecall.prog="if(!"+str.substring(0,index)+"(\""

+str.substring(index+1,str.length())+"\"))return false;";

}}else if(symbolTable.getType(temp).equals("piece")

&& (first.equals("loc_x")||first.equals("loc_y"))){

namecall.prog=temp+".get"+(first.equals("loc_x")?"X":"Y")+"()";}else if(symbolTable.getType(temp).equals("piece") && !first.equals("")){//fun case with class casts

String type = sa.typeInJava(symbolTable.getType("[piece]."+first));if(type.equals("int")){

if(!rest.equals(""))errmsg+="ERROR: int has no data members";

namecall.prog="((Integer)("+temp2+".getClass().getField(\""+first+"\").get("+temp2+"))).intValue()";

}else if(type.equals("bool")){

if(!rest.equals(""))errmsg+="ERROR: bool has no data members";

namecall.prog="((Boolean)("+temp2+".getClass().getBoolean(\""+first+"\").get("+temp2+"))).boolValue()";

}else

namecall.prog="(("+type+")("+temp2+".getClass().getField(\""+first+"\").get("+temp2+")))"+rest;

if(rest.equals(""))namecall.temp= temp2+".getClass().getField(\""

Page 118: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

110 APPENDIX A. SOURCE CODE

+first+"\").set("+temp2+",";}

};

set returns[e2dProgTypeBall set]{ set=new e2dProgTypeBall("","");

e2dProgTypeBall e1=new e2dProgTypeBall();e2dProgTypeBall e2=new e2dProgTypeBall();String type="";

}:#(SET ((e1=expression {if(type.equals("")){type=e1.type;

set.prog+="(new e2dSet<"+sa.typeInJava2(type)+">())";}}(#(RANGE e2=expression)

{ try{sa.verifyRangeTypes(e1.type,e2.type);}catch(Exception e){errmsg+=e.getMessage() + "\n";}

})?

{ if(e2.prog.equals("")) {set.prog+=".addR("+e1.prog+")";}else {errmsg+="ERROR: Cannot add a range to a general set";}try {sa.verifySameType(e1.type,type);}catch (Exception e) {errmsg += e.getMessage() + "\n";}

})+|#("matched" n:NAME {set.prog="_fol._matched_"

+n.getText(); type="piece";if(!symbolTable.getType("matched("

+n.getText()+")").equals("set_of piece"))

errmsg+="MATCHED: Either no matched of name "+n.getText()+" or not of type set_of piece\n";})

|#("unmatched" n2:NAME {set.prog="_fol._unmatched_"+n2.getText();type="piece";

if(!symbolTable.getType("unmatched("+n2.getText()+")").equals("set_of piece"))

errmsg+="UNMATCHED: Either no unmatched of name "+n2.getText()+" or not of type set_of piece\n";

})))

{set.type="set_of " + type;};

//INIT!init returns[String init]

Page 119: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.3. TREE WALKER 111

{init=""; String c, t=""; inInit=true;}:#(INIT (c=initcmd {t+="\t"+c+"\n";}

)*){init="public void _init()\n{\n" + t +"}\n"; inInit=false;};

initcmd returns[String initcmd]{ initcmd="";

e2dProgTypeBall t = new e2dProgTypeBall();e2dProgTypeBall c, e, a;String i="", i2="", nw="";String cmds="", cmds2="";String ass="";

}:#("foreach" (t=type)? n:NAME (c=namecall|c=set)

{ // verify foreachtry {sa.verifyForEachTypes(t.type, n.getText(), c.type);}catch (Exception ex) {errmsg += ex.getMessage() + "\n";}nw=n.getText();if(c.type.equals("piece")

&& symbolTable.getType(nw).equals("shape"))c.prog="("+c.prog+").getShapes()";

}(i=initcmd {cmds+="\t"+i+"\n";})*

){ initcmd+="for("+t.prog+" "+nw+":"+c.prog+")\n{\n"+cmds+"}\n";}

| #("if" e=expression(i=initcmd {cmds+="\t"+i;})*( #("else"

(i2=initcmd {cmds2+="\t"+i2;})*

))?

) {initcmd="if("+e.prog+")\n{\n"+cmds+"}\nelse\n{\n"+cmds2+"}\n";}| ass=print {initcmd=ass;}| ass=declaration {initcmd=ass;}| ass=assignment {initcmd=ass;}| ass=maycommand {initcmd=ass;}| ass=hidecommand {initcmd=ass;}| ass=addplayers {initcmd=ass;};

hidecommand returns[String hidecommand]{hidecommand="";}

:#("hide" n:NAME

Page 120: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

112 APPENDIX A. SOURCE CODE

{if(n.getText().equals("hands"))

hidecommand="gs.hideHands();";else if(n.getText().equals("Bag"))

hidecommand="gs.hideBag();";else if(n.getText().equals("Board"))

hidecommand="gs.hideBoard();";else

errmsg+="HIDE: Cannot hide "+n.getText()+"\n";})

|#("reveal" n2:NAME{

if(n2.getText().equals("hands"))hidecommand="gs.revealHands();";

else if(n2.getText().equals("Bag"))hidecommand="gs.revealBag();";

else if(n2.getText().equals("Board"))hidecommand="gs.revealBoard();";

elseerrmsg+="HIDE: Cannot reveal "+n.getText()+"\n";

});

print returns [String print]{print=""; e2dProgTypeBall e = new e2dProgTypeBall();}

:#("print" e=expression){ try {sa.verifyStringTypes(e.type, e.prog);}

catch (Exception ex) {errmsg += ex.getMessage() + "\n";}print="tgt.print("+e.prog+");";

};

declaration returns[String declaration]{declaration = ""; e2dProgTypeBall t=new e2dProgTypeBall();e2dProgTypeBall e=new e2dProgTypeBall();}

:#(DECLARATION t=type n2:NAME (ASS e=expression)?){declaration=t.prog+" "+n2.getText() + "=";symbolTable.add(n2.getText(), t.type);if(e.prog.equals("")){

if(t.type.equals("int"))declaration+="0";

else if(t.type.equals("bool"))declaration+="true";

else

Page 121: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.3. TREE WALKER 113

declaration+="new "+sa.typeInJava(t.type)+"()";}else

declaration+=e.prog;declaration+=";";};

assignment returns[String assignment]{ assignment=""; e2dProgTypeBall rhs, lhs; String op="";}

:#(ASSIGNMENT( #(k:PLUSEQ lhs=namecall rhs=expression) {op=k.getText();}| #(l:MINEQ lhs=namecall rhs=expression) {op=l.getText();}| #(m:ASS lhs=namecall rhs=expression) {op="=";}) {

//special cases firstif(!lhs.temp.equals("")){

if(rhs.type.equals("int"))rhs.prog="(new Integer("+rhs.prog+"))";

else if(rhs.type.equals("bool"))rhs.prog="(new Boolean("+rhs.prog+"))";

if(op.equals("="))assignment=lhs.temp+rhs.prog+");";

else if(op.equals("+=")) //NOT TYPE-CHECKEDassignment=lhs.temp+lhs.temp+"+"+rhs.prog+")";

else if(op.equals("-="))assignment=lhs.temp+lhs.temp+"-"+rhs.prog+")";

}else if(lhs.prog.equals("gs.getBoard().getHeight()"))

assignment="gs.getBoard().setHeight("+rhs.prog+");";else if(lhs.prog.equals("gs.getBoard().getWidth()"))

assignment="gs.getBoard().setWidth("+rhs.prog+");";else if(lhs.prog.equals("gs.getPlayers()")){

assignment="gs.addPlayer(new e2dPlayer(\""+rhs.prog+"\"));";}else if(lhs.prog.equals("gs.getBag()")){

if(op.equals("+="))assignment="gs.addPiece"

+(symbolTable.isSet(rhs.type)?"s":"")+"ToBag("+rhs.prog+");";

elseerrmsg+="ASSIGNMENT: Cannot use operation other than"

" += with Bag as lhs\n";}

Page 122: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

114 APPENDIX A. SOURCE CODE

else if(lhs.prog.equals("Turn")){

if(op.equals("=")){

if(rhs.type.equals("player"))assignment="changeTurn("+rhs.prog+");"

+(inInit?"":"return false;");else

errmsg+="TURNCHANGE: Cannot assign a non-player"+ " to variable Turn\n";

}else{

if(rhs.type.equals("int"))assignment="changeTurn("

+(op.equals("-=")?"-(":"(")+rhs.prog+"));"+(inInit?"":"return false;");

elseerrmsg+="TURNCHANGE: Cannot increment or decrement"

+ " Turn by a non-int\n";}

}else{

try {sa.legalAssignment(lhs.type,rhs.type);}catch (Exception e) {errmsg += e.getMessage() + "\n";}

if(symbolTable.isSet(lhs.type)){

if(symbolTable.isSet(rhs.type)){

if(op.equals("+="))assignment=lhs.prog+".addAll("+rhs.prog+");";

else if(op.equals("="))assignment=lhs.prog+" = "+rhs.prog+";";

elseerrmsg+="ERROR: Cannot subtract sets from sets\n";

}else{

if(op.equals("+="))assignment=lhs.prog+".add("+rhs.prog+");";

else if(op.equals("="))errmsg+="ERROR: Cannot assign "+rhs.type+" to "

+lhs.type+"\n";

Page 123: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.3. TREE WALKER 115

else //op is -=assignment=lhs.prog+".remove("+rhs.prog+");";

}}else{

if(op.equals("="))assignment=lhs.prog+op+rhs.prog+";";

else if(op.equals("-=")){

if(rhs.type.equals("int"))assignment=lhs.prog+" -= "+rhs.prog+";";

elseerrmsg+="ERROR: Cannot use -= on "+rhs.type+"\n";

}else if(op.equals("+=")){

if(rhs.type.equals("int") || rhs.type.equals("string"))assignment=lhs.prog+" += "+rhs.prog+";";

elseerrmsg+="ERROR: Cannot use += on "+rhs.type+"\n";

}}

}}

);

addplayers returns [String addplayers]{addplayers="";}

:#(ADDPLAYERS(#(a:NAME

{ addplayers += "gs.addPlayer(\"" + a.getText() + "\");\n";symbolTable.put(a.getText(),"player");

})

|#(b:NUM {addplayers += "gs.addPlayer(\"" + b.getText() + "\");\n";})|#(RANGE c:NUM d:NUM

{addplayers += "gs.addPlayerRange(" + c.getText() + ","+ d.getText() + ");\n";})

)+);

// PATTERNSpatterns returns[String patterns]{patterns=""; String m="", a="", act="", temp="", entry="";ArrayList<String> acts = new ArrayList<String>();

Page 124: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

116 APPENDIX A. SOURCE CODE

table_funcs=new ArrayList<String>();ArrayList<String> actname = new ArrayList<String>();e2dProgTypeBall e = new e2dProgTypeBall();e2dSymbolTable tempSymTab;ArrayList<e2dProgTypeBall> p = new ArrayList<e2dProgTypeBall>();}

:#(PATTERNS (#(n:NAME {tempSymTab=new e2dSymbolTable(symbolTable);acts = new ArrayList<String>();actname = new ArrayList<String>();table_funcs = new ArrayList<String>();table_funcArg = new ArrayList<String>();}

(p=pparams)? (m=maylist)? e=expression// verify expression is of bool type{ try {sa.verifyPatternTypes(e.type);}

catch (Exception ex) {errmsg += ex.getMessage() + "\n";}}

(#("action" k:NAME (temp=actioncommand {act+=temp;})*{acts.add("if(_s.equals(\""+k.getText()+"\"))\n{\n"

+act+"}\n");actname.add(k.getText());})

)*){ entry=new String(n.getText());patterns+="public boolean "+n.getText()+"(String _s";for(int i=0; i<p.size(); i++){

patterns+=","+p.get(i).prog+")\n{\n";entry+=(i==0?"(":",")+"["+p.get(i).type+"]"

+(i==p.size()-1?")":"");}patterns+=") throws Exception\n{\n";symbolTable.add(entry, "bool");patterns+="final class _FolClass\n{\n";for(int i=0; i<table_funcArg.size(); i++){

patterns+="e2dSet<e2dPiece> _matched_"+table_funcArg.get(i)+";\n"+"e2dSet<e2dPiece> _unmatched_"+table_funcArg.get(i)+";\n";

}patterns+="public _FolClass()\n{\n";for(int i=0; i<table_funcArg.size(); i++){

Page 125: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.3. TREE WALKER 117

patterns+="\t_matched_"+table_funcArg.get(i)+" =new e2dSet<e2dPiece>();\n"+"\t_unmatched_"+table_funcArg.get(i)+" =new e2dSet<e2dPiece>();\n";

}patterns+="}\n";for(int i=0; i<table_funcs.size(); i++){

patterns+=table_funcs.get(i);}patterns+="\n}\n\t_FolClass _fol = new _FolClass();\n"+"\tgs.setTempFlags();\n"+m+"\n"+"\tboolean rvalue=( "+e.prog+" );\n"+"\tgs.resetFlags();\n"+"\tif(!_s.equals(\"\"))\n{\n"+"\tif(rvalue)\n\t{\n";for(int i=0; i<acts.size(); i++){

patterns+=acts.get(i);tempSymTab.add(entry+"."+actname.get(i), "action");

}patterns+="\t}\n"+"return true;\n}\n"//return true here since now have taken action so semantics// of rvalue are different+"\treturn(rvalue);\n}\n\n";symbolTable = tempSymTab;//reset symbol table for closing scopesa = new e2dSemanticAnalyzer(symbolTable);

})+

);

maylist returns[String maylist]{maylist=""; String m="";}

:#(MAYLIST (m=maycommand {maylist+=m;})+);maycommand returns[String maycommand]{maycommand="";}

:#(MAYCOMMAND ("may"("flip" {maycommand="gs.getFlags().mayFlip();\n";}|"rotate" {maycommand="gs.getFlags().mayRotate();\n";}|"flip_over_x" {maycommand="gs.getFlags().mayFlipX();\n";}|"flip_over_y" {maycommand="gs.getFlags().mayFlipY();\n";})

|"maynot"("flip" {maycommand="gs.getFlags().mayNotFlip();\n";}

Page 126: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

118 APPENDIX A. SOURCE CODE

|"rotate" {maycommand="gs.getFlags().mayNotRotate();\n";}|"flip_over_x" {maycommand="gs.getFlags().mayNotFlipX();\n";}|"flip_over_y" {maycommand="gs.getFlags().mayNotFlipY();\n";})

));

pparams returns[ArrayList<e2dProgTypeBall> pparams]{pparams=new ArrayList<e2dProgTypeBall>(); e2dProgTypeBall p;}

:#(PPARAMS (p=pparam {pparams.add(new e2dProgTypeBall(p.prog,p.type));})+);pparam returns[e2dProgTypeBall pparam]{pparam=new e2dProgTypeBall(); e2dProgTypeBall t=new e2dProgTypeBall();}

:#(PPARAM t=type n:NAME) {pparam.prog+=t.prog+" "+n.getText();pparam.type=t.type;};

//pattern actionsactioncommand returns[String actioncommand]{actioncommand=""; e2dProgTypeBall t = new e2dProgTypeBall();e2dProgTypeBall c = new e2dProgTypeBall();String i="", i2="", cmds="", cmds2="", nw="";e2dProgTypeBall e = new e2dProgTypeBall();}

:#("foreach" (t=type)? n:NAME (c=namecall | c=set){ // verify foreach

try {sa.verifyForEachTypes(t.type, n.getText(), c.type);}catch (Exception ex) {errmsg += ex.getMessage() + "\n";}nw=n.getText();if(c.type.equals("piece")

&& symbolTable.getType(nw).equals("shape"))c.prog="("+c.prog+").getShapes()";

}(i=actioncommand {cmds+="\t"+i+"\n";})*

) {actioncommand+="for("+t.prog+" "+nw+":"+c.prog+")\n{\n"+cmds+"}\n";}| #("if" e=expression

// verify expression is of bool type{ try {sa.verifyIfTypes(e.type);}

catch (Exception ex) {errmsg += ex.getMessage() + "\n";}}(i=actioncommand {cmds+="\t"+i;})*( #("else"

(i2=actioncommand {cmds2+="\t"+i2;})*

))?

) {actioncommand="if("+e.prog+")\n{\n"+cmds+"}\nelse\n{\n"+cmds2+"}\n";}| (c=paramcall|c=namecall) {actioncommand+=c.prog;}

Page 127: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.3. TREE WALKER 119

| i=assignment {actioncommand+=i;}| i=declaration {actioncommand+=i;}| i=print {actioncommand+=i;}| i=piecemove {actioncommand+=i;}| "gameover" {actioncommand+= "_gameover=true; return false;";};

piecemove returns [String piecemove]{piecemove="";

e2dProgTypeBall c = new e2dProgTypeBall();e2dProgTypeBall f = new e2dProgTypeBall();e2dProgTypeBall t = new e2dProgTypeBall();f.prog=c.prog=t.prog="";

}:#("draw" ("from" f=call

// verify that f is a set type{ try{sa.verifySetTypes(f.type);}

catch(Exception ex){errmsg+=ex.getMessage()+"\n";}}

)?{piecemove="draw("+f.prog+");";})

|#("play" ("from" f=call// verify that f is a set type{ try{sa.verifySetTypes(f.type);}

catch(Exception ex){errmsg+=ex.getMessage()+"\n";}}

)?{piecemove="play("+f.prog+");";})

|#("move" (c=call {c.prog+=",";})? "from" f=call "to" t=call){ piecemove="move("+c.prog+f.prog+","+t.prog+");";

// verify that f and t are set types of the same type{ try{sa.verifyMoveSameSetTypes(f.type, t.type);}

catch(Exception ex){errmsg+=ex.getMessage()+"\n";}}

}|#("remove" (c=call {c.prog+=",";})? ("from" f=call)? ("to" t=call)?)

{ piecemove="remove("+c.prog+f.prog+","+t.prog+");";// verify that f and t are set types of the same type{ try{sa.verifyMoveSameSetTypes(f.type, t.type);}

catch(Exception ex){errmsg+=ex.getMessage()+"\n";}}

};

// LOGIClogic returns[String logic]{logic=""; String t = "", s = "";}

:#(LOGIC t=turn s=end)

Page 128: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

120 APPENDIX A. SOURCE CODE

{logic="public void _logic() throws Exception\n"+"{\nwhile(!end(\"\") && !_gameover)\n{\n"+"\tif(! _turn()) break;\n}\n\n"+s+"}\n"+"public boolean _turn() throws Exception\n{\n"+t+"changeTurn(1); return true;\n}\n";

};

turn returns[String turn]{turn=""; String o="", a="";}

:#("Turn" (o=turncommand {a+="\t"+o+"\n";})*

) {turn=a;};

turncommand returns[String turncommand]{turncommand=""; e2dProgTypeBall t = new e2dProgTypeBall();e2dProgTypeBall c = new e2dProgTypeBall();String i="", i2="", cmds="", cmds2="", nw="";e2dProgTypeBall e = new e2dProgTypeBall();}

:#("foreach" (t=type)? n:NAME (c=namecall | c=set){ // verify foreach

try {sa.verifyForEachTypes(t.type, n.getText(), c.type);}catch (Exception ex) {errmsg += ex.getMessage() + "\n";}nw=n.getText();if(c.type.equals("piece")

&& symbolTable.getType(nw).equals("shape"))c.prog="("+c.prog+").getShapes()";

}(i=turncommand {cmds+="\t"+i+"\n";})*

) {turncommand+="for("+t.prog+" "+nw+":"+c.prog+")\n{\n"+cmds+"}\n"; }| #("if" e=expression

// verify expression is of bool type{ try {sa.verifyIfTypes(e.type);}

catch (Exception ex) {errmsg += ex.getMessage() + "\n";}}(i=turncommand {cmds+="\t"+i;})*( #("else"

(i2=turncommand {cmds2+="\t"+i2;})*

))?

) {turncommand="if("+e.prog+")\n{\n"+cmds+"}\nelse\n{\n"+cmds2+"}\n";}| (c=paramcall|c=namecall) {turncommand+=c.prog;}| i=assignment {turncommand+=i;}| i=declaration {turncommand+=i;}

Page 129: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.4. SEMANTIC ANALYZER 121

| i=print {turncommand+=i;}| i=piecemove {turncommand+=i;}| "gameover" {turncommand+= "gameover=true; return false;";};

end returns[String end]{end="";String o="", a="";}

:#("End" (o=endcommand {a+=o+"\n";})*

) {end=a;};

endcommand returns[String endcommand]{endcommand=""; e2dProgTypeBall t = new e2dProgTypeBall();e2dProgTypeBall c = new e2dProgTypeBall();String i="", i2="", cmds="", cmds2="", nw="";e2dProgTypeBall e = new e2dProgTypeBall();}

:#("foreach" (t=type)? n:NAME (c=namecall | c=set){ // verify foreach

try {sa.verifyForEachTypes(t.type, n.getText(), c.type);}catch (Exception ex) {errmsg += ex.getMessage() + "\n";}nw=n.getText();if(c.type.equals("piece")

&& symbolTable.getType(nw).equals("shape"))c.prog="("+c.prog+").getShapes()";

}(i=endcommand {cmds+="\t"+i+"\n";})*

) {endcommand+="for("+t.prog+" "+nw+":"+c.prog+")\n{\n"+cmds+"}\n";}| #("if" e=expression

(i=endcommand {cmds+="\t"+i;})*( #("else"

(i2=endcommand {cmds2+="\t"+i2;})*

))?

) {endcommand="if("+e.prog+")\n{\n"+cmds+"}\nelse\n{\n"+cmds2+"}\n";}| c=paramcall {endcommand+=c.prog;}| i=assignment {endcommand+=i;}| i=declaration {endcommand+=i;}| i=print {endcommand+=i;}| i=piecemove {endcommand+=i;};

A.4 Semantic Analyzer

package e2dParser;

Page 130: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

122 APPENDIX A. SOURCE CODE

import antlr.*;import antlr.collections.*;import antlr.debug.misc.ASTFrame;import java.util.ArrayList;

/*** Semantic Analyzer for e2d* @author Luqman Skye**/

public class e2dSemanticAnalyzer {public e2dSemanticAnalyzer(e2dSymbolTable st){

symtab = st;}

/** the symbol table being used by the tree walker */private e2dSymbolTable symtab;

/** list(0) is left and right, list(1) is up and down** @param prev string of previous offset symbol, only one!* @param s string of offset or alignment symbols* @return last udlr^_<> char* @throws MalformedAlignmentException*/public String calculateOffset(String prev, String s, ArrayList<Integer> l)throws MalformedAlignmentException, IllegalArgumentException{

String rvalue = prev,c;Integer t;//prev should only be a single character at mostif(prev.length()>1){throw new IllegalArgumentException("argument prev cannot be more than one character");}

for(int i=0; i<s.length(); i++){

if(prev.equals("^")||prev.equals("_")||prev.equals(">")||prev.equals("<")){

throw new MalformedAlignmentException("Double alignments");}c=s.substring(i,i+1);if(c.equals("u")){

Page 131: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.4. SEMANTIC ANALYZER 123

t = l.remove(1);l.add(1, new Integer(t.intValue()+1));

}else if(c.equals("d")){t = l.remove(1);l.add(1, new Integer(t.intValue()-1));

}else if(c.equals("l")){t = l.remove(0);l.add(0, new Integer(t.intValue()-1));

}else if(c.equals("r")){t = l.remove(0);l.add(0, new Integer(t.intValue()+1));

}else if(c.equals("^")){if(rvalue.equals("u") || rvalue.equals("d")){throw new MalformedAlignmentException("Alignment doesn’t match preceding term");}

}else if(c.equals("_")){if(rvalue.equals("u") || rvalue.equals("d")){throw new MalformedAlignmentException("Alignment doesn’t match preceding term");}

}else if(c.equals("<")){if(rvalue.equals("l") || rvalue.equals("r")){throw new MalformedAlignmentException("Alignment doesn’t match preceding term");}

}else if(c.equals(">")){if(rvalue.equals("l") || rvalue.equals("r")){throw new MalformedAlignmentException("Alignment doesn’t match preceding term");}

}else{throw new MalformedAlignmentException("Illegal alignment character");

}rvalue = c;

}

return rvalue;}

/*** Ensures that last offset symbol is compatible with alignment symbol* @param name string of offset symbols* @param alignchar alignment symbol* @throws Exception*/public void alignment_aligncompat(String name, String alignchar)throws Exception{

Page 132: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

124 APPENDIX A. SOURCE CODE

if (alignchar != "<" && alignchar != ">" && alignchar!= "^" && alignchar != "_")

throw new Exception("ERROR: alignment character must be <, >, ^, or _. found "+ alignchar);

else if (((alignchar.equals("<") || alignchar.equals(">"))&& name.charAt(name.length()-1) != ’d’&& name.charAt(name.length()-1) != ’u’)

|| ((alignchar.equals("^") || alignchar.equals("_"))&& name.charAt(name.length()-1) != ’r’&& name.charAt(name.length()-1) != ’l’))

throw new Exception("ERROR: alignment character "+ alignchar+ " does not match offset character"+ name.charAt(name.length()-1));

}

/*** Returns the type of name in the symbol table* @param name* @return the type of name* @throws Exception when name is not in the symbol table*/public String getType(String name) throws Exception{

String retVal = symtab.getType(name);if (retVal.equals("")) throw new Exception("getType: name " + name+ " not in symbol table");return retVal;

}

/*** Verifies that name1 and name2 have the same type* @param name1* @param name2* @throws Exception if name1 and name2 do not have the same type*/public void verifySameType(String name1, String name2) throws Exception{

if (symtab.getType(name1) != symtab.getType(name2))throw new Exception ("ERROR: " + name1 + " and " + name2+ " do not have the same type");

}

/*** Checks if can assign (t1:=t2) or (t1+=t2) or (t1-=t2)

Page 133: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.4. SEMANTIC ANALYZER 125

* @param t1 lhs of assignment* @param t2 rhs of assignment* @throws Exception thrown when assignment is impossible*/public void legalAssignment(String t1, String t2) throws Exception{

boolean good=false;if(t1.equals(t2)) good=true;if(t1.equals("set_of "+t2)) good=true;if(t1.equals("piece") && symtab.isNewType(t2)&& !symtab.isSet(t2)) good=true;if(t1.equals("set_of piece") && symtab.isNewType(t2)) good=true;if(!good) throw new Exception("ERROR: Cannot assign "+t2+" to "+t1);

}

/*** Takes an e2d type and converts it into the Java type* @param t name of type to change* @return name of type in Java*/public String typeInJava(String t){

String rvalue = new String(t);if(symtab.isSet(t))

rvalue = "e2dSet<"+typeInJava(t.substring(7,t.length()))+">";else if(t.equals("piece"))

rvalue="e2dPiece";else if(t.equals("shape"))

rvalue="e2dShape";else if(t.equals("player"))

rvalue="e2dPlayer";else if(t.equals("property"))

rvalue="e2dProperty";else if(t.equals("int"))

rvalue="int";else if(t.equals("bool"))

rvalue="boolean";else if(t.equals("string"))

rvalue="String";return rvalue;

}

/*** Type in Java, only extended types* @param t string of the type* @return string of type in Java

Page 134: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

126 APPENDIX A. SOURCE CODE

*/public String typeInJava2(String t){

String rvalue = new String(t);if(symtab.isSet(t))

rvalue = "e2dSet<"+typeInJava(t.substring(7,t.length()))+">";else if(t.equals("piece"))

rvalue="e2dPiece";else if(t.equals("shape"))

rvalue="e2dShape";else if(t.equals("player"))

rvalue="e2dPlayer";else if(t.equals("property"))

rvalue="e2dProperty";else if(t.equals("int"))

rvalue="Integer";else if(t.equals("bool"))

rvalue="Boolean";else if(t.equals("string"))

rvalue="String";return rvalue;

}

/*** Verifies that operands of / have correct types* @param type1* @param type2* @throws Exception if type1 and type2 are not appropriate for /*/public void verifyDivTypes(String type1, String type2) throws Exception{if (type1 != "int" || type2 != "int")

throw new Exception("DIV(/): both arguments must be of type int");}

/*** Verifies that operands of % have correct types* @param type1* @param type2* @throws Exception if type1 and type2 are not appropriate for %*/public void verifyModTypes(String type1, String type2) throws Exception{if (type1 != "int" || type2 != "int")

throw new Exception("MOD(%): both arguments must be of type int");}

Page 135: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.4. SEMANTIC ANALYZER 127

/*** Verifies that operands of * have correct types* @param type1* @param type2* @throws Exception if type1 and type2 are not appropriate for **/public void verifyMultTypes(String type1, String type2) throws Exception{if ((type1 != "int" && !type1.startsWith("set_of")) || type2 != "int")

throw new Exception("MULT(*): either both arguments must be of type int "+ "or the first argument must be a set and the second argument an int");

}

/*** Verifies that operands of + have correct types* @param type1* @param type2* @throws Exception if type1 and type2 are not appropriate for +*/public void verifyAddTypes(String type1, String type2) throws Exception{if ( !(type1.equals("int") && type2.equals("int"))

&& !(type1.equals("string") && type2.equals("string"))&& !(type1.startsWith("set_of") && type2.startsWith("set_of"))

)throw new Exception("ADD(+): both arguments to+ must have the same type: either int, string, or set.");

}

/*** Verifies that operands of - have correct types* @param type1* @param type2* @throws Exception if type1 and type2 are not appropriate for -*/public void verifyMinusTypes(String type1, String type2) throws Exception{if (type1 != "int" || type2 != "int")

throw new Exception("MINUS(-): both arguments to- must be of type int");

}

/*** Verifies that operand of playable has correct type* @param type

Page 136: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

128 APPENDIX A. SOURCE CODE

* @throws Exception if type is not appropriate for playable*/public void verifyPlayableTypes(String type) throws Exception{if (!(type.equals("piece") || symtab.isNewType(type)))

throw new Exception("PLAYABLE: argument must be of type piece");}

/*** Verifies that relational operator has correct operand types* @param type* @throws Exception if types do not match or cannot be compared*/public void verifyCmpTypes(String type1, String type2, String cmp)throws Exception{if (!cmp.equals("==") && !cmp.equals("!=")) // cmp does not test equality{

if ( !(type1.equals("int") && type2.equals("int"))&& !(type1.equals("string") && type2.equals("string"))

)throw new Exception("CMP: both arguments to " + cmp+ " must have the same type: either int or string.");

}else if (!type1.equals(type2))

throw new Exception("CMP: both arguments to " + cmp+ " must have the same type (trying to compare "+type1+" to "+type2+")");

}

/*** Verifies that operands have correct types* @param type1* @param type2* @throws Exception if types don’t match*/public void verifyOverlapsTypes(String type1, String type2) throws Exception{

if (!type1.equals("piece") || !type2.equals("piece"))throw new Exception("OVERLAPS: both arguments must be of type piece");

}

/*** Verifies that operands have correct types* @param type1* @param type2

Page 137: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.4. SEMANTIC ANALYZER 129

* @throws Exception if types don’t match*/public void verifyAdjacentTypes(String type1, String type2) throws Exception{

if (!type1.equals("piece") || !type2.equals("piece"))throw new Exception("ADJACENT: both arguments must be of type piece");

}

/*** Verifies that operands have correct types* @param type1* @param type2* @throws Exception if types don’t match*/public void verifyAttachesTypes(String type1, String type2) throws Exception{

if (!type1.equals("piece") || !type2.equals("piece"))throw new Exception("ATTACHES: both arguments must be of type piece");

}

/*** Verifies that operands have correct types* @param type1* @param type2* @throws Exception if types don’t match*/public void verifyElementOfTypes(String type1, String type2) throws Exception{

if (type1.equals(type2.substring(7)))throw new Exception("ELEMENT_OF: first argument must have the type "

+ " of which the second argument is a set");}

/*** Verifies that operand has correct type* @param type* @throws Exception if type not boolean*/public void verifyNotTypes(String type) throws Exception{

if (!type.equals("bool"))throw new Exception("NOT: argument to not must be of type bool");

}

/*** Verifies that operand has correct type

Page 138: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

130 APPENDIX A. SOURCE CODE

* @param type1* @param type2* @throws Exception if types not boolean*/public void verifyAndTypes(String type1, String type2) throws Exception{

if (!type1.equals("bool") || !type2.equals("bool"))throw new Exception("AND: argument to and must be of type bool");

}

/*** Verifies that operand has correct type* @param type1* @param type2* @throws Exception if types not boolean*/public void verifyOrTypes(String type1, String type2) throws Exception{

if (!type1.equals("bool") || !type2.equals("bool"))throw new Exception("OR: argument to or must be of type bool");

}

/*** Verifies that operand has correct type* @param type* @throws Exception if type not boolean*/public void verifyFOLTypes(String type) throws Exception{

if (!type.equals("bool"))throw new Exception("FOL: predicate of first-order logical"+" expression must be of type bool");

}

/*** Verifies that operand has correct type* @param type* @throws Exception if type not integer*/public void verifySizeTypes(String type) throws Exception{

if (!type.equals("int"))throw new Exception("SIZE: size must be of type int not" + type);

}

Page 139: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.4. SEMANTIC ANALYZER 131

/*** Verifies that operand of unminus is of type int* @param type* @throws Exception if type is not int*/public void verifyUnminusTypes(String type) throws Exception{if (!type.equals("int"))

throw new Exception("UNMINUS: operand must be of type int not " + type);}

/*** Verifies that name of pattern call is a pattern* @param name* @throws Exception if name is not a pattern*/public void verifyPatternCallTypes(String name) throws Exception{if (!symtab.getType(name).equals("pattern"))

throw new Exception("PATTERNCALL: name must be of type pattern");}

/*** Verifies that ranges are int types* @param type1* @param type2* @throws Exception if types are not int*/public void verifyRangeTypes(String type1, String type2) throws Exception{if (!type1.equals("int") || !type2.equals("int"))

throw new Exception("RANGE: end points of range must be of type int not "+ type1 + " and " + type2);

}

/*** Verifies that type is a "set_of" type* @param type* @throws Exception if type is not a "set_of" type*/public void verifyForEachTypes(String type) throws Exception{if (!type.startsWith("set_of"))

throw new Exception("FOREACH: elements must come from set type not "+ type);

}

Page 140: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

132 APPENDIX A. SOURCE CODE

/*** Verifies that this is a valid foreach statement,* and adds name to symbol table* if it’s not already there* @param type type (empty if no type declared)* @param name variable that each element is taking* @param set set varable is taking values over, should be of type t* @throws Exception if not a valid foreach statement*/public void verifyForEachTypes(String type, String name, String set)throws Exception{

if(type.equals("")){

type = symtab.getType(name);if(type==null)

throw new Exception("FOREACH: attempt to reference "+name+" which is not yet defined");

}else{

if(symtab.inTable(name))throw new Exception("FOREACH: attempt to redeclare "+name);

elsesymtab.add(name, type);

}if(!symtab.isSetOf(set, type) && !set.equals("piece")&&!type.equals("shape"))

throw new Exception("FOREACH: attempt to treat "+type+" as elements of "+set);

}

/*** Verifies that type is a "set_of" type* @param type* @throws Exception if type is not a "set_of" type*/public void verifySetTypes(String type) throws Exception{if (!type.startsWith("set_of"))

throw new Exception("SET: elements must come from set type not "+ type);

}

/**

Page 141: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.4. SEMANTIC ANALYZER 133

* Verifies that type is a "bool" type* @param type* @throws Exception if type is not a "bool" type*/public void verifyPatternTypes(String type) throws Exception{if (!type.equals("bool"))

throw new Exception("PATTERN: expression must evaluate to a bool not "+ type);

}

/*** Verifies that type is a "bool" type* @param type* @throws Exception if type is not a "bool" type*/public void verifyIfTypes(String type) throws Exception{if (!type.equals("bool"))

throw new Exception("IF: expression to if-statement must evaluate to a bool not "+ type);

}

/*** Verifies that sets are both of the same type* @param type1* @param type2* @throws Exception if types are not set types* or if they are different set types*/public void verifyMoveSameSetTypes(String type1, String type2)throws Exception{if (!type1.startsWith("set_of") || !type1.equals(type2))

throw new Exception("PIECEMOVE: from and to set types must both be sets of the same type. "+ "Instead they were of types " + type1 + " and " + type2);

}

/*** Verifies that type is of type string* @param type* @param string* @throws Exception if type is not string*/

Page 142: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

134 APPENDIX A. SOURCE CODE

public void verifyStringTypes(String type, String string) throws Exception{if(!(type.equals("string")))

throw new Exception("ERROR: Cannot print ["+string+"] because it’s not a string\n");

}

/*** Verifies that type1 is a piece and type2 is an int* @param type1* @param type2* @throws Exception*/public void verifyRotateTypes(String type1, String type2) throws Exception{if(!(type1.equals("piece")) || !(type2.equals("int")))

throw new Exception("ROTATE: LHS must be a piece and RHS must be an int. "+ "Found LHS: " + type1 + " and RHS: " + type2 + "\n");

}

/*** Verifies that type is a piece* @param type* @throws Exception*/public void verifyFlipTypes(String type) throws Exception{if(!type.equals("piece"))

throw new Exception("FLIP: Only pieces can be flipped, not "+ type + "\n");

}}

A.5 Front-End Return Types and Exceptions

A.5.1 e2dAttachType

package e2dParser;

public class e2dAttachType {String name="";String shape="";String align="";String prop="";

Page 143: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.5. FRONT-END RETURN TYPES AND EXCEPTIONS 135

String name2="";String shape2="";String align2="";String prop2="";

}

A.5.2 e2dPieceCode

package e2dParser;

public class e2dPieceCode {String name="";String code="";

}

A.5.3 e2dProgTypeBall

package e2dParser;

/*** Return class combining program and type* @author Luqman Skye**/

public class e2dProgTypeBall {e2dProgTypeBall(){}e2dProgTypeBall(String p, String t) {prog = p; type=t;}public String prog="";public String type="";public String temp="";

}

A.5.4 e2dShapeReturnType

package e2dParser;

/*** A return type for shapes in tree walker so that* we can move by more than 1 unit at a time* @author nt2039**/

public class e2dShapeReturnType {public String rvalue="";public int width=0;

Page 144: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

136 APPENDIX A. SOURCE CODE

public int height=0;public int x=0;public int y=0;

}

A.5.5 MalformedAlignmentException

package e2dParser;

public class MalformedAlignmentException extends Exception {

/****/private static final long serialVersionUID = -1040613263084206921L;

public MalformedAlignmentException(){super();}

public MalformedAlignmentException(String msg){super(msg);}

}

A.6 e2dCore

A.6.1 e2dAttachPoint

package e2dCore;

/*** Class for storing e2d attachment points. Currently, the e2d compiler* does not correctly generate these points and this class is not useful.* @author nt**/

public class e2dAttachPoint {private String srcAttach;private String destAttach;private int shapeOffX, shapeOffY;private double pointOffX, pointOffY;private boolean prop;

/*** Create a new attachment point

Page 145: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 137

* @param me A unique encoding of this attachment point* @param you A unique encoding of this attachment* rule’s partner attachment point* @param sox The x-offset from the origin piece* of the shape used in this attachment* @param soy The y-offset from the origin piece of* the shape used in this attachment* @param pox Floating-point encoding of the x coordinate of the corner of the* attachment point* @param poy Floating-point encoding of the y coordinate of the corner of the* attachment point.* @param p Boolean value telling if the properties of the shapes* involved in this* attachment must be valid.*/public e2dAttachPoint(String me, String you, int sox, int soy,

double pox, double poy, boolean p){

srcAttach = new String(me);destAttach = new String(you);shapeOffX = sox;shapeOffY = soy;pointOffX = pox;pointOffY = poy;prop = p;

}

/*** Copy constructor. Makes a new instance of an AttachPoint based* off the given one* @param a attach point to copy*/public e2dAttachPoint(e2dAttachPoint a){

srcAttach = new String(a.srcAttach);destAttach = new String(a.destAttach);shapeOffX = a.shapeOffX;shapeOffY = a.shapeOffY;pointOffX = a.pointOffX;pointOffY = a.pointOffY;prop = a.prop;

}

/*** Get this attachment point’s source encoding* @return unique encoding of this attachment point rule

Page 146: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

138 APPENDIX A. SOURCE CODE

*/public String getSourceAttach(){

return srcAttach;}

/*** Get this attachment point’s destination encoding* @return unique string corresponding to some other attachment point*/public String getDestAttach(){

return destAttach;}

/*** Get the offset from the origin of the piece of the shape invoved in this* attachment* @return x coordinate*/public int getShapeOffX(){

return shapeOffX;}

/*** Get the offset from the origin of the piece of the shape invoved in this* attachment* @return y coordinate*/public int getShapeOffY(){

return shapeOffY;}

/*** Get the corner of the shape involved in this attachment* @return x coordinate*/public double getCornerX(){

return pointOffX;}

/*** Get the corner of the shape involved in this attachment

Page 147: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 139

* @return y coordinate*/public double getCornerY(){

return pointOffY;}

public boolean propsMustMatch(){

return prop;}

/*** Adjust this attachment point for rotation counterclockwise**/public void rotateL(){

int ti = shapeOffX;shapeOffX = -shapeOffY;shapeOffY = ti;

double tf = pointOffX;pointOffX = -pointOffY;pointOffY = tf;

}

/*** Adjust this attachment point for rotation clockwise**/public void rotateR(){

int ti = shapeOffX;shapeOffX = shapeOffY;shapeOffY = -ti;

double tf = pointOffX;pointOffX = pointOffY;pointOffY = -tf;

}

/*** Adjust this attachment point for reflection over the horizontal axis**/

Page 148: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

140 APPENDIX A. SOURCE CODE

public void flipX(){

shapeOffY = -shapeOffY;pointOffY = -pointOffY;

}

/*** Ajust this attachment point for reflection over the vertical axis**/public void flipY(){

shapeOffX = -shapeOffX;pointOffY = -pointOffY;

}

public void setCornerX(double x){

pointOffX = x;}public void setCornerY(double y){

pointOffY = y;}

}

A.6.2 e2dBasicShape

package e2dCore;

import java.awt.Color; import java.awt.Graphics;

/*** The basic unit of our implementation of e2d: a 1x1 square with a property** @author jlc, aja (draw)**/

public class e2dBasicShape {

/* offsett from orgin basic shape */

protected int offX;

protected int offY;

Page 149: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 141

protected e2dProperty prop;

protected int boardX;

protected int boardY;

protected boolean onBoard = false;

/*** Constructor used by e2dShape to generate its basic shapes** @param xx* the x value of the basic shape* @param yy* the y value of the basic shape* @param p* the property of the top shape called to the basic shape*/public e2dBasicShape(int xx, int yy, e2dProperty p){

boardX = offX = xx;boardY = offY = yy;

prop = p;

}

/*** Copy the given basic shape** @param b*/public e2dBasicShape(e2dBasicShape b){

offX = b.offX;offY = b.offY;

boardX = b.boardX;boardY = b.boardY;prop = b.prop;

}

/****************************************************************************** Acessors****************************************************************************/

Page 150: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

142 APPENDIX A. SOURCE CODE

/*** method returns basicShapes x value** @return value of x*/public int getOffX(){

return offX;}

/*** method returns basicShapes offset y value** @return value of offY*/public int getOffY(){

return offY;}

/*** returns basicShape’s x location on the board** @return*/public int getBoardX(){

return boardX;}

/*** returns basicShape’s y location on the board** @return*/public int getBoardY(){

return boardY;}

/*** method returns the e2dProperty of the basic shape** @return the e2dProperty of the basic shape*/

Page 151: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 143

public e2dProperty getProp(){

return prop;}

/*** method sets the x value of the basic shape** @param xx* value to set x to*/public void setOffX(int xx){

offX = xx;}

/*** method sets the y value of the basic shape** @param yy* value to set y to*/public void setOffY(int yy){

offY = yy;}

/*** sets the board location of the basic shape** @param xx*/public void setBoardX(int xx){

boardX = xx;}

/*** sets the board location of the basic shape** @param yy*/public void setBoardY(int yy){

boardY = yy;}

Page 152: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

144 APPENDIX A. SOURCE CODE

/*** method that sets the property of the basic shape** @param p* the property to set prop to*/public void setProp(e2dProperty p){

prop = p;}

/*** checks if the BasicShape is on the board** @return true iff on the board*/public boolean isOnBoard(){

return onBoard;}

/*** Sets whether or not the piece is on board** @param b* true iff piece is on board*/public void setOnBoard(boolean b){

onBoard = b;}

/*** Marks this basic shape as appearing on the board** @param x* x coordinate of the location of this shape on the board* @param y* y coordinate of the location of this shape on the board*/public void putOnBoard(int x, int y){

onBoard = true;boardX = x;boardY = y;

Page 153: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 145

}

/*** Marks this basic shape as no longer appearing on the board**/public void removeFromBoard(){

onBoard = false;boardX = offX;boardY = offY;

}

/****************************************************************************** GUI FUNCTIONALITY****************************************************************************//*** method drawBasicShape draws the basic shape of a shape** @param g* the graphics component to draw on* @param xMid* the middle in the x direction in pixels* @param yMid* the middle in the y direction in pixels* @param granulation* the current granulation of the board* @param selected* wheather the top piece is selected* @author aja*/public void drawBasicShape(Graphics g, int xMid, int yMid, int granulation,

boolean selected){

int tranX;int tranY;tranX = xMid + offX * granulation;tranY = yMid - offY * granulation;

// set transparent if slectedif (selected)

g.setColor(new Color(prop.getColor().getRed(),prop.getColor().getGreen(), prop.getColor().getBlue(), 150));

elseg.setColor(prop.getColor());

Page 154: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

146 APPENDIX A. SOURCE CODE

g.fillRect(tranX, tranY, granulation, granulation);g.setColor(Color.BLACK);g.drawRect(tranX, tranY, granulation, granulation);

}

/*** takes an orgin, the xCord and yCord, and draws the piece from it using the* translation. If origin is 0,0 then it is the same as drawPiece** @param g* the graphics component to draw on* @param xCord* the x coordinate to do drawing on* @param yCord* the y coordinate to do drawing on* @param xMid* the middle in the x direction in pixels* @param yMid* the middle in the y direction in pixels* @param granulation* the current granulation of the board* @param selected* wheather the top piece is selected* @author aja*/public void drawBasicShapeFromOrigin(Graphics g, int xCord, int yCord,

int xMid, int yMid, int granulation, boolean selected){

int tranX;int tranY;tranX = xMid + (xCord + offX) * granulation;tranY = yMid - (yCord + offY) * granulation;

if (selected)g.setColor(new Color(prop.getColor().getRed(),

prop.getColor().getGreen(), prop.getColor().getBlue(), 150));else

g.setColor(prop.getColor());

g.fillRect(tranX, tranY, granulation, granulation);g.setColor(Color.BLACK);g.drawRect(tranX, tranY, granulation, granulation);

}

/**

Page 155: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 147

* Static because needs to be called arbitrarily... draw and outline of a* piece used. Used to do the follow of the mouse, should take in an extra* argument for the color to stop color from being static.** @param g* the graphics component to draw on* @param xCord* the x coordinate to do drawing on* @param yCord* the y coordinate to do drawing on* @param xMid* the middle in the x direction in pixels* @param yMid* the middle in the y direction in pixels* @param granulation* the current granulation of the board* @author aja*/public void drawOutlineBasicShape(Graphics g, int xCord, int yCord, int xMid,

int yMid, int granulation){

int tranX;int tranY;tranX = xMid + (xCord + offX) * granulation;tranY = yMid - (yCord + offY) * granulation;

g.setColor(prop.getColor());g.drawRect(tranX, tranY, granulation, granulation);

}

}

A.6.3 e2dBoard

package e2dCore;

/*** Class representing e2d’s "Board"* @author jlc**/

public class e2dBoard {/**************************************************************Private members

Page 156: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

148 APPENDIX A. SOURCE CODE

*************************************************************/protected e2dSet<e2dPiece> pieces; //pieces on the boardprotected boolean hasWidth; //Does the board have a maximum width?protected int width; //The maximum widthprotected boolean hasHeight; //Does the board have a maximum height?protected int height; //The maximum height

protected int xmin, xmax, ymin, ymax;

/** Error messages used for constructing exceptions*/private static final String widthOutOfBoundsErrMsg =

"Given width out of bounds";private static final String heightOutOfBoundsErrMsg =

"Given height out of bounds";private static final String invalidWidthErrMsg =

"Invalid width: must be > 0";private static final String invalidHeightErrMsg =

"Invalid height: must be > 0";private static final String badPieceStateErrMsg =

"Invalid piece state: claims to be on board but not in pieces";

/************************************************************** Constructors*************************************************************//*** Default constructor. Constructs an empty board with no height* or width restrictions.*/public e2dBoard(){

pieces = new e2dSet<e2dPiece>();hasWidth = hasHeight = false;width = height = -1; //just to be sure we know they’re invalid :)

}

/*** Construct an empty e2dBoard with the given height and width* restrictions for gameplay.* Note that maximum heights and widths mean x & y coordinates of a maximum* of maximum of maxh/2 and maxw/2 respectively.** @param maxw Maximum width of the board in grid units* @param maxh Maximum height of the board in grid units

Page 157: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 149

* @throws IllegalArgumentException The given height or width does not make* sense; ie, it zero/negative.*/public e2dBoard(int maxw, int maxh) throws IllegalArgumentException{

pieces = new e2dSet<e2dPiece>();

if(maxw > 0)width = maxw;

elsethrow new IllegalArgumentException(invalidWidthErrMsg);

if(maxh > 0)height = maxh;

elsethrow new IllegalArgumentException(invalidHeightErrMsg);

hasWidth = hasHeight = true;}//deep copypublic e2dBoard(e2dBoard b){

pieces = new e2dSet<e2dPiece>();for(e2dPiece p : b.pieces){

try{

if(p.getClass().equals(Class.forName("e2dCore.e2dPiece"))){

pieces.add(new e2dPiece(p));}else{

Class[] copyParams = new Class[2];copyParams[0] = p.getClass().getDeclaringClass();copyParams[1] = p.getClass();Object[] copyArgs = new Object[2];copyArgs[0] = copyParams[0].newInstance();copyArgs[1] = p;

pieces.add(p.getClass().getConstructor(copyParams).newInstance(copyArgs));

}}catch(Exception e){

Page 158: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

150 APPENDIX A. SOURCE CODE

System.err.println("board failed to copy right");pieces.add(new e2dPiece(p));

}}hasWidth = b.hasWidth;width = b.width;hasHeight = b.hasHeight;height = b.height;xmin = b.xmin;xmax = b.xmax;ymin = b.ymin;ymax = b.ymax;

}

/************************************************************** Public functions*************************************************************/

/************************************************************** Accessors*************************************************************/public void setFlags(e2dFlags f){

for(e2dPiece p : pieces)p.setFlags(f);

}

/*** Put a piece that does not have a current location on to the board.* @param piece The piece to be placed on the board* @param x The x coordinate of where the piece will be placed* @param y The y coordinate of where the piece will be placed* @throws IllegalArgumentException The given x or y coordinate given* is outside the bounds of the board’s* maximum size.*/public void putPieceAt(e2dPiece piece, int x, int y)throws IllegalArgumentException{

if(hasWidth){

if(piece.offWidthBoard(x,xmin,xmax))throw new IllegalArgumentException(widthOutOfBoundsErrMsg);

}

Page 159: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 151

if(hasHeight){

if(piece.offHeightBoard(y,ymin,ymax))throw new IllegalArgumentException(heightOutOfBoundsErrMsg);

}piece.putOnBoard(x, y);pieces.add(piece);

}

/*** Put a piece which has a location already stored on to the board* @param p* @throws IllegalArgumentException The location of the piece is outside the* bounds of the board’s maximum size.*/public void putPiece(e2dPiece p) throws IllegalArgumentException{

if(p.isOnBoard()) //is this ready to be put on board?{

if(hasWidth){

if(p.offWidthBoard(p.getX(),xmin,xmax))throw new IllegalArgumentException(widthOutOfBoundsErrMsg);

}if(hasHeight){

if(p.offHeightBoard(p.getY(),ymin,ymax))throw new IllegalArgumentException(heightOutOfBoundsErrMsg);

}

pieces.add(p);}else

throw new IllegalArgumentException();}

/*** Get the piece stored at the given x and y location on the board, or null* if no piece is at that coordinate. This function finds the FIRST piece on* the board at that location; if later pieces in the board are also located at* that point* @param x The x coordinate that the piece is located at* @param y The y coordinate that the piece is located at* @return The piece located at the given x and y coordinates or null if* no pieces are located at that coordinate.

Page 160: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

152 APPENDIX A. SOURCE CODE

* @throws IllegalArgumentException The x or y coordinates given are outside the* bounds of the board’s maximum size.*/public e2dPiece getPieceAt(int x, int y) throws IllegalArgumentException{

if(hasWidth && ((x < xmin) || (x > xmax))){

throw new IllegalArgumentException(widthOutOfBoundsErrMsg);}if(hasHeight && ((y < ymin) || (y > ymax))){

throw new IllegalArgumentException(heightOutOfBoundsErrMsg);}

//search through pieces until find x & y located piecefor(e2dPiece p : pieces){

if(p.isOnPiece(x, y))return p;

}

return null;}

/*** Remove the given piece from the board* @param piece a piece which is already on the board* @throws IllegalArgumentException The given piece is not currently on* the board.*/public void removePiece(e2dPiece p) throws IllegalArgumentException{

if(p.isOnBoard()){

for(int i = 0; i < pieces.size(); i++){

e2dPiece temp = pieces.get(i);if(p.equals(temp) &&

p.getX() == temp.getX() &&p.getY() == temp.getY())

{pieces.remove(i);p.removeFromBoard();return;

}

Page 161: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 153

}throw new NotOnBoardException("Piece not in board’s pieces set");

}else

throw new NotOnBoardException(badPieceStateErrMsg);}

/*** Sets the maximum height for the board to the given value* @param h The new maximum height* @throws IllegalArgumentException The height is invalid, ie, negative.*/public void setHeight(int h) throws IllegalArgumentException{

if(h < 0){

throw new IllegalArgumentException(invalidHeightErrMsg);}

height = h;if((h%2) == 0){

ymax = h/2;ymin = -(h/2)+1;

}else{

//Convention: if board is odd, push one more to minymax = (h/2)+1;ymin = -(h/2) + 1;

}hasHeight = true;

}

/*** Get the maximum height of the board in grid units* @return Maximum height of the board in grid units or -1 if not limited*/public int getHeight(){

return height;}

/*** Set the maximum width for the board to the given value

Page 162: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

154 APPENDIX A. SOURCE CODE

* @param w The new maximum width* @throws IllegalArgumentException*/public void setWidth(int w) throws IllegalArgumentException{

if(w < 0){

throw new IllegalArgumentException(invalidWidthErrMsg);}

width = w;if((w%2) == 0){

xmax = w/2-1;xmin = -(w/2);

}else{

//Convention: if board is odd, push one more to minxmax = (w/2)- 1;xmin = -(w/2) - 1;

}hasWidth = true;

}

/*** Get the maximum width of the board in grid units* @return Maximum width of the board in grid units*/public int getWidth(){

return width;}

/*** Get the set of pieces currently on the board* @return*/public e2dSet<e2dPiece> getPieces(){

return pieces;}

public int getXMin(){

if(hasWidth)

Page 163: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 155

return xmin;else

throw new IllegalStateException("Attempted to get xmin when not bounded");

}public int getXMax(){

if(hasWidth)return xmax;

elsethrow new IllegalStateException("Attempted to get xmax when not bounded");

}public int getYMin(){

if(hasHeight)return ymin;

elsethrow new IllegalStateException("Attempted to get ymin when not bounded");

}public int getYMax(){

if(hasHeight)return ymax;

elsethrow new IllegalStateException("Attempted to get ymax when not bounded");

}}

A.6.4 e2dFlags

package e2dCore;

/*** Handy class for storing all flags (may, reveal, etc) used by e2d** @author aja, jlc**/

public class e2dFlags {/* for the may’s */private boolean mayRotate;

private boolean mayFlipX;

Page 164: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

156 APPENDIX A. SOURCE CODE

private boolean mayFlipY;

private boolean mayFlip;

/* for hide and reveal options */private boolean showBag;

private boolean showHands;

/*** Default constructor; sets all flags to false (max restrictions)*/public e2dFlags(){

mayRotate = false;mayFlipX = false;mayFlipY = false;mayFlip = false;

showBag = false;showHands = false;

}

/*** Copy the given set of flags.** @param f* flags to copy*/public e2dFlags(e2dFlags f){

mayRotate = f.mayRotate;mayFlipX = f.mayFlipX;mayFlipY = f.mayFlipY;mayFlip = f.mayFlip;

showBag = f.showBag;showHands = f.showHands;

}

/*** Allow rotations**/public void mayRotate()

Page 165: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 157

{mayRotate = true;

}

/*** Do not allow roatations**/public void mayNotRotate(){

mayRotate = false;}

/*** Allow all flips--that is, mayFlipX() and mayFlipY()** @see #mayFlipX()* @see #mayFlipY()*/public void mayFlip(){

mayFlip = true;mayFlipX = true;mayFlipY = true;

}

/*** Do not allow any flips--that is, mayNotFlipX() and mayNotFlipY()** @see #mayNotFlipX()* @see #mayNotFlipY()*/public void mayNotFlip(){

mayFlip = false;mayFlipX = false;mayFlipY = false;

}

/*** Allow pieces to be reflected over the y axis during comparisons.***/public void mayFlipY(){

Page 166: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

158 APPENDIX A. SOURCE CODE

mayFlipY = true;}

/*** Do not allow pieces to be reflected over the y axis**/public void mayNotFlipY(){

mayFlipY = false;}

/*** Allow pieces to be reflected over the x axis**/public void mayFlipX(){

mayFlipX = true;}

/*** Do not allow pieces to be reflected over the x axis**/public void mayNotFlipX(){

mayFlipX = false;}

/*** Hide the bag from the players (equivalent to asking for draws at random)**/public void hideBag(){

showBag = false;}

/*** Reveal the bag to the players before they choose from it**/public void revealBag(){

showBag = true;

Page 167: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 159

}

/*** Hide players’ hands from the other players**/public void hideHands(){

showHands = false;}

/*** Reveal all players’ hands to other players.**/public void revealHands(){

showHands = true;}

/*** Checks if pieces can rotate during comparisons** @return true iff pieces may rotate*/public boolean canRotate(){

return mayRotate;}

/*** Checks if pieces can flip over the x or y axis during comparisons** @return true iff pieces may rotate over BOTH the x AND y axis* @see #canFlipX()* @see #canFlipY()*/public boolean canFlip(){

return mayFlip;}

/*** Checks if pieces can flip over the x axis during comparisons** @return true iff pieces may flip over the x axis

Page 168: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

160 APPENDIX A. SOURCE CODE

*/public boolean canFlipX(){

return mayFlipX;}

/*** Checks if pieces can flip over the y axis during comparisons** @return true iff pieces may flip over the y axis*/public boolean canFlipY(){

return mayFlipY;}

/*** Checks if the bag is currently revealed to the players** @return true iff the bag is currently revealed*/public boolean canViewBag(){

return showBag;}

/*** Checks if ALL players’ hands are revealed to the other players** @return true iff all players’ hands are revealed to all*/public boolean canViewHands(){

return showHands;}

}

A.6.5 e2dGame

package e2dCore;

/*** Class containing all the essential verbs necessary for coordinating* interaction between the GUI and modifications of the state of the game.*

Page 169: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 161

* Code generated by the e2d compiler extends this class** @author aja, jlc**/

public class e2dGame {protected e2dGameState gs;

protected e2dInteractor tgt;

protected int turnCounter = 0;

/*** Construct the default game with an empty gamestate**/public e2dGame(){

gs = new e2dGameState();}

public e2dGameState getGameState(){

return gs;}/** Piece movement functions. e2dCore implementations of the piece movement* functions defined in the e2d Language Reference Manual section 4.5. Makes* heavy use of the e2dInteractor interface.*//*** Perform the "move" construct from the e2d langauge*/protected void move(e2dSet<? extends e2dPiece> from,

e2dSet<? extends e2dPiece> to) throws Exception{

if(from.size() <= 0){

throw new EmptySetException("The set is empty");}

e2dPiece[] played = new e2dPiece[2];

// test to see if it is from some hand to some other hande2dPlayer fromPlayer = null;e2dPlayer toPlayer = null;

Page 170: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

162 APPENDIX A. SOURCE CODE

for (e2dPlayer player : gs.getPlayers()){

if (player.getHand() == from){

fromPlayer = player;break;

}}for (e2dPlayer player : gs.getPlayers()){

if (player.getHand() == to){

toPlayer = player;break;

}}

if (fromPlayer != null && toPlayer != null){

// both correspond to a playerplayed = tgt.moveFromSomeHandToSomeHand(toPlayer, fromPlayer);if (doPieceMove(played[1], played[0], toPlayer)){

tgt.updateGameState(gs);return;

} else{

tgt.print("Illegal Move");tgt.updateGameState(gs);move(from, to); // recursion is happyreturn;

}

} else if (fromPlayer != null && toPlayer == null){

// we now know that the from corresponds to a player// is it to the bag?

if (to == gs.getBag()){

// is it the current player?if (fromPlayer == gs.getCurrPlayer()){

played = tgt.moveFromCurrHand(e2dInteractor.DEST_BAG);if (doPieceMove(played[1], played[0], gs.getCurrPlayer()))

Page 171: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 163

{tgt.updateGameState(gs);return;

} else{

tgt.print("Illegal Move");tgt.updateGameState(gs);move(from, to); // recursion is happyreturn;

}

} else{

// it isn’t the current playerplayed = tgt.moveFromSomeHand(e2dInteractor.DEST_BAG, fromPlayer);if (doPieceMove(played[1], played[0], fromPlayer)){

tgt.updateGameState(gs);return;

} else{

tgt.print("Illegal Move");tgt.updateGameState(gs);move(from, to); // recursion is happyreturn;

}}

} else if (to == gs.getBoard().getPieces()){

// moving to the boardtry{

// is it the current player?if (fromPlayer == gs.getCurrPlayer()){

played = tgt.moveFromCurrHand(e2dInteractor.DEST_BOARD);if (doPieceMove(played[1], played[0], gs.getCurrPlayer())){

tgt.updateGameState(gs);return;

} else{

tgt.print("Illegal Move");tgt.updateGameState(gs);

Page 172: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

164 APPENDIX A. SOURCE CODE

move(from, to); // recursion is happyreturn;

}} else{

// not the current playerplayed = tgt.moveFromSomeHand(e2dInteractor.DEST_BOARD, fromPlayer);if (doPieceMove(played[1], played[0], null)){

tgt.updateGameState(gs);return;

} else{

tgt.print("Illegal Move");tgt.updateGameState(gs);move(from, to); // recursion is happyreturn;

}}

}catch(IllegalArgumentException offBoard){

tgt.print("That’s not on the board!");tgt.updateGameState(gs);move(from,to);return;

}}

} else if (fromPlayer == null && toPlayer != null){

// not from a player but to a players hand

// is the to the current playerif (toPlayer == gs.getCurrPlayer()){

//check form conditionsif(from == gs.getBag()){

played = tgt.moveFromBag(e2dInteractor.DEST_CURRHAND);}else if(from == gs.getBoard().getPieces()){

played = tgt.moveFromBoard(e2dInteractor.DEST_CURRHAND);}

Page 173: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 165

else{

played = tgt.moveFromSet(e2dInteractor.DEST_CURRHAND, from);}if (doPieceMove(played[1], played[0], toPlayer)){

tgt.updateGameState(gs);return;

} else{

tgt.print("Illegal Move");tgt.updateGameState(gs);move(from, to); // recursion is happyreturn;

}} else{

//it is from set to arbitrary playerif(from == gs.getBag()){

tgt.moveFromBagToHand(toPlayer);}else if(from == gs.getBoard().getPieces()){

tgt.moveFromBoardToHand(toPlayer);}else{

played = tgt.moveFromSetToHand(from, toPlayer);}if (doPieceMove(played[1], played[0], toPlayer)){

tgt.updateGameState(gs);return;

} else{

tgt.print("Illegal Move");tgt.updateGameState(gs);move(from, to); // recursion is happyreturn;

}}

} else if (fromPlayer == null && toPlayer == null){

// moveing from some set to another set

Page 174: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

166 APPENDIX A. SOURCE CODE

// is it from the bagif (from == gs.getBag()){

// where is it to

if (to == gs.getBoard().getPieces()){

try{

// it’s from bag to boardplayed = tgt.moveFromBag(e2dInteractor.DEST_BOARD);if (doPieceMove(played[1], played[0], null)){

tgt.updateGameState(gs);return;

} else{

tgt.print("Illegal Move");tgt.updateGameState(gs);move(from, to); // recursion is happyreturn;

}}catch(IllegalArgumentException e){

tgt.print("That’s not on the board!");tgt.updateGameState(gs);move(from,to);return;

}} else if (to == gs.getBag()){

// bag to bag makes no sense so just returnreturn; //should be exception

}} else if (from == gs.getBoard().getPieces()){

// its from the board

// where is it toif (to == gs.getBoard().getPieces()){

try{

played = tgt.moveFromBoard(e2dInteractor.DEST_BOARD);if (doPieceMove(played[1], played[0], null))

Page 175: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 167

{tgt.updateGameState(gs);return;

} else{

tgt.print("Illegal Move");tgt.updateGameState(gs);move(from, to); // recursion is happyreturn;

}}catch(IllegalArgumentException e){

tgt.print("That’s not on the board!");tgt.updateGameState(gs);move(from,to);return;

}} else if (to == gs.getBag()){

played = tgt.moveFromBoard(e2dInteractor.DEST_BAG);if (doPieceMove(played[1], played[0], null)){

tgt.updateGameState(gs);return;

} else{

tgt.print("Illegal Move");tgt.updateGameState(gs);move(from, to); // recursion is happyreturn;

}}

}}

}

/*** perform the "remove" funciton of the e2d language** @param from* set that will be removed from*/protected void remove(e2dSet<? extends e2dPiece> from){

if(from.size() <= 0)

Page 176: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

168 APPENDIX A. SOURCE CODE

{throw new EmptySetException("The set is empty");

}

e2dPiece played;

// test to see if it is from some hand to some other hande2dPlayer fromPlayer = null;

for (e2dPlayer player : gs.getPlayers()){

if (player.getHand() == from){

fromPlayer = player;break;

}}

// is the from a players handif (fromPlayer != null){

// is it the current playerif (fromPlayer == gs.getCurrPlayer()){

played = tgt.removeFromCurrHand();gs.getCurrPlayer().removePieceFromHand(played);tgt.updateGameState(gs);return;

} else{

// otherwise it is from someother players handplayed = tgt.removeFromHand(fromPlayer);fromPlayer.removePieceFromHand(played);tgt.updateGameState(gs);return;

}} else{

// it is not from a player

// is it from the bagif (from == gs.getBag()){

played = tgt.removeFromBag();gs.removePieceFromBag(played);tgt.updateGameState(gs);

Page 177: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 169

return;} else if (from == gs.getBoard().getPieces()){

// its from the boardplayed = tgt.removeFromBoard();gs.removePieceFromBoard(played);tgt.updateGameState(gs);return;

}}

}

/*** e2d language function "remove piece from set"** @param piece* @param from*/protected void remove(e2dPiece piece, e2dSet<e2dPiece> from){

if(from.size() <= 0){

throw new EmptySetException("The set is empty");}

// test to see if it is from some hand to some other hande2dPlayer fromPlayer = null;

for (e2dPlayer player : gs.getPlayers()){

if (player.getHand() == from){

fromPlayer = player;break;

}}

// is the from a players handif (fromPlayer != null){

// is it the current playerif (fromPlayer == gs.getCurrPlayer()){

gs.getCurrPlayer().removePieceFromHand(piece);tgt.updateGameState(gs);

Page 178: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

170 APPENDIX A. SOURCE CODE

return;} else{

// otherwise it is from someother players handfromPlayer.removePieceFromHand(piece);tgt.updateGameState(gs);return;

}} else{

// it is not from a player

// is it from the bagif (from == gs.getBag()){

gs.removePieceFromBag(piece);tgt.updateGameState(gs);return;

} else if (from == gs.getBoard().getPieces()){

gs.removePieceFromBoard(piece);tgt.updateGameState(gs);return;

}}

}

/*** e2dLanguage function "draw"**/protected void draw() throws Exception{

move(gs.getBag(), gs.getCurrPlayer().getHand());tgt.updateGameState(gs);

}

protected void draw(e2dSet<? extends e2dPiece> from) throws Exception{

move(from, gs.getCurrPlayer().getHand());tgt.updateGameState(gs);

}

protected void play() throws Exception{

move(gs.getCurrPlayer().getHand(), gs.getBoard().getPieces());

Page 179: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 171

tgt.updateGameState(gs);}

protected void play(e2dSet<? extends e2dPiece> from) throws Exception{

move(from, gs.getBoard().getPieces());tgt.updateGameState(gs);

}

private boolean doPieceMove(e2dPiece src, e2dPiece dest, e2dPlayer player)throws Exception

{e2dGameState temp = gs;gs = new e2dGameState(gs);

//pointer to the actual piece in gamestate that the interactor used//as the source of its transformatione2dPiece realSrcPtr = null;

e2dPlayer realPlayer = null; //not by Real Media Inc.

if(player != null){

for(int i = 0; i < temp.getPlayers().size(); i++){

if(player.equals(temp.getPlayers().get(i))){

realPlayer = gs.getPlayers().get(i);}

}if(realPlayer == null)

throw new NoSuchPlayerException("Player disappeared in copy");}

// remove src from its original positionif (src.isInBag()){

for(e2dPiece p : gs.getBag()){

if(src.equals(p)){

System.out.println("Source found in bag");realSrcPtr = p;break;

}

Page 180: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

172 APPENDIX A. SOURCE CODE

}gs.removePieceFromBag(realSrcPtr);

} else if (src.isInHand()){

boolean found = false;System.out.println("Source found in hand");for (e2dPlayer p : gs.getPlayers()){

for(e2dPiece q : p.getHand()){

if(src.equals(q)){

System.out.println("Src contained in p’s hand");realSrcPtr = q;found = true;break;

}}if(found){

gs.removePieceFromPlayer(realSrcPtr, p);break;

}}

} else if (src.isOnBoard()){

System.out.println("Source found in board");for(e2dPiece p : gs.getBoard().getPieces()){

if(src.equals(p) &&src.getX() == p.getX() &&src.getY() == p.getY())

{realSrcPtr = p;

}}gs.removePieceFromBoard(realSrcPtr);

} else{

gs = temp;throw new IllegalStateException("src came from someplace mysterious");

}

if(realSrcPtr == null){

Page 181: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 173

gs = temp;throw new IllegalStateException("No real source... how did this happen?");

}/** Since src and dest may be copies stored as e2dPieces,* we don’t know if they’ve* lost subclassing information that might be* necessary in the e2dGame. In* order to make up for this we basically have to figure* out the transformation* that was applied to get from src to dest. Luckily,* e2dPieces have enough* knowledge that we can effectively do this transformation.*/

if(src.getRotCount() != dest.getRotCount()){

int rotdiff = dest.getRotCount() - src.getRotCount();realSrcPtr.rotate(rotdiff);

}if(src.getFlipXCount()%2 != dest.getFlipXCount()%2){

realSrcPtr.flipX();}if(src.getFlipYCount()%2 != dest.getFlipYCount()%2){

realSrcPtr.flipY();}

realSrcPtr.clearTransformationMemory();

// add dest to its new locationif (dest.isInBag()){

System.out.println("putting piece into bag");gs.addPieceToBag(realSrcPtr);

} else if (dest.isInHand()){

if (realPlayer != null){

System.out.println("putting piece into somebody’s hand");gs.addPieceToPlayer(realSrcPtr, realPlayer);

}else{

Page 182: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

174 APPENDIX A. SOURCE CODE

gs = temp;throw new IllegalArgumentException("Invalid player setting");

}

} else if (dest.isOnBoard()){

System.out.println("putting piece into board");realSrcPtr.putOnBoard(dest.getX(), dest.getY());gs.setCurrPiece(realSrcPtr);if(legal("")){

gs.addPieceToBoard(realSrcPtr);} else{

gs = temp;return false;

}} else{

throw new IllegalStateException("dest is headed to"+ " someplace mysterious");

}gs.setCurrPiece(realSrcPtr);return true;

}

/*** Increments the turn counter by the offset.** @param offset* amount to increment the turn counter*/public void changeTurn(int offset){

int modbase = gs.getPlayers().size();while (offset < 0){

offset += modbase;}turnCounter = (turnCounter + offset) % modbase;gs.setCurrPlayer(gs.getPlayers().get(turnCounter));tgt.updateGameState(gs);

}

/**

Page 183: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 175

* Set the turn as the given player’s** @param p*/public void changeTurn(e2dPlayer p){

int newIdx;for(newIdx = 0; newIdx < gs.getPlayers().size(); newIdx++){

if(p.equals(gs.getPlayers().get(newIdx))){

break;}

}turnCounter = newIdx;System.err.println("fuckers are setting offset to "+turnCounter);gs.setCurrPlayer(p);

}

public boolean playable(e2dPiece p) throws Exception{

//calculate the bounds for playableint minX, maxX, minY, maxY;if(gs.getBoard().getWidth() == -1){

//choose an arbitrary max/min sizeminX = -50;maxX = 50;

}else{

minX = gs.getBoard().getXMin();maxX = gs.getBoard().getXMax();

}

if(gs.getBoard().getHeight() == -1){

//as aboveminY = -50;maxY = 50;

}else{

minY = gs.getBoard().getYMin();maxY = gs.getBoard().getYMax();

}

Page 184: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

176 APPENDIX A. SOURCE CODE

//more evil hypothetical gamestate stuffe2dGameState temp = new e2dGameState(gs);

try{

Class[] copyParams;Object[] copyArgs;//magicif(p.getClass().equals((new e2dPiece()).getClass())) //i hate java{

copyParams = new Class[1];copyParams[0] = p.getClass();copyArgs = new Object[1];copyArgs[0] = p;

}else{

//okay, it’s an inner class... bleargh!//inner classes have absolute INSANITY... they actually have a//hidden first argument which is the outer class. Whoever thought//this was a Good Idea was clearly insane. It’s not obvious// that these//things exist and are a bitch to track down. Because we can’t know//the subclass that this will get called in (or//what inner e2dPieces it//defines) we have to do this hidden argument addition ourselves.copyParams = new Class[2];copyParams[0] = this.getClass();copyParams[1] = p.getClass();copyArgs = new Object[2];copyArgs[0] = this;copyArgs[1] = p;

}

gs.setCurrPiece(p.getClass().getConstructor(copyParams).newInstance(copyArgs));

}catch(Exception e){

throw new Exception("buggered", e);}//if magic worked, the currpiece is now set to a copy of pe2dPiece q = gs.getCurrPiece();

for(int x = 0; x < maxX; x++){

Page 185: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 177

for(int y = 0; y < maxY; y++){

q.putOnBoard(x,y);if(legal("")){

gs = temp;return true;

}

if(-x > minX){

q.putOnBoard(-x,y);if(legal("")){

gs = temp;return true;

}}if(-y > minY){

q.putOnBoard(x,-y);if(legal("")){

gs = temp;return true;

}}if(-x > minX && -y > minY){

q.putOnBoard(-x,-y);if(legal("")){

gs = temp;return true;

}}

}}gs = temp;return false;

}

/*** Legal pattern. Must be extended, but stubbed in here for implementation of* move*

Page 186: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

178 APPENDIX A. SOURCE CODE

* @return*/public boolean legal(String s) throws Exception{

return true;}

/*** End pattern.** @return*/public boolean end(String s) throws Exception{

return true;}

}

A.6.6 e2dGameState

package e2dCore;

/*** Holds the state of the current game. Does not do any communication with other* classes; it is a self contained data structure that contains what the game* looks like at a given moment in time.** @author jlc**/

public class e2dGameState {/****************************************************************************** Private members****************************************************************************/private e2dSet<e2dPlayer> players;

private e2dBoard board;

private e2dSet<e2dProperty> properties;

private e2dSet<e2dPiece> bag;

private e2dSet<e2dPlayer> winners;

private e2dPlayer currPlayer;

Page 187: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 179

private e2dPiece currPiece;

private e2dFlags flags; // object containing all flags

private e2dFlags tempFlags;

private boolean addedPlayer, addedProperty, tempFlagsValid;

public String gameName;/****************************************************************************** Constructors****************************************************************************//*** generate generic empty game state with all default may and reveals set*/public e2dGameState(){

players = new e2dSet<e2dPlayer>();board = new e2dBoard();properties = new e2dSet<e2dProperty>();bag = new e2dSet<e2dPiece>();winners = new e2dSet<e2dPlayer>();

currPlayer = null;currPiece = null;

flags = new e2dFlags();tempFlags = new e2dFlags();

}

/*** copy constructor** @param gs* the gameState to be copy*/public e2dGameState(e2dGameState gs){

currPiece = null;

if (gs.currPlayer == null)currPlayer = null;

players = new e2dSet<e2dPlayer>();

Page 188: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

180 APPENDIX A. SOURCE CODE

for (e2dPlayer p : gs.players){

players.add(new e2dPlayer(p));if (p == gs.currPlayer)

currPlayer = players.get(players.size() - 1);}

board = new e2dBoard(gs.board);properties = new e2dSet<e2dProperty>();for (e2dProperty p : gs.properties){

properties.add(new e2dProperty(p));}bag = new e2dSet<e2dPiece>();for (e2dPiece b : gs.bag){

try{

if(b.getClass().equals(Class.forName("e2dCore.e2dPiece"))){

bag.add(new e2dPiece(b));}else{

//we’re a subclass. Do magicClass[] copyParams = new Class[2];copyParams[0] = b.getClass().getDeclaringClass();copyParams[1] = b.getClass();Object[] copyArgs = new Object[2];copyArgs[0] = copyParams[0].newInstance();copyArgs[1] = b;

bag.add(b.getClass().getConstructor(copyParams).newInstance(copyArgs));

}}catch(Exception e){

System.err.println("copy of bag failed");System.err.println(e.toString());bag.add(new e2dPiece(b));

}

Page 189: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 181

if (b == gs.currPiece)currPiece = bag.get(bag.size() - 1);

}winners = new e2dSet<e2dPlayer>();for (e2dPlayer w : gs.winners){

winners.add(new e2dPlayer(w));}if (gs.currPiece == null)

currPiece = null;else{

e2dPiece temp;try{

for (int i = 0; i < board.getPieces().size(); i++){

temp = board.getPieces().get(i);if (gs.currPiece.equals(temp)&& gs.currPiece.getX() == temp.getX()

&& gs.currPiece.getY() == temp.getY()){

currPiece = temp;break;

}}

}catch(NotOnBoardException e){

//this is actually a somewhat normal occurance, as only//currPiece should have this set right... anyway, do nothing.

}if (currPiece == null){

//Okay. Board failed. Let’s try bagfor(int i = 0; i < bag.size(); i++){

temp = bag.get(i);

Page 190: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

182 APPENDIX A. SOURCE CODE

try{

if (gs.currPiece.equals(temp)&& gs.currPiece.getX() == temp.getX()

&& gs.currPiece.getY() == temp.getY()){

currPiece = temp;break;

}}catch(NotOnBoardException e){

//this is actually a somewhat normal occurance, as only//currPiece should have this set right// ... anyway, do nothing.

}}

}if(currPiece == null){

//Alright, being annoying. Have to go through all the hands.for(e2dPlayer p : players){

for(int i = 0; i < p.getHand().size(); i++){

temp = p.getHand().get(i);try{

if (gs.currPiece.equals(temp)&& gs.currPiece.getX() == temp.getX()

&& gs.currPiece.getY() == temp.getY()){

currPiece = temp;break;

}}catch(NotOnBoardException e){

//this is actually a somewhat normal occurance,// as only//currPiece should have this set right...// anyway, do nothing.

}}

}}

Page 191: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 183

}

flags = new e2dFlags(gs.flags);tempFlags = new e2dFlags(gs.tempFlags);

addedPlayer = gs.addedPlayer;addedProperty = gs.addedProperty;tempFlagsValid = gs.tempFlagsValid;

}

/****************************************************************************** Public Behaviors****************************************************************************/

/*** Function to be called at the end of e2d’s Init construct. Guarantees that* the gamestate represents a legal state at the start of the first turn.*/public void initOver(){

if (!addedPlayer){

players.add(new e2dPlayer("name"));currPlayer = players.get(0);

}}

/****************************************************************************** Accessors****************************************************************************/

/*** Sets the turn to the given player** @param player* Player whose turn it will become*/public void setCurrPlayer(e2dPlayer player){

currPlayer = player;}

/*** adds a property to game state with this name*

Page 192: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

184 APPENDIX A. SOURCE CODE

* @param name* the name to use to add the property*/public void addProperty(String name){

addedProperty = true;properties.add(new e2dProperty(name, true));

}

/*** add a range of properties** @param low* the min (inclusive)* @param high* the max (inclusive)*/public void addPropertyRange(int low, int high){

addedProperty = true;for (int i = low; i <= high; i++)

properties.add(new e2dProperty(new Integer(i).toString(), true));}

/*** add a piece to the board** @param p* the piece to be added to the board*/public void addPieceToBoard(e2dPiece p){

board.putPieceAt(p, p.getX(), p.getY());}

/*** adds a set of pieces to the board** @param pieces* the set of pieces*/public void addPiecesToBoard(e2dSet<? extends e2dPiece> pieces){

for (e2dPiece p : pieces){

addPieceToBoard(p);

Page 193: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 185

}}

/*** add a piece to the bag** @param p* the piece to be added to the bag*/public void addPieceToBag(e2dPiece p){

p.putInBag();bag.add(p);

}

/*** add’s a set of pieces to the bag** @param pieces* the pieces to add*/public void addPiecesToBag(e2dSet<? extends e2dPiece> pieces){

for (e2dPiece p : pieces){

addPieceToBag(p);}

}

/*** add a piece to the current players hand** @param p* the piece to be added*/public void addPieceToCurrPlayerHand(e2dPiece p){

currPlayer.addPieceToHand(p);}

/*** adds a set of piece to the current player’s hand** @param pieces* the set of pieces*/

Page 194: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

186 APPENDIX A. SOURCE CODE

public void addPiecesToCurrPlayerHand(e2dSet<? extends e2dPiece> pieces){

for (e2dPiece p : pieces){

addPieceToCurrPlayerHand(p);}

}

/*** add a piece to an arbitrary player’s hand** @param p* the piece to be added* @param player* the player, who’s hand to add it to* @throws NoSuchPlayerException* when there is no player in the players set*/public void addPieceToPlayer(e2dPiece p, e2dPlayer player)

throws NoSuchPlayerException{

for (e2dPlayer pl : players){

if (pl.equals(player)){

p.putInHand();pl.getHand().add(p);return;

}}throw new NoSuchPlayerException("Atempted to add a piece to invalid player");

}

/*** adds a set of pieces to a perticuler player’s hand** @param pieces* the set of pieces* @param player* the player*/public void addPiecesToPlayer(e2dSet<? extends e2dPiece> pieces,

e2dPlayer player){

Page 195: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 187

for (e2dPiece p : pieces){

addPieceToPlayer(p, player);}

}

/*** remove a piece from an arbitrary players hand** @param piece* the piece to remove* @param player* the player who’s hand to remove it from*/public void removePieceFromPlayer(e2dPiece piece, e2dPlayer player){

player.removePieceFromHand(piece);

}

/*** remove a set of pieces from a player’s hand** @param pieces* the set of pieces* @param player* the player*/public void removePiecesFromPlayer(e2dSet<? extends e2dPiece> pieces,

e2dPlayer player){

for (e2dPiece p : pieces){

removePieceFromPlayer(p, player);}

}

/*** remove a piece from the bag** @param p* the piece to remove* @throws IllegalStateException* the piece is not set to in bag* @throws NoSuchPieceInSetException* the piece does not exist

Page 196: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

188 APPENDIX A. SOURCE CODE

*/public void removePieceFromBag(e2dPiece p) throws IllegalStateException,

NoSuchPieceInSetException{

e2dPiece removedPiece = null;

if (!p.isInBag()){

throw new IllegalStateException("Piece to be removed from bag, is not set in bag");

}for (int i = 0; i < bag.size(); i++){

if (p.equals(bag.get(i))){

removedPiece = bag.remove(i);break;

}}if (removedPiece == null)

throw new NoSuchPieceInSetException("Piece is not in the bag");}

/*** remove a set of pieces form the bag** @param pieces* the set of pieces*/public void removePiecesFromBag(e2dSet<? extends e2dPiece> pieces){

for (e2dPiece p : pieces){

removePieceFromBag(p);}

}

/*** remove a piece from the board** @param p* the piece to remove from the board*/public void removePieceFromBoard(e2dPiece p){

board.removePiece(p);

Page 197: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 189

}

/*** remove a set of piece from the board** @param pieces* the set of pieces*/public void removePiecesFromBoard(e2dSet<? extends e2dPiece> pieces){

for (e2dPiece p : pieces){

removePieceFromBoard(p);}

}

/*** Adds a new player to the game** @param player* player to be added to the game*/public void addPlayer(e2dPlayer player){

addedPlayer = true;players.add(player);

}

/*** Adds a new player with name to game** @param player* name of player to add*/public void addPlayer(String player){

addedPlayer = true;players.add(new e2dPlayer(player));

}

/*** add a range of players** @param low* the min (inclusive)* @param high

Page 198: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

190 APPENDIX A. SOURCE CODE

* the max (inclusive)*/public void addPlayerRange(int low, int high){

addedPlayer = true;for (int i = low; i <= high; i++)

players.add(new e2dPlayer(new Integer(i).toString()));}

/*** Adds a player to the list of winners** @param player* the new winner*/public void addWinner(e2dPlayer player){

winners.add(player);}

/*** Remove a player from the game** @param player* ejected player*/public void removePlayer(e2dPlayer player){

players.remove(player);}

/*** Remove a player from the winner set** @param player* the loser*/public void removeWinner(e2dPlayer player){

winners.remove(player);}

/*** returns the property with the given name** @param name

Page 199: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 191

* the name to search for* @return the property with the given name* @throws IllegalStateException* no property exist with that name*/public e2dProperty getPropertyByName(String name)

throws IllegalStateException{

if (addedProperty == false)throw new IllegalStateException("No properties declared");

for (e2dProperty p : properties){

if (p.getName().equals(name))return p;

}throw new NoSuchPropertyException("Couldn’t find property " + name);

}

public e2dPlayer getPlayerByName(String name){

if (addedPlayer == false)throw new IllegalStateException("No players declared");

for (e2dPlayer p : players){

if (p.getName().equals(name))return p;

}throw new NoSuchPropertyException("Couldn’t find property " + name);

}

/*** Returns a reference to the list of properties* @return the reference*/public e2dSet<e2dProperty> getProperties(){

return properties;}

/*** hides the hands from view**/public void hideHands(){

flags.hideHands();

Page 200: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

192 APPENDIX A. SOURCE CODE

}

/*** allows the hands to be viewed**/public void revealHands(){

flags.revealHands();}

/*** hides the bag from view**/public void hideBag(){

flags.hideBag();}

/*** allows the bag to be viewed**/public void revealBag(){

flags.revealBag();}

/*** Gets the current may flag state.** @return current may flags*/public e2dFlags getFlags(){

if (tempFlagsValid)return tempFlags;

elsereturn flags;

}

/*** propegates an update of the flags through all needed places**/

Page 201: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 193

public void setTempFlags(){

tempFlagsValid = true;pushFlagsUpdate();

}

/*** restest the update of flags called from setTempFlags**/public void resetFlags(){

tempFlagsValid = false;pushFlagsUpdate();

}

/*** does the flag setting from setTempFlags and resetFlags**/private void pushFlagsUpdate(){

e2dFlags f = tempFlagsValid ? tempFlags : flags;// push flags to all childrenfor (e2dPiece p : board.getPieces())

p.setFlags(f);

}

/*** accesor that returns the board** @return the board*/public e2dBoard getBoard(){

return board;}

/*** Gets the contents of the bag** @return set containing all the pieces in the bag*/public e2dSet<e2dPiece> getBag(){

Page 202: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

194 APPENDIX A. SOURCE CODE

return bag;}

/*** returns the current player** @return the current player*/public e2dPlayer getCurrPlayer(){

return currPlayer;}

/*** returns the set of players** @return the set of players*/public e2dSet<e2dPlayer> getPlayers(){

return players;}

/*** returns the set of winners** @return the set of winners*/public e2dSet<e2dPlayer> getWinners(){

return winners;}

/*** Set the current piece** @param p* the new current piece*/public void setCurrPiece(e2dPiece p){

currPiece = p;}

public e2dPiece getCurrPiece(){

Page 203: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 195

return currPiece;}

}

A.6.7 e2dInteractor

package e2dCore;

import java.util.ArrayList;

/*** Interface defining basic functionality needed by any class that plans to run* user interaction for an e2d game.** @author jlc**/

public interface e2dInteractor {/** Destintation values*//*** Destination is the board*/public static final int DEST_BOARD = 1;

/*** Destination is the current player’s hand*/public static final int DEST_CURRHAND = 2;

/*** Destination is the bag*/public static final int DEST_BAG = 3;

/*** Inform the user that the game is over and some number of players has won.** @param winners* The winners of the game, or null/empty list if none*/void tellGameOver(e2dSet<e2dPlayer> winners);

/*** Display a message to the user

Page 204: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

196 APPENDIX A. SOURCE CODE

** @param msg* message to be printed. The null message causes an exception*/void print(String msg) throws IllegalArgumentException;

/*** Update the interactor’s representation of the game** @param gs* New state of the game that will be displayed*/void updateGameState(e2dGameState gs);

/*** Offer a choice to the user** @param s* list of choices offered to user* @returns user’s choice*/String makeChoice(ArrayList<String> s);

/*** Offers a titled choice to the user** @param title* title of the choice* @param s* list of choices offered to user* @return user’s choice*/String makeChoice(String title, ArrayList<String> s);

/** Piece movements*//*** Present a choice to the user: choose a piece from this set and place it on* dest** @param dest* Place the piece is to be moved to* @return the piece that was moved*/e2dPiece[] moveFromSet(int dest, e2dSet<? extends e2dPiece> s);

Page 205: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 197

/*** Present a choice to the user: choose a piece from the board and place it on* dest** @param dest* Place the piece is to be moved to* @return the piece that was moved*/e2dPiece[] moveFromBoard(int dest);

/*** Present a choice to the user: choose a piece from the current player’s hand* and place it on dest** @param dest* Place the piece is to be moved to* @return the piece that was moved*/e2dPiece[] moveFromCurrHand(int dest);

/*** Present a choice to the user: choose a piece from the bag and place it on* the dest** @param dest* Place the piece is to be moved to* @return the piece that was moved*/e2dPiece[] moveFromBag(int dest);

/*** Present a choice to the user: choose a piece from some arbitrary player’s* hand and place it on dest** @param dest* place the piece is to be moved to* @param from* Player whose hand will be chosen from* @return the piece that was moved*/e2dPiece[] moveFromSomeHand(int dest, e2dPlayer from)

throws NoSuchPlayerException;

/*** Present a choice to the user: choose a piece from the from hand and place

Page 206: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

198 APPENDIX A. SOURCE CODE

* it in the to hand** @param to* player whose hand will be recieve the piece* @param from* player whose hand the piece will be chosen from* @return The piece that was moved*/e2dPiece[] moveFromSomeHandToSomeHand(e2dPlayer to, e2dPlayer from)

throws NoSuchPlayerException;

/*** Present a choice to the user: chose a piece from an arbitrary set and move* it to some other player’s hand** @param from* Set used as source for selection* @param to* Player who will recieve the piece* @return the piece that was moved* @throws NoSuchPlayerException* if the player doesn’t exist*/e2dPiece[] moveFromSetToHand(e2dSet<? extends e2dPiece> from, e2dPlayer to)

throws NoSuchPlayerException;

/*** Present a choice to the player: choose a piece from the bag and give it to* another player** @param to* player who recive the piece* @return the piece that was moved* @throws NoSuchPlayerException* if the player doesn’t exist*/e2dPiece[] moveFromBagToHand(e2dPlayer to) throws NoSuchPlayerException;

e2dPiece[] moveFromBoardToHand(e2dPlayer to) throws NoSuchPlayerException;/*** Present a choice to the user: choose a piece from this set that will be* removed from the game.** @param from* the set which contains the piece to be removed* @return the piece that was removed

Page 207: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 199

*/e2dPiece removeFromSet(e2dSet<? extends e2dPiece> from);

/*** Present a choice to the user: choose a piece to remove from the bag if the* bag is visible, otherwise notify the user that a piece will be randomly* removed from the bag** @return the piece removed*/e2dPiece removeFromBag();

/*** Present a choice to the user: choose a piece to remove from the user’s* hand.** @return the piece removed*/e2dPiece removeFromCurrHand();

/*** Present a choice to the user: remove a piece from another player’s hand.** @param fromPlayer* The player who will loose a piece* @return the piece removed* @throws NoSuchPlayerException* the specified player does not exist*/e2dPiece removeFromHand(e2dPlayer fromPlayer) throws NoSuchPlayerException;

/*** Present a choice to the user: choose a piece that is on the board and* remove it.** @return*/e2dPiece removeFromBoard();

}

A.6.8 e2dPiece

package e2dCore;

//import java.awt.Color;

Page 208: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

200 APPENDIX A. SOURCE CODE

import java.awt.Graphics;

/*** Class representing a piece within e2d** @author jlc, aja(draw)**/

public class e2dPiece {

/****************************************************************************** Data members****************************************************************************/protected e2dSet<e2dShape> shapes;

protected int boardX; // location data

protected int boardY;

// in the future, figure out a more elegant way to solve this problemprotected boolean onBoard;

protected boolean inHand;

protected boolean inBag;

protected e2dFlags flags;

protected e2dSet<e2dAttachPoint> attachments;

protected int rotCount, flipXCount, flipYCount;

/** variable for the GUI to know if the piece is selected currently Always set* to false unless otherwise changed by the gui*/protected boolean selected = false;

protected boolean inPannel = false;

private static final e2dProperty DEFAULT_PROPERTY = new e2dProperty();

/****************************************************************************** Constructors****************************************************************************//**

Page 209: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 201

* Default constructor. Creates the empty piece. Override in inheritors to* generate correct pieces.*/public e2dPiece(){

shapes = new e2dSet<e2dShape>();

/* initialize x and y to zero by default */boardX = 0;boardY = 0;

onBoard = false;inHand = false;inBag = false;

/* onBoard is false otherwise x and y would be given */onBoard = false;

flags = new e2dFlags();

attachments = null;

rotCount = flipXCount = flipYCount = 0;}

public e2dPiece(e2dFlags f){

shapes = new e2dSet<e2dShape>();

/* initialize x and y to zero by default */boardX = 0;boardY = 0;

onBoard = false;inHand = false;inBag = false;

/* onBoard is false otherwise x and y would be given */onBoard = false;

flags = f;

attachments = null;

rotCount = flipXCount = flipYCount = 0;}

Page 210: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

202 APPENDIX A. SOURCE CODE

/*** Construct a new piece built from the given set of e2dShapes** @param set*/public e2dPiece(e2dSet<e2dShape> set){

/* copy the set and assign to shapes */shapes = new e2dSet<e2dShape>(set);

/* set x and y to 0 since not on board */boardX = 0;boardY = 0;

/* and not on board */onBoard = false;inHand = false;inBag = false;

flags = new e2dFlags();

attachments = null;

rotCount = flipXCount = flipYCount = 0;}

/* Constructors that the GUI will need to work *//*** Copy constructor. Create a duplicate of the given piece** @param b* The piece that will be copied.*/public e2dPiece(e2dPiece b){

shapes = new e2dSet<e2dShape>();for (e2dShape s : b.shapes)

shapes.add(new e2dShape(s));

boardX = b.boardX;boardY = b.boardY;

onBoard = b.onBoard;inHand = b.inHand;inBag = b.inBag;

Page 211: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 203

flags = b.flags;

selected = b.selected;inPannel = b.inPannel;

if(b.attachments == null){

attachments = null;}else{

attachments = new e2dSet<e2dAttachPoint>();for(e2dAttachPoint a : b.attachments){

attachments.add(new e2dAttachPoint(a));}

}

rotCount = b.rotCount;flipXCount = b.flipXCount;flipYCount = b.flipYCount;

}

/*** Create a new piece that will be placed on the board based off the old* piece.** @param x* The x coordinate of where the new piece will be on the board* @param y* The y coordinate of where the new piece will be on the board* @param b* The piece which we’re modeled off of.*/public e2dPiece(int x, int y, e2dPiece b){

shapes = new e2dSet<e2dShape>();for (e2dShape s : b.shapes)

shapes.add(new e2dShape(s));boardX = x;boardY = y;

onBoard = true;inHand = false;inBag = false;

Page 212: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

204 APPENDIX A. SOURCE CODE

flags = b.flags;

selected = b.selected;

if(b.attachments == null){

attachments = null;}else{

attachments = new e2dSet<e2dAttachPoint>();for(e2dAttachPoint a : b.attachments){

attachments.add(new e2dAttachPoint(a));}

}

rotCount = b.rotCount;flipXCount = b.flipXCount;flipYCount = b.flipYCount;

// put on boardputOnBoard(x, y);

}

/****************************************************************************** CLONE method****************************************************************************//*** Does the same thing as the copy constructor** @author aja*/public e2dPiece clone(){

e2dPiece p = new e2dPiece(this);return p;

}

/*** Discover if all the basic shapes in this piece have a corresponding basic* shape in the given shape. Performs a massively annoying imaginary* translation to make this work. Guh.** @param p

Page 213: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 205

* @return true iff* @author jlc*/public boolean compareShapes(e2dPiece p){

// here’s something fun:// We need to arbitrarily translate the locations of the basic shapes// in these pieces to a common relative location. Magic starts here.int tempX, tempY;int thisXSkew, pXSkew;int thisYSkew, pYSkew;thisXSkew = pXSkew = thisYSkew = pYSkew = 0;// can garantee that there’s a// 0,0for (e2dShape s : this.shapes){

for (e2dBasicShape b : s.getBasicShapes()){

tempX = b.getOffX();tempY = b.getOffY();thisXSkew = tempX < thisXSkew ? tempX : thisXSkew;thisYSkew = tempY < thisYSkew ? tempY : thisYSkew;

}}

for (e2dShape t : p.shapes){

for (e2dBasicShape c : t.getBasicShapes()){

tempX = c.getOffX();tempY = c.getOffY();pXSkew = tempX < pXSkew ? tempX : pXSkew;pYSkew = tempY < pYSkew ? tempY : pYSkew;

}}

int bOffsetX, bOffsetY;int bTranslatedOffsetX, cTranslatedOffsetX;int bTranslatedOffsetY, cTranslatedOffsetY;boolean bsMatches;for (e2dShape s : shapes){

// Store s’s offsets for xlation

// try to match each basic shape to some basic shape// in the other piece

Page 214: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

206 APPENDIX A. SOURCE CODE

for (e2dBasicShape b : s.getBasicShapes()){

// couldn’t have matched before we check ;)bsMatches = false;

// Store b’s offsets for xlationbOffsetX = b.getOffX();bOffsetY = b.getOffY();

for (e2dShape t : p.shapes){

// if the shapes differ in properites, we can’t possibly// match this basic shape in this shapeif (s.getProperty() != t.getProperty())

continue;

// store t’s offsets for xlationfor (e2dBasicShape c : t.getBasicShapes()){

// magicbTranslatedOffsetX = bOffsetX + pXSkew;cTranslatedOffsetX = c.getOffX() + thisXSkew;bTranslatedOffsetY = bOffsetY + pYSkew;cTranslatedOffsetY = c.getOffY() + thisYSkew;

if ((bTranslatedOffsetX == cTranslatedOffsetX)&& (bTranslatedOffsetY == cTranslatedOffsetY))

{bsMatches = true;break;

}}if (bsMatches)

break;}if (!bsMatches) // couldn’t match this basic shape, die.

return false;}

}

return true;}

/*** Determine if this piece is geometrically equivielent to the given piece.* Takes into account the current state of the may flags.

Page 215: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 207

** Adam doesn’t understand this, but if he just thought, it’d make sense --jlc** @param p* the piece to compare to* @return true iff these two pieces are share the same geometry & properties* at the same grid points. That is, true if, under a translation and* a sequence of zero or more reflections and rotations as specified* by the may flags, this piece completely overlaps p, and for every* square in both this and p, the properties of overlaping squares are* equivalent.*/public boolean equals(e2dPiece p){

// case1: irrespective of rotation, all shapes in same offset positionsif (this.compareShapes(p))

return true;

// make a copy for rotationse2dPiece munged = new e2dPiece(this);

if (flags.canRotate()){

// for all rotationsfor (int i = 0; i < 4; i++){

munged.rotateL(); // could rotateR() with same effects

// case2: rotated, but not flippedif (munged.compareShapes(p))

return true;

// case3: rotated, and can flip over x axisif (flags.canFlipX()){

munged.flipX();if (munged.compareShapes(p))

return true;munged.flipX(); // flipping a second time resets the piece

}

// case4: rotated, and can flip over y axisif (flags.canFlipY()){

munged.flipY();if (munged.compareShapes(p))

Page 216: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

208 APPENDIX A. SOURCE CODE

return true;munged.flipY(); // flipping a second time resets the piece

}}

} else{

// case5: can’t rotate, but can relfect over x axisif (flags.canFlipX()){

munged.flipX();if (munged.compareShapes(p))

return true;munged.flipX(); // flipping a second time resets the piece

}

// case6: can’t rotate, but can reflect over y axisif (flags.canFlipY()){

munged.flipY();if (munged.compareShapes(p))

return true;munged.flipY(); // flipping a second time resets the piece

}

// case7: can’t rotate, but can reflect over x && yif (flags.canFlip()){

munged.flipX();munged.flipY();if (munged.compareShapes(p))

return true;munged.flipY(); // flipping a second time resets the piecemunged.flipX(); // flipping a second time resets the piece

}}return false;

}

/****************************************************************************** Accessors****************************************************************************/

/*** Set the flags for this piece** @param f

Page 217: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 209

* the new set of may flags*/public void setFlags(e2dFlags f){

flags = f;for (e2dShape s : shapes){

s.setFlags(f);}

}

/*** Get a view of this piece as a collection of shapes** @return a shape set containing the shapes*/public e2dSet<e2dShape> getShapes(){

return shapes;}

/*** Get the location of the piece on the board** @return X-coordinate of the piece on the board*/public int getX() throws NotOnBoardException{

if (onBoard)return boardX;

throw new NotOnBoardException();}

/*** Get the location of the piece on the board** @return*/public int getY() throws NotOnBoardException{

if (onBoard)return boardY;

throw new NotOnBoardException();}

/**

Page 218: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

210 APPENDIX A. SOURCE CODE

* Determines if the piece is currently on the board** @return true iff the piece is on the board*/public boolean isOnBoard(){

return onBoard;}

/*** Determines if the piece is currently in somebody’s hand. Note that the* piece does NOT know whose hand it is end.** @return true iff the piece is on the board*/public boolean isInHand(){

return inHand;}

/*** Determines if the piece is currently in the bag.** @return*/public boolean isInBag(){

return inBag;}

/*** Prep this piece for being put into the bag**/public void putInBag(){

if (onBoard)removeFromBoard();

if (inHand)removeFromHand();

inBag = true;}

/*** Mark this piece as no longer in the bag

Page 219: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 211

**/public void removeFromBag(){

inBag = false;}

/*** Prep this piece for placement into a hand**/public void putInHand(){

if (onBoard)removeFromBoard();

if (inBag)removeFromBag();

inHand = true;}

/*** Mark this piece as no longer in a hand**/public void removeFromHand(){

inHand = false;}

/*** Get the origin shape (that is, the shape at offset 0,0)** @return the orign* @throws NoOriginException* no origin has been defined--this piece is not well defined.*/public e2dShape getOriginShape() throws NoOriginException{

for (e2dShape s : shapes){

if (s.getOffX() == 0 && s.getOffY() == 0)return s;

}// should throw exception herethrow new NoOriginException();

Page 220: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

212 APPENDIX A. SOURCE CODE

}

/****************************************************************************** Public Behaviors****************************************************************************/

/*** Rotate the piece by some amount** @param deg* an integer, mod 4 for the four orientation: 0 - no rotate 1 - 90* degrees 2 - 180 degrees 3 - 270 degrees**/public void rotate(int deg){

if (!flags.canRotate())throw new TransformationNotPermittedException("Unable to rotate piece");

for( ; deg < 0 ; deg+=4);int numRotate = deg % 4;

for (int i = 0; i < numRotate; i++){

/** rotation in the possitive direction, in math orientation*/rotateL();

}}

/*** Rotate the piece anticlockwise by 90 degrees**/public void rotateL(){

if (!flags.canRotate())throw new TransformationNotPermittedException("Unable to rotate piece");

for (e2dShape s : shapes){

int temp = s.getOffX();s.setOffX(-s.getOffY());s.setOffY(temp);s.rotateL();

Page 221: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 213

}if(attachments != null){

for(e2dAttachPoint a : attachments){

a.rotateL();}

}rotCount++;

}

/*** Rotate the piece clockwise by 90 degrees**/public void rotateR(){

if (!flags.canRotate())throw new TransformationNotPermittedException("Unable to rotate piece");

for (e2dShape s : shapes){

int temp = s.getOffX();s.setOffX(s.getOffY());s.setOffY(-temp);s.rotateR();

}if(attachments != null){

for(e2dAttachPoint a : attachments){

a.rotateR();}

}rotCount--;

}

/*** Flip the piece over the X (horizontal) axis**/public void flipX(){

if (!flags.canFlipX())throw new TransformationNotPermittedException(

"Unable to flip piece over X");

Page 222: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

214 APPENDIX A. SOURCE CODE

for (e2dShape s : shapes){

s.setOffY(-s.getOffY());s.flipX();

}if(attachments != null){

for(e2dAttachPoint a : attachments){

a.flipX();}

}flipXCount++;

}

/*** Flip the piece over the Y (vertical) axis**/public void flipY(){

if (!flags.canFlipY())throw new TransformationNotPermittedException(

"Unable to flip piece over Y");

for (e2dShape s : shapes){

s.setOffX(-s.getOffX());s.flipY();

}if(attachments != null){

for(e2dAttachPoint a : attachments){

a.flipY();}

}flipYCount++;

}

/*** Check if this piece is adjacent to the given piece.** @param p* piece which may be adjacent to this one

Page 223: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 215

* @return true iff this is adjacent to p* @throws NotOnBoardException* either this piece or p is not on the board*/public boolean adjacent(e2dPiece p) throws NotOnBoardException{

if (isOnBoard() && p.isOnBoard()){

// Is there a non-O(n^2) way to do this?for (e2dShape t : shapes){

for (e2dShape s : p.shapes){

if (t.adjacent(s))// s.adjacent(t))return true;

}}

// otherwisereturn false;

} else{

throw new NotOnBoardException();}

}

/*** Check if the given shape is adjacent to this piece.** @param s* Shape that may be adjacent to this piece* @return true iff this piece is adjacent to the given shape* @throws NotOnBoardException* either the piece or shape is not on the board*/public boolean adjacent(e2dShape s) throws NotOnBoardException{

if (isOnBoard() && s.isOnBoard()){

for (e2dShape t : shapes){

if (t.adjacent(s))return true;

}} else{

Page 224: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

216 APPENDIX A. SOURCE CODE

throw new NotOnBoardException();}return true;

}

/*** Determine if this piece overlaps the given piece.** @param p* the piece which this piece might cover* @return true iff the pieces share a grid coordinate* @throws NotOnBoardException* One of the pieces are not on the board*/public boolean overlaps(e2dPiece p) throws NotOnBoardException{

if (isOnBoard() && p.isOnBoard()){

for (e2dShape t : this.shapes){

for (e2dShape s : p.shapes){

if (t.overlaps(s))return true;

}}return false;

} else{

throw new NotOnBoardException();}

}

/*** Determine if this piece overlaps the given shape.** @param s* the piece which this shape might cover* @return true iff the pieces share a grid coordinate* @throws NotOnBoardException* One of the pieces are not on the board*/public boolean overlaps(e2dShape s){

if (isOnBoard() && s.isOnBoard()){

Page 225: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 217

for (e2dShape t : shapes){

if (t.overlaps(s))return true;

}} else{

throw new NotOnBoardException();}return true;

}

/*** updates the piece and all subshapes to onBoard status also updates the* board coordinate values** @param xx* the new x coordinate* @param yy* the new y coordinate*/public void putOnBoard(int xx, int yy){

if (inHand)removeFromHand();

if (inBag)removeFromBag();

onBoard = true;

boardX = xx;boardY = yy;

for (e2dShape s : shapes){

s.putOnBoard(boardX + s.getOffX(), boardY + s.getOffY());}

}

/*** updates the piece to not on Board status also update the board coordinate* values**/public void removeFromBoard(){

Page 226: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

218 APPENDIX A. SOURCE CODE

boardX = 0;boardY = 0;

for (e2dShape s : shapes){

s.removeFromBoard();}

}

/*** Add a 1x1 shape with the given offsets using the default property** @param xShift* offset from the piece’s origin* @param yShift* offset from the piece’s origin*/public void addShape(int xShift, int yShift){

addShape(xShift, yShift, DEFAULT_PROPERTY);}

/*** Add a 1x1 shape with the given offsets using the given property** @param xShift* offset from the piece’s origin* @param yShift* offset from the piece’s origin* @param p* the new shape’s property*/public void addShape(int xShift, int yShift, e2dProperty p){

e2dShape s = new e2dShape(xShift, yShift, p);s.setFlags(flags);shapes.add(s);

}

/*** Add a width x height shpae with the given offsets using the default* property** @param xShift* offset from the piece’s origin* @param yShift

Page 227: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 219

* offset from the piece’s origin* @param width* the width of the new shape* @param height* the height of the new shape* @return reference to the shape added*/public e2dShape addShape(int xShift, int yShift, int width, int height){

return addShape(xShift, yShift, width, height, DEFAULT_PROPERTY);}

/*** Add a width x height shpae with the given offsets using the given property** @param xShift* offset from the piece’s origin* @param yShift* offset from the piece’s origin* @param width* the width of the new shape* @param height* the height of the new shape* @param p* the property* @return a reference to the shape added*/public e2dShape addShape(int xShift, int yShift, int width, int height,

e2dProperty p){

e2dShape s = new e2dShape(xShift, yShift, width, height, p);s.setFlags(flags);shapes.add(s);return s;

}

/****************************************************************************** Behavior for GUI****************************************************************************/

/****************************************************************************** takes in a grid cordinate and determines if it is on the piece** also useful for overlaps() method should be used when piece is on the board****************************************************************************//**

Page 228: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

220 APPENDIX A. SOURCE CODE

* Returns true if the given (x,y) coordinate lies on this shape** @param x* x coord* @param y* y coord* @return true if this shape lies on x,y*/public boolean isOnPiece(int x, int y){

for (e2dShape s : shapes){

if (s.isOnShape(x, y))return true;

}

return false;}

/* general draw function *//*** Adam’s crazy draw code** @author aja*/public void drawPiece(Graphics g, int xMid, int yMid, int granulation){

for (int i = 0; i < shapes.size(); i++){

e2dShape s = shapes.get(i);s.drawShapeFromOrigin(g, boardX, boardY, xMid, yMid, granulation,

selected);}

}

/*** Adam’s crazy draw code** @author aja*/public void drawPieceInPanel(Graphics g, int xMid, int yMid, int granulation){

for (int i = 0; i < shapes.size(); i++){

e2dShape s = shapes.get(i);

Page 229: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 221

s.drawShapeFromOrigin(g, 0, 0, xMid, yMid, granulation, selected);}

}

/* outline draw function *//*** Adam’s crazy draw code** @author aja*/public void drawPieceOutline(Graphics g, int xCord, int yCord, int xMid,

int yMid, int granulation){

for (int i = 0; i < shapes.size(); i++){

e2dShape s = shapes.get(i);s.drawOutlineShape(g, xCord, yCord, xMid, yMid, granulation);

}}

/*** Adam’s crazy draw code** @author aja*/public void setSelected(boolean t){

selected = t;}

/*** checks a pieces shapes to see if they would be off the board in the width* direction if placed at loaction x and y with a board from xmin to xmax* @param x the x location* @param y the y location* @param xmin the minimum width range* @param xmax the maximum width range* @return*/public boolean offWidthBoard(int x,int xmin, int xmax){

for(e2dShape s : shapes){

if(s.offWidthBoard(x,xmin,xmax))

Page 230: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

222 APPENDIX A. SOURCE CODE

return true;}return false;

}

/*** checks a pieces shapes to see if they would be off the board in the height* direction if placed at loaction x and y with a board from ymin to ymax* @param x the x location* @param y the y location* @param ymin the minimum height range* @param ymax the maximum height range* @return*/public boolean offHeightBoard(int y, int ymin, int ymax){

for(e2dShape s : shapes){

if(s.offHeightBoard(y,ymin,ymax))return true;

}return false;

}

/** Attachments starts below here. Abandon all hope, ye who scroll down**/public void addAttach(String src, String dest,

int offX, int offY,double attachX, double attachY,boolean propsMustMatch)

{if(attachments == null)

attachments = new e2dSet<e2dAttachPoint>();

attachments.add(new e2dAttachPoint(src, dest,offX, offY,attachX, attachY,propsMustMatch));

}

public void putAttachmentsOnBoard(){

for(e2dAttachPoint a : attachments){

Page 231: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 223

a.setCornerX(boardX + a.getCornerX());a.setCornerY(boardY + a.getCornerY());

}

}

public boolean attaches(e2dPiece p){

//two pieces without attachment points always attachif(attachments == null && p.attachments == null)

return true;

//if one or the other piece defines attachments, but NOT//both, then we must not attachif(attachments == null || p.attachments == null)

return false;

for(e2dAttachPoint a : attachments){

for(e2dAttachPoint b : p.attachments){

if(a.getDestAttach().equals(b.getSourceAttach())){

System.err.println(""+a.getCornerX()+" "+b.getCornerX()+" "+a.getCornerY()+" "+b.getCornerY());if(a.getCornerX() == b.getCornerX() &&

a.getCornerY() == b.getCornerY()){

if(a.propsMustMatch()){

//check that the properties on the attach points matchfor(e2dShape s : shapes){

for(e2dShape t : p.shapes){

if(s.isOnShape(a.getShapeOffX(), a.getShapeOffY()) &&t.isOnShape(b.getShapeOffX(), b.getShapeOffY()))

{if(s.getProperty() == t.getProperty()){

return true;}

}}

}

Page 232: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

224 APPENDIX A. SOURCE CODE

}else{

return true; //found a legit attach point}

}}

}}return false; //failed to find matching attach points

}

public int getRotCount(){

return rotCount;}

public int getFlipXCount(){

return flipXCount;}

public int getFlipYCount(){

return flipYCount;}public void clearTransformationMemory(){

rotCount = flipXCount = flipYCount = 0;}

}

A.6.9 e2dPlayer

/*************************************************************************The Five Tans ** **e2dPlayer.java ** **e2d Core class for creating game players. Extended by e2d code. ** **CHANGELOG: **Editors Date Description **jlc, nt 04/05/2006 Created. **aja 04/26/2006 added in new useful accesors **aja 04/2706 added in handviewpanel per player *

Page 233: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 225

* will make life easier for the GUI *************************************************************************/

package e2dCore;

/*** Class representing a player in e2d** @author jlc**/

public class e2dPlayer {/****************************************************************************** Private members****************************************************************************/private e2dSet<e2dPiece> hand;

public int score; //public so generated code can refer to them easillypublic String name;

/****************************************************************************** Public Behaviors****************************************************************************//****************************************************************************** Constructors****************************************************************************//*** Construct a generic player*/public e2dPlayer(){

hand = new e2dSet<e2dPiece>();score = 0;name = new String();

}

/*** Construct a player with the given name** @param n* the name*/public e2dPlayer(String n){

hand = new e2dSet<e2dPiece>();score = 0;name = new String(n);

Page 234: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

226 APPENDIX A. SOURCE CODE

}

/*** Construct a new copy of the player** @param p* player to copy*/public e2dPlayer(e2dPlayer p){

hand = new e2dSet<e2dPiece>();// deep copyfor (e2dPiece t : p.hand){

try{

if(t.getClass().equals(Class.forName("e2dCore.e2dPiece"))){

hand.add(new e2dPiece(t));}else{

//we’re a subclass. Do magicClass[] copyParams = new Class[2];copyParams[0] = t.getClass().getDeclaringClass();copyParams[1] = t.getClass();Object[] copyArgs = new Object[2];copyArgs[0] = copyParams[0].newInstance();copyArgs[1] = t;

hand.add(t.getClass().getConstructor(copyParams).newInstance(copyArgs));}

}catch(Exception e){

System.err.println("player failed to copy right");hand.add(new e2dPiece(t));

}

}score = p.score;name = new String(p.name);

}

/*****************************************************************************

Page 235: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 227

* Accessors****************************************************************************//*** Get this player’s score** @return this player’s score*/public int getScore(){

return score;}

/*** get this player’s name** @return the name*/public String getName(){

return name;}

/*** Set this player’s score** @param s* new score*/public void setScore(int s){

score = s;}

/*** Change the player’s score by some amount** @param i* amount to change*/public void addToScore(int i){

score += i;}

/* could be usefull ;) adam *//**

Page 236: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

228 APPENDIX A. SOURCE CODE

* increment the score by one*/public void incrementScore(){

score++;}

/*** decrement the score by one**/public void decrementScore(){

score--;}

/*** Set this player’s name** @param n* new name*/public void setName(String n){

name = n;}

/*** Get a reference to this player’s hand** @return the hand*/public e2dSet<e2dPiece> getHand(){

return hand;}

/* New Useful assecors to the hand -- by adam *//*** Add a piece to the player’s hand*/public void addPieceToHand(e2dPiece p){

p.putInHand();hand.add(p);

}

Page 237: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 229

/*** Remove a piece from the player’s hand** @param p* piece to be removed* @throws IllegalArgumentException* this piece is not in this hand*/public void removePieceFromHand(e2dPiece p) throws IllegalArgumentException{

if (!p.isInHand())throw new IllegalStateException(

"Piece claiming not to be in hand is to be removed");for (int i = 0; i < hand.size(); i++){

if (p.equals(hand.get(i))){

hand.remove(i);p.removeFromHand();return;

}}throw new NoSuchPieceInSetException("Piece not found in hand");

}

}

A.6.10 e2dProperty

package e2dCore;

import java.awt.Color;

/*** Stores the property used by e2dPiece. Properties in e2d are ordered, however,* other functions may need unordered properties as temporaries. The ordering* of ordered properties (those used in an e2dGame) are preserved by using the* e2dProperty(String, boolean) constructor when getting ordered properties.** @author jlc, aja**/

public class e2dProperty {private static int nthCreated = 0;private int order;

Page 238: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

230 APPENDIX A. SOURCE CODE

/*name of the property*/private String name;

/*color associated with the property* Good for the GUI :)*/private Color color;

/**************************************** Constructors****************************************/

/*** Create a copy of the given e2dProperty* @param the property to copy*/public e2dProperty(e2dProperty p){

name = new String(p.name);color = new Color(p.color.getRGB());order = p.order;

}

/*** Create an ordered property with the given name.* @param n the name* @param first dummy variable to differentiate this from e2dProperty(String)*/public e2dProperty(String n, boolean first){

name = n;color = Color.RED;order = nthCreated++;

}

/*** Create the default property**/public e2dProperty(){

name = null;color = Color.RED;order = -1;

}

Page 239: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 231

/*** Create an unordered property with no name and the given color* @param col the color*/public e2dProperty(Color col){

name = null;color = col;

}

/*** Create an unordered property with the given name and the default color* @param n the name*/public e2dProperty(String n){

name = n;

/*set color to default, red*/color = Color.RED;order = -1;

}

/*** Create an unordered property with the given name and color* @param n the name* @param col the color*/public e2dProperty(String n, Color col){

name = n;color = col;order = -1;

}

/**************************************** equals method***************************************//*** Equals. Overrides java.lang.Object.equals() for comparing two properties* Properties are equivalent if and only if their names and colors are the same* @param p The property that will be compared to* @return true iff this is equivalent to p*/public boolean equals(e2dProperty p)

Page 240: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

232 APPENDIX A. SOURCE CODE

{if(name == p.getName() && color == p.getColor())

return true;else

return false;}

/*** Compare the ordering of two properties* @param p property to be compared to* @return 0 if created at the same time (ie, same property),* -1 if this is older* 1 if p is older* @throws IllegalStateException orders are* unknown or integers cannot compare well*/public int compare(e2dProperty p) throws IllegalStateException{

if(order == -1 || p.order == -1) //unknown orderthrow new IllegalStateException();

if(order == p.order)return 0;

if(order < p.order)return -1;

if(order > p.order)return 1;

throw new IllegalStateException();}

/**************************************** Accesors***************************************//*** Get this property’s name* @return the name*/public String getName(){

return name;}

/*** Get this property’s color* @return the color*/public Color getColor()

Page 241: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 233

{return color;

}

/*** Set this property’s name* @param n new name*/public void setName(String n){

name = n;}

/*** Set this property’s color* @param col new color*/public void setColor(Color col){

color = col;}

}

A.6.11 e2dSet

/*************************************************************************The Five Tans ** **e2dSet.java ** **e2d Core class defining sets consistant with the e2d LRM. Used heavily**by other e2d classes for storage when extra e2d-specific information **is needed. Really just a wrapper around an ArrayList ** **CHANGELOG: **Editors Date Description **jlc, nt 04/05/2006 Created. **aja 04/25/2006 changed to extend ArrayList **aja 04/25/2003 changed back, but added in all the ** functionality of arraylist in **aja 04/26/2006 fixed functionality and a whole ** bunch of useful constructors **jlc 04/27/2006 Fixed bug related to a.clone() in the ** e2dSet(ArrayList<E> a) constructor *

Page 242: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

234 APPENDIX A. SOURCE CODE

*jlc 04/28/2006 Fed up with the excessive similarites to** ArrayList. Now just extends ArrayList *************************************************************************/

package e2dCore;

import java.util.ArrayList; import java.util.Random;

/*** Basic set type for e2d. Extends ArrayList, so the normal ArrayList* accessors work. Note that deep copies are YOUR responsibility, there* is no good way to do that here. Includes function to randomly choose* a member of the set.* @author jlc* @param <E> Classtype to be stored.*/public class e2dSet<E> extends ArrayList<E>

{private static final long serialVersionUID = 6166216085592592953L;private Random rand;

/*** Default constructor. Creates an empty set.**/public e2dSet(){

super();rand = new Random();

}

/*** Creates a shallow copy of the given set* @param a Set to be copied.*/public e2dSet(e2dSet<E> a){

super(a);rand = new Random();

}

/*** Choose a member of the set at random.* @return Randomly-chosen member of the set*/public E getMemberAtRandom()

Page 243: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 235

{int s = size();if(s > 0){

int i = rand.nextInt(s);return get(i);

}else{

throw new EmptySetException("The set is empty");}

}

/*** Hack to make life easier in code generation* @param o Object to add* @return a reference to this object*/public e2dSet<E> addR(E o){

add(o);return this;

}

/*** Hack to make life easier in code generation* @param o array to add* @return reference to this object*/public e2dSet<E> addAllR(e2dSet<E> o){

addAll(o);return this;

}

/*** Hack to make life easier in code generation* @param o element to remove* @return reference to this object*/public e2dSet<E> removeR(e2dSet<E> o){

remove(o);return this;

}}

Page 244: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

236 APPENDIX A. SOURCE CODE

A.6.12 e2dShape

package e2dCore;

import java.awt.Color; import java.awt.Graphics;

/*** the shape aspect of a piece for e2d** @author aja, jlc**/

public class e2dShape {/****************************************************************************** Data Members****************************************************************************/

protected int offX;

protected int offY;

public int width; //for ease of code generation

public int height; //for ease of code generation

protected e2dSet<e2dBasicShape> basicShapes;

protected boolean onBoard = false;

public e2dProperty prop; //makes code generation easier

protected e2dFlags flags;

/****************************************************************************** Constructors** all constructors written by Adam Aviv and Jamie Culpon****************************************************************************//*** copy constructor for e2dPiece** @param s* the e2dShape to copy*/public e2dShape(e2dShape s){

Page 245: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 237

offX = s.offX;offY = s.offY;width = s.width;height = s.height;

// deep copybasicShapes = new e2dSet<e2dBasicShape>();for (e2dBasicShape b : s.basicShapes)

basicShapes.add(new e2dBasicShape(b));

onBoard = s.onBoard;

prop = s.prop;

flags = s.flags;}

/*** Create a 1x1 shape with the default property on the board with the offsets* of a and b** @param a* xwise offset for this shape* @param b* ywise offset for this shape*/public e2dShape(int x, int y){

offX = x;offY = y;

basicShapes = new e2dSet<e2dBasicShape>();

/* default width and height implied */width = 1;height = 1;

/* default color or property */prop = new e2dProperty();

onBoard = false;

flags = new e2dFlags();

/* add in the basic shape */basicShapes.add(new e2dBasicShape(offX, offY, prop));

Page 246: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

238 APPENDIX A. SOURCE CODE

}

/*** constructor that copys the basic shapes from s, but sets the offSets to x* and y** @param x* the new x offset* @param y* the new y offset* @param s* the shape to copy*/public e2dShape(int x, int y, e2dShape s){

offX = x;offY = y;

basicShapes = new e2dSet<e2dBasicShape>();

/* default width and height implied */width = s.getWidth();height = s.getHeight();

onBoard = s.onBoard;

flags = s.flags;/* default color or property */prop = s.getProperty();

/* add in the basic shape */for (int i = 0; i < s.getBasicShapes().size(); i++){

e2dBasicShape temp = s.getBasicShapes().get(i);basicShapes.add(new e2dBasicShape(temp.getOffX(), temp.getOffY(), prop));

}}

/*** Constructor to creat a new shape with offset* x and y with the property p** @param x* the new x offset* @param y

Page 247: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 239

* the new y offset* @param p* the property of the shape*/public e2dShape(int x, int y, e2dProperty p){

offX = x;offY = y;

basicShapes = new e2dSet<e2dBasicShape>();

/* default width and height implied */width = 1;height = 1;

onBoard = false;

flags = new e2dFlags();

/* default color or property */prop = p;/* add in the basic shape */basicShapes.add(new e2dBasicShape(offX, offY, prop));

}

/*** constructor to create a new shape with offset x and y with a new property* of the Color col** @param x* the new x offset* @param y* the new y offset* @param col* the color for the property*/

public e2dShape(int x, int y, int w, int h){

offX = x;offY = y;

basicShapes = new e2dSet<e2dBasicShape>();

width = w;

Page 248: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

240 APPENDIX A. SOURCE CODE

height = h;

onBoard = false;

flags = new e2dFlags();

/* default color or property */prop = new e2dProperty();

for (int i = 0; i < w; i++){

for (int j = 0; j < h; j++){

/* add in a basic shape for dimensions */basicShapes.add(new e2dBasicShape(offX + i, offY + j, prop));

}}

}

/*** constuctor with a property x and y offset and a width and height** @param x* the x offset* @param y* the y offset* @param w* the width* @param h* the height* @param p* the property*/public e2dShape(int x, int y, int w, int h, e2dProperty p){

offX = x;offY = y;

basicShapes = new e2dSet<e2dBasicShape>();

width = w;height = h;

onBoard = false;

Page 249: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 241

flags = new e2dFlags();

/* default color or property */prop = p;

for (int i = 0; i < w; i++){

for (int j = 0; j < h; j++){

/* add in a basic shape for dimensions */basicShapes.add(new e2dBasicShape(offX + i, offY + j, prop));

}}

}

/****************************************************************************** Clone method****************************************************************************/public e2dShape clone(){

e2dShape p = new e2dShape(offX, offY, prop);return p;

}

/****************************************************************************** Set Flags method****************************************************************************/

/*** sets the flags to the refference provided*/public void setFlags(e2dFlags f){

flags = f;}

/****************************************************************************** Equals method****************************************************************************//*** determine if this shape is geometrically equivalent to the given shape I* don’t really understant code, but jamie assures me it is correct --aja** @author jlc*/

Page 250: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

242 APPENDIX A. SOURCE CODE

public boolean equals(e2dShape s){

if (prop != s.prop)return false;

// case 1: unrotated, unflipped equalsif (/* offX == s.offX && offY == s.offY && */this.compareBasicShapes(s))

return true;

// make a copy for rotationse2dShape munged = new e2dShape(this);

if (flags.canRotate()){

for (int i = 0; i < 4; i++){

munged.rotateL();// case 2: rotated, but can’t flipif ((munged.offX == s.offX) && (munged.offY == s.offY)

&& (this.compareBasicShapes(s)))return true;

// case 3: rotated, and flip over horizif (flags.canFlipX()){

munged.flipX();if ((munged.offX == s.offX) && (munged.offY == s.offY)

&& (this.compareBasicShapes(s)))return true;

munged.flipX();}// case4: roatated, and flip over vertif (flags.canFlipY()){

munged.flipY();if ((munged.offX == s.offX) && (munged.offY == s.offY)

&& (this.compareBasicShapes(s)))return true;

munged.flipY();}

}} else{

// case5: not rotated, flipped over horizif (flags.canFlipX()){

munged.flipX();

Page 251: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 243

if ((munged.offX == s.offX) && (munged.offY == s.offY)&& (this.compareBasicShapes(s)))

return true;munged.flipX();

}// case6: not rotated, flipped over vertif (flags.canFlipY()){

munged.flipY();if ((munged.offX == s.offX) && (munged.offY == s.offY)

&& (this.compareBasicShapes(s)))return true;

munged.flipY();}// case6: not rotated, can flip over bothif (flags.canFlip()){

munged.flipX();munged.flipY();if ((munged.offX == s.offX) && (munged.offY == s.offY)

&& (this.compareBasicShapes(s)))return true;

munged.flipY();munged.flipX();

}}return false;

}

/*** compares a shapes basicshapes using geomitric comparison I again don’t know* what is going on, but I trust jamie -- adam** @author jlc* @param s* the shape to compare basic shapes on* @return true if geometrically equivalent, false if not*/public boolean compareBasicShapes(e2dShape s){

if (basicShapes.size() != s.basicShapes.size())return false;

boolean matchesBS = false;for (e2dBasicShape b : basicShapes){

for (e2dBasicShape c : s.basicShapes)

Page 252: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

244 APPENDIX A. SOURCE CODE

{if ((b.getOffX() == c.getOffX()) && (b.getOffY() == c.getOffY())){

matchesBS = true;break;

}}

if (!matchesBS)return false;

matchesBS = false;}

return true;}

/****************************************************************************** Accessors*****************************************************************************/

/*** Gets a set of basic shapes representing this shape** @return e2dSet of basic shapes that construct this shape*/public e2dSet<e2dBasicShape> getBasicShapes(){

return basicShapes;}

/*** method returns offset value of x** @return the value of x*/public int getOffX(){

return offX;}

/*** method returns the offset value of y** @return the value of y

Page 253: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 245

*/public int getOffY(){

return offY;}

/*** method returns the width of the shape** @return the value of width*/public int getWidth(){

return width;}

/*** method returns the value of the height** @return the value of height*/public int getHeight(){

return height;}

/*** returns wheather shape is onBoard** @return true for on board false for off board*/public boolean isOnBoard(){

return onBoard;}

/*** returns the e2dProperty of the shape** @return the reference to its e2dProperty*/public e2dProperty getProperty(){

return prop;}

Page 254: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

246 APPENDIX A. SOURCE CODE

/*** sets the value of x** @param xx* the value to set x to*/public void setOffX(int xx){

offX = xx;}

/*** sets the value of y** @param yy* the value to set y to*/public void setOffY(int yy){

offY = yy;}

/*** sets the value of x and y** @param xx* the value to set x to* @param yy* the value to set y to*/public void setOffXY(int xx, int yy){

offX = xx;offY = yy;

}

/*** sets the wheather the shape is on the board** @param b* true for on, false for off*/public void setOnBoard(boolean b){

onBoard = b;}

Page 255: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 247

/*** sets the value of the e2dProperty of the shape** @param p* the property to set it to*/public void setProperty(e2dProperty p){

prop = p;

for(e2dBasicShape b : basicShapes){

b.setProp(prop);}

}

/****************************************************************************** Public Behaviors****************************************************************************//*** Marks this shape as occuring on the board at the given location** @param x* the x coordinate of where the shape is placed* @param y* the y coordinate of where the shape is placed*/public void putOnBoard(int x, int y){

onBoard = true;

for (e2dBasicShape i : basicShapes){

i.putOnBoard(x + i.getOffX(), y + i.getOffY());

}}

/*** Marks this shape as no longer occuring on the board**/public void removeFromBoard(){

onBoard = false;

Page 256: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

248 APPENDIX A. SOURCE CODE

for (e2dBasicShape i : basicShapes)i.removeFromBoard();

}

/*** Check if this shape is adjacent to the given piece** @param p* piece which may be adjacent to this shape* @return true iff this shape is adjacent to p* @throws NotOnBoardException* either p or this shape is not on the board*/public boolean adjacent(e2dPiece p) throws NotOnBoardException{

return p.adjacent(this);}

/*** Check if this shape is adjacent to the given shape** @param s* shape which may be adjacent to this one* @return true iff s is adjacent to this shape* @throws NotOnBoardException* either s or this shape is not on the board*/public boolean adjacent(e2dShape s) throws NotOnBoardException{

int bx, by, cx, cy;if (onBoard && s.onBoard){

for (e2dBasicShape b : basicShapes){

bx = b.getBoardX();by = b.getBoardY();for (e2dBasicShape c : s.basicShapes){

cx = c.getBoardX();cy = c.getBoardY();/** System.out.println("("+bx+","+by+")"+" adjacentp "+* "("+cx+","+cy+")");*/

if ((by == cy && ((bx - 1) == cx || (bx + 1) == cx))

Page 257: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 249

|| (bx == cx && ((by - 1) == cy || (by + 1) == cy))){

// System.out.println("t");return true;

}// System.out.println("nil");

}}return false;

} else{

throw new NotOnBoardException();}

}

/*** Determines if this shape overlaps the given piece** @param p* piece that this shape may cover* @return true iff this overlaps the piece* @throws NotOnBoardException* either this or p is not on the board*/public boolean overlaps(e2dPiece p) throws NotOnBoardException{

return p.overlaps(this);}

/*** Determines if this shape overlaps the given shape** @param s* Shape that this may overlap* @return true iff this overlaps s* @throws NotOnBoardException* either this or s is not on the board*/public boolean overlaps(e2dShape s) throws NotOnBoardException{

if (onBoard && s.onBoard){

for (e2dBasicShape b : basicShapes){

for (e2dBasicShape c : s.basicShapes){

Page 258: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

250 APPENDIX A. SOURCE CODE

if (b.getBoardX() == c.getBoardX() &&b.getBoardY() == c.getBoardY())return true;

}}return false;

} else{

throw new NotOnBoardException();}

}

/*** rotate a shape left**/public void rotateL(){

if (!flags.canRotate())throw new TransformationNotPermittedException("Cannot rotate this shape");

for (e2dBasicShape b : basicShapes){

int temp = b.getOffX();b.setOffX(-b.getOffY());b.setOffY(temp);

}}

/*** rotate a shape right**/public void rotateR(){

if (!flags.canRotate())throw new TransformationNotPermittedException("Cannot rotate this shape");

for (e2dBasicShape b : basicShapes){

int temp = b.getOffX();b.setOffX(b.getOffY());b.setOffY(-temp);

}

Page 259: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 251

}

/*** flip a shape over its x axis**/public void flipX(){

if (!flags.canFlipX())throw new TransformationNotPermittedException(

"Cannot flip this shape over X");

for (e2dBasicShape b : basicShapes){

b.setOffY(-b.getOffY());}

}

/*** flip a shape over its y axis**/public void flipY(){

if (!flags.canFlipY())throw new TransformationNotPermittedException(

"Cannot flip this shape over Y");

for (e2dBasicShape b : basicShapes){

b.setOffX(-b.getOffX());}

}

/****************************************************************************** GUI BEHAVIOR** All code written by Adam Aviv****************************************************************************//*** checks to see if the coordinate x and y corrispond to a basicShape in the* set** @param x* x coordinate on the board* @param y

Page 260: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

252 APPENDIX A. SOURCE CODE

* y coordinate on the board* @return true for it is on the shape and false if not*/public boolean isOnShape(int x, int y){

for (e2dBasicShape b : basicShapes){

if ((x == b.getBoardX()) && (y == b.getBoardY()))return true;

}return false;

}

/*** method drawShape calls the draw function for the basic shapes** @author aja2002* @param g* the graphics component to draw on* @param xMid* the middle in the x direction in pixels* @param yMid* the middle in the y direction in pixels* @param granulation* the current granulation of the board* @param selected* wheather the top piece is selected*/public void drawShape(Graphics g, int xMid, int yMid, int granulation,

boolean selected){

for (int i = 0; i < basicShapes.size(); i++){

e2dBasicShape temp = basicShapes.get(i);temp.drawBasicShape(g, xMid, yMid, granulation, selected);

}

}

/*** calls the drawBaisShapeFromOrigin for each basic shape in set** @author aja2002* @param g* the graphics component

Page 261: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 253

* @param xCord* the x coordinate for origin* @param yCord* the y coordinate for origin* @param xMid* the middle in the x direction in pixels* @param yMid* the middle in the y direction in pixels* @param granulation* the current granulation of the board* @param selected* wheather the top piece is selected*/public void drawShapeFromOrigin(Graphics g, int xCord, int yCord, int xMid,

int yMid, int granulation, boolean selected){

for (int i = 0; i < basicShapes.size(); i++){

e2dBasicShape temp = basicShapes.get(i);temp.drawBasicShapeFromOrigin(g, xCord, yCord, xMid, yMid, granulation,

selected);}

}

/*** draws the outline of a shape** @param g* the graphics component* @param xCord* the x location to draw on in grid squares* @param yCord* the y location to draw on in grid squares* @param xMid* where the middle of the board is in pixels in the x direction* @param yMid* where the middle of the board is in pixels in the y direction* @param granulation* the granulation in pixels*/public void drawOutlineShape(Graphics g, int xCord, int yCord, int xMid,

int yMid, int granulation){

for (e2dBasicShape b : basicShapes)

Page 262: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

254 APPENDIX A. SOURCE CODE

{b.drawOutlineBasicShape(g, xCord, yCord, xMid, yMid, granulation);

}

}/*** checks weather a shapes basic shapes are off the board in the width direction* if the basic shapes x-origin is x and the boards with is [xmin,xmax]* @param x the x location* @param xmin the minimun of the board in the width* @param xmax the maximum of the board in the width* @return*/public boolean offWidthBoard(int x, int xmin, int xmax){

for(e2dBasicShape b : basicShapes){

if(x+b.getOffX() < xmin || x+b.getOffX() > xmax)return true;

}return false;

}

/*** checks weather a shapes basic shapes are off the board in the height direction* if the basic shapes origin is x and y and the boards with is [ymin,ymax]* @param x the x location* @param y the y location* @param ymin the minimun of the board in the height* @param ymax the maximum of the board in the height* @return*/public boolean offHeightBoard(int y, int ymin, int ymax){

for(e2dBasicShape b : basicShapes){

if(y+b.getOffY() < ymin || y+b.getOffY() > ymax)return true;

}return false;

}

}

Page 263: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 255

A.6.13 Exceptions

package e2dCore;

public class EmptySetException extends IllegalStateException {

/****/private static final long serialVersionUID = 6693525654747366367L;

public EmptySetException(){

super();}

public EmptySetException(String msg){

super(msg);}

}

package e2dCore;

/*** Exception indicating that the given piece does not have a an origin.** @author jlc**/

public class NoOriginException extends IllegalStateException {private static final long serialVersionUID = -7462747283036827852L;

/*** default constructor**/public NoOriginException(){

super();}

/*** generate an exception with a given message** @param msg

Page 264: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

256 APPENDIX A. SOURCE CODE

* the given message*/public NoOriginException(String msg){

super(msg);}

}

package e2dCore;

/*** An exception that should be thrown when a piece can not be found in a set** @author jlc**/

public class NoSuchPieceInSetException extendsIllegalArgumentException {

/*** default constructor**/public NoSuchPieceInSetException(){

super();}

/*** generate an exception with the specified message** @param msg* the specified message*/public NoSuchPieceInSetException(String msg){

super(msg);}

}

/*************************************************************************The Five Tans ** **NoSuchPlayerException.java ** **e2dCore exception to be thrown when a gamestate request tries to **modify a player not currently in the game. *

Page 265: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 257

* **Change Log **jlc 04/28/06 Added some javadoc *************************************************************************/

package e2dCore;

/*** Exception thrown to indicate that the given e2dPlayer was not found* @author jlc2108**/

public class NoSuchPlayerException extends IllegalArgumentException{

private static final long serialVersionUID = 6043682936696925150L;private e2dPlayer badPlayer;

/*** Creates a default, empty NoSuchPlayerException**/public NoSuchPlayerException(){

//use compiler defaults}

/*** Creates a NoSuchPlayerException with the given error message* @param msg error message to be passed to the caller*/public NoSuchPlayerException(String msg){

super(msg);}

/*** Creates a NoSuchPlayerException with an error message and a* copy of the player that caused the problem.* @param msg* @param p*/public NoSuchPlayerException(String msg, e2dPlayer p){

super(msg);badPlayer = new e2dPlayer(p);

Page 266: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

258 APPENDIX A. SOURCE CODE

}

public e2dPlayer getBadPlayer(){

return badPlayer;}

}

package e2dCore;

/*** An excpetion that should be thrown when a requested property can not be found** @author jlc**/

public class NoSuchPropertyException extends IllegalStateException {private static final long serialVersionUID = -2749964130669733135L;

/*** Generates a default exception**/public NoSuchPropertyException(){

super();}

/*** Generates an exception with a specified error message** @param msg* the error message*/public NoSuchPropertyException(String msg){

super(msg);}

}

package e2dCore;

/**** An exception that should be thrown when attempting to manipulate from the* board and the piece is not there

Page 267: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.6. E2DCORE 259

** @author jlc**/

public class NotOnBoardException extends IllegalStateException {private static final long serialVersionUID = -4302497778709067288L;

/*** defualt constructor**/public NotOnBoardException(){

super();}

/*** include a message to be displayed** @param msg* the message to display*/public NotOnBoardException(String msg){

super(msg);}

}

package e2dCore;

public class TransformationNotPermittedException extendsIllegalArgumentException

{public TransformationNotPermittedException(){

super();}

public TransformationNotPermittedException(String msg){

super(msg);}

}

Page 268: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

260 APPENDIX A. SOURCE CODE

A.7 e2dGUI

A.7.1 GUIe2dBagViewPanel

/******************************************************************************** GUIe2dBagViewPanel.java** Panel used to displaying the bag** Written by Adam Aviv and edited (at one point) by Hugh Gordon******************************************************************************/

package e2dGUI;

import java.awt.GridLayout;

import javax.swing.JPanel;

import e2dCore.e2dPiece; import e2dCore.e2dPlayer; importe2dCore.e2dSet;

/*** Panel used to display the bag** @author aja2002**/

public class GUIe2dBagViewPanel extends JPanel {

private static final long serialVersionUID = 1L;

private e2dSet<e2dPiece> pieces;

private e2dSet<GUIe2dPieceGraphicsPanel> piecesPanels;

private GUIe2dFrame theTop;

private JPanel displayPanel;

private boolean selectedFromBag = false;

private int currentIndex = -1;

private e2dPiece selectedPiece = null;

Page 269: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 261

/*** Constructor** @param p* the set of pieces to add* @param w* the width of the panel* @param h* the height of the panel* @param t* the top Frame to make calls to*/public GUIe2dBagViewPanel(e2dSet<e2dPiece> p, GUIe2dFrame t){

pieces = p; // pointer to the list, global updatetheTop = t;displayPanel = new JPanel();

piecesPanels = new e2dSet<GUIe2dPieceGraphicsPanel>();displayPanel.setLayout(new GridLayout(1, pieces.size()));for (int i = 0; i < pieces.size(); i++){

e2dPiece piece = pieces.get(i);GUIe2dPieceGraphicsPanel tempPanel = new GUIe2dPieceGraphicsPanel(

120, 120, 40, this, i);tempPanel.updateCurrentPiece(new e2dPiece(piece));

piecesPanels.add(i, tempPanel);

// add it to the viewable paneldisplayPanel.add(tempPanel);

}this.add(displayPanel);

}

/*** Method called from lower panel to tell the bag panel what was clicked** @param index* the index of graphic panel that was clicked*/public void clicked(int index){

currentIndex = index;selectedFromBag = true;if (theTop.moveFromBag)

Page 270: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

262 APPENDIX A. SOURCE CODE

{if (!pieces.isEmpty() && index < pieces.size()){

selectedPiece = pieces.get(index);if (theTop.moveToHand){

e2dPiece[] returnPieces = new e2dPiece[2];returnPieces[0] = new e2dPiece(selectedPiece);returnPieces[0].putInHand();returnPieces[1] = new e2dPiece(selectedPiece);theTop.setPlayedPiece(returnPieces);

}else

theTop.setCurrentPiece(new e2dPiece(selectedPiece));}

}}

/*** sets the state so nothing is selected**/public void unselect(){

selectedPiece = null;currentIndex = -1;selectedFromBag = false;

}

/*** Updates the bag, given a new set of e2dPiece’s** @param newBag* the set of e2dPiece’s*/

public void setBag(e2dSet<e2dPiece> newBag){

pieces = newBag;

displayPanel.removeAll();piecesPanels = new e2dSet<GUIe2dPieceGraphicsPanel>();displayPanel.setLayout(new GridLayout(1, pieces.size()));for (int i = 0; i < pieces.size(); i++){

e2dPiece piece = pieces.get(i);

Page 271: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 263

GUIe2dPieceGraphicsPanel tempPanel = new GUIe2dPieceGraphicsPanel(120, 120, 40, this, i);

tempPanel.updateCurrentPiece(new e2dPiece(piece));

piecesPanels.add(i, tempPanel);

// add it to the viewable paneldisplayPanel.add(tempPanel);

}

displayPanel.validate();this.validate();

}

}

A.7.2 GUIe2dBoard

/******************************************************************************** GUIe2dBoard** written by Adam Aviv and Hugh Gordon******************************************************************************/

package e2dGUI;

import java.awt.BorderLayout; import java.awt.Color; importjava.awt.Dimension; import java.awt.Graphics; importjava.awt.GridLayout; import java.awt.event.ActionEvent; importjava.awt.event.ActionListener; import java.awt.event.MouseEvent;import java.awt.event.MouseListener; importjava.awt.event.MouseMotionListener; import java.util.ArrayList;

import javax.swing.JButton; import javax.swing.JOptionPane; importjavax.swing.JPanel;

import e2dCore.e2dBoard; import e2dCore.e2dPiece; importe2dCore.e2dSet; import e2dCore.e2dShape;

/*** The class that renders the pieces on the board and all the functionality of* zooming and changing view** @author aja2002**/

Page 272: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

264 APPENDIX A. SOURCE CODE

public class GUIe2dBoard extends JPanel {

/*** GUIe2dBoard for fun and e2d*/private static final long serialVersionUID = -2608662078772447581L;

private e2dSet<e2dPiece> pieces;

private e2dPiece theCurrentPiece;

/* height and width of the current view of the board *//* in pixels */public int boardwidth;

public int boardheight;

private int gridWidth;

private int gridHeight;

private final int initGridWidth;

private final int initGridHeight;

private int maxWidth = 500;

private int maxHeight = 500;

/* number of pixels per grid length */private int granulation = 50;

/** @param focus(x/y) is the amount of pixels to move the center of the view if* odd number of shapes specified focus is set to one granulation if even* focus is set to 0 each set per direction*/private int focusX;

private int focusY;

private BoardGraphicsPanel theBoard;/* graphics class */

private NamePanel theName;

private JButton zoomInButton;

Page 273: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 265

private JButton zoomOutButton;

private JButton zoomToPiecesButton;

private JButton focusLeft;

private JButton focusRight;

private JButton focusUp;

private JButton focusDown;

private JButton focusCenter;

private GUIe2dFrame theTop;

private boolean selectPhase;

private e2dSet<e2dPiece> selectedPieces;

private e2dPiece selectedPiece = null;

private e2dPiece outLinePiece; /* for drawing the outline */

private e2dBoard coreBoard;

/*** Constructor** @param b* e2dBoard from core* @param t* the top level frame*/public GUIe2dBoard(e2dBoard b, GUIe2dFrame t){

coreBoard = b;int w, h;if ((w = coreBoard.getWidth()) < 0)

w = 20;if ((h = coreBoard.getHeight()) < 0)

h = 20;

pieces = new e2dSet<e2dPiece>();

Page 274: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

266 APPENDIX A. SOURCE CODE

theTop = t;

selectPhase = true;

selectedPieces = new e2dSet<e2dPiece>();

while (granulation * w < maxWidth || granulation * h < maxHeight){

granulation++;}

/** step until granulation reaches size needed to display requirements*/

while (granulation * w > maxWidth || granulation * h > maxHeight){

granulation--;}

gridWidth = w;gridHeight = h;

initGridWidth = w;initGridHeight = h;

boardwidth = granulation * w;boardheight = granulation * h;

focusX = 0;focusY = 0;

/* if odd shift focus */if (gridWidth % 2 != 0)

focusX = 1;if (gridHeight % 2 != 0)

focusY = 1;

theBoard = new BoardGraphicsPanel(boardwidth, boardheight, granulation,focusX, focusY, pieces);

theBoard.setCurrentPiece(theCurrentPiece);theName = new NamePanel("Domain");BorderLayout bLayout = new BorderLayout();setLayout(bLayout);

setSize(maxWidth + 100, maxHeight + 100);setLocation(100, 100);

Page 275: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 267

/* all the buttons and their associated action */zoomInButton = new JButton("Zoom In");zoomOutButton = new JButton("Zoom Out");zoomToPiecesButton = new JButton("Zoom to shapes");focusRight = new JButton(">");focusLeft = new JButton("<");focusUp = new JButton("^");focusDown = new JButton("v");focusCenter = new JButton("*");

zoomInButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

zoom(1, 2);}

});zoomOutButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

zoom(-1, 2);}

});

zoomToPiecesButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

zoomToPieces();}

});focusRight.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

updateFocus(focusX - 2, focusY);}

});focusLeft.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

updateFocus(focusX + 2, focusY);}

Page 276: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

268 APPENDIX A. SOURCE CODE

});focusUp.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

updateFocus(focusX, focusY + 2);}

});focusDown.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

updateFocus(focusX, focusY - 2);}

});focusCenter.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

focusX = 0;focusY = 0;

/* if odd shift focus */if (gridWidth % 2 != 0)

focusX = 1;if (gridHeight % 2 != 0)

focusY = 1;

updateFocus(focusX, focusY);

}});

/* putting it all togeather */JPanel northPanel = new JPanel();JPanel northWestPanel = new JPanel();JPanel northEastPanel = new JPanel();JPanel northCenterPanel = new JPanel();JPanel northCenterSouthPanel = new JPanel();

northEastPanel.setLayout(new GridLayout(3, 1));northWestPanel.setLayout(new BorderLayout());northCenterPanel.setLayout(new BorderLayout());northPanel.setLayout(new BorderLayout());northCenterSouthPanel.setLayout(new GridLayout(1, 2));

Page 277: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 269

/* Add buttons only when they can be used */if (coreBoard.getWidth() < 0){

northWestPanel.add(focusRight, BorderLayout.EAST);northWestPanel.add(focusLeft, BorderLayout.WEST);

}if (coreBoard.getHeight() < 0){

northWestPanel.add(focusUp, BorderLayout.NORTH);northWestPanel.add(focusDown, BorderLayout.SOUTH);

}if (coreBoard.getHeight() < 0 || coreBoard.getWidth() < 0){

northWestPanel.add(focusCenter, BorderLayout.CENTER);}

northCenterPanel.add(theName, BorderLayout.NORTH);northCenterPanel.add(northCenterSouthPanel, BorderLayout.SOUTH);

if (coreBoard.getHeight() < 0 && coreBoard.getWidth() < 0){

northEastPanel.add(zoomOutButton);northEastPanel.add(zoomInButton);northEastPanel.add(zoomToPiecesButton);

}

northPanel.add(northWestPanel, BorderLayout.WEST);northPanel.add(northEastPanel, BorderLayout.EAST);northCenterPanel.add(theName, BorderLayout.CENTER);northPanel.add(northCenterPanel, BorderLayout.CENTER);add(northPanel, BorderLayout.NORTH);

add(theBoard, BorderLayout.CENTER);

}

/*** returns the piece set** @return the set of pieces on the board*/public e2dSet<e2dPiece> getPieceSet(){

return pieces;}

Page 278: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

270 APPENDIX A. SOURCE CODE

/*** sets the current phase of the board, true for select phase, false for play* phase** @param s* what to set phase to*/public void setPhase(boolean s){

selectPhase = s;

}

/*** method that initilaizes the board**/public void initializeBoard(){

gridWidth = initGridWidth;gridHeight = initGridHeight;

while (granulation * gridWidth < maxWidth|| granulation * gridHeight < maxHeight)

{granulation++;

}

/** step until granulation reaches size needed to display requirements*/

while (granulation * gridWidth > maxWidth|| granulation * gridHeight > maxHeight)

{granulation--;

}

focusX = 0;focusY = 0;

/* if odd shift focus */if (gridWidth % 2 != 0)

focusX = 1;if (gridHeight % 2 != 0)

focusY = 1;

Page 279: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 271

theBoard.updateGraphicsGranulation(granulation);theBoard.updateGraphicsFocus(focusX, focusY);updateBoard();

}

/*** returns true if the current piece is selected from the board, otherwise* false** @return true for selected from board, false for not*/public boolean isSelectedFromBoard(){

if (selectedPiece == null)return false;

elsereturn true;

}

/*** if selected piece is not null returns a new piece from the selected piece* with Zeroed coordinates, otherwise it returns the selectedPiece which is* null** @return either the selected piece with zero or null if selected piece is* null*/public e2dPiece getSelectedPiece(){

if (selectedPiece != null)return new e2dPiece(selectedPiece);

elsereturn selectedPiece;

}

/*** sets the current piece for the board** @param p* what piece to set the current piece to*/public void setTheCurrentPiece(e2dPiece p){

if (p != null){

Page 280: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

272 APPENDIX A. SOURCE CODE

theCurrentPiece = new e2dPiece(p);theBoard.setCurrentPiece(theCurrentPiece);updateBoard();

} else{

theCurrentPiece = null;if (selectedPiece != null){

selectedPiece.setSelected(false);selectedPiece = null;updateBoard();

}}

}

/*** repaints the board graphic panel**/public void updateBoard(){

theBoard.repaint();

}

/*** realigns everything so that all the pieces are viewable does not zoom to* e2dBasicShape level should only be used with infinite board settings*/public void zoomToPieces(){

// determine how man square viewable// subtract one for upper right correctionint viewableXpos = (boardwidth / granulation - focusX) / 2 - 1;// because// up// right// is// pointint viewableXneg = (boardwidth / granulation + focusX) / 2;int viewableYpos = (boardheight / granulation + focusY) / 2;int viewableYneg = (boardheight / granulation - focusY) / 2 - 1;// upper// right// is// pointq// see if any our outside the view range

Page 281: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 273

e2dPiece unviewable = null;for (int i = 0; i < pieces.size(); i++){

e2dPiece p = (e2dPiece) pieces.get(i);// for the originif (p.getX() > viewableXpos || p.getY() > viewableYpos

|| p.getX() < -viewableXneg || p.getY() < -viewableYneg)unviewable = p;

// for the subshapese2dSet<e2dShape> subShapes = p.getShapes();for (int j = 0; j < subShapes.size(); j++){

e2dShape s = (e2dShape) subShapes.get(j);if (s.getOffX() > viewableXpos || s.getOffY() > viewableYpos

|| s.getOffX() < -viewableXneg|| s.getOffY() < -viewableYneg)

unviewable = p;}

}

// step out a two grids at a time till it is goodif (unviewable != null){

while (unviewable.getX() > viewableXpos|| unviewable.getX() > viewableYpos|| unviewable.getY() < -viewableXneg|| unviewable.getY() < -viewableYneg)

{

// reset variablesviewableXpos = (boardwidth / granulation - focusX) / 2 - 1;viewableXneg = (boardwidth / granulation + focusX) / 2;viewableYpos = (boardheight / granulation + focusY) / 2 - 1;viewableYneg = (boardheight / granulation - focusY) / 2;zoom(-1, 2);// the zoom out

}}

}

/*** changes the focus** @param

Page 282: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

274 APPENDIX A. SOURCE CODE

*/private void updateFocus(int x, int y){

focusX = x;focusY = y;theBoard.updateGraphicsFocus(focusX, focusY);/*

* tell theBoard to change its* focus*/

updateBoard();}

/*** zoom increases/decreases the granulation so that the grid is one grid wider* in bothe directions if x<0 zoom out if x>0 zoom in x == 0 does nothing** @param x* zoom in or zoom out* @param gridNum* the number of grids to do the zoom with*/public void zoom(int x, int gridNum){

if (x > 0){

if (gridWidth - gridNum > 0 && gridHeight - gridNum > 0){

gridWidth -= gridNum;gridHeight -= gridNum;while (granulation * gridWidth < maxWidth

|| granulation * gridHeight < maxHeight){

granulation++;}

}}if (x < 0){

if (gridWidth + gridNum < maxWidth&& gridHeight + gridNum < maxHeight){

gridWidth += gridNum;gridHeight += gridNum;while (granulation >= 1

&& (granulation * gridWidth > maxWidth

Page 283: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 275

|| granulation * gridHeight > maxHeight)){

granulation--;}

}}

theBoard.updateGraphicsGranulation(granulation);updateBoard();

}

/*** resets everything given the new e2dBoard object** @param b* the new e2dBoard object*/public void setBoard(e2dBoard b){

e2dSet<e2dPiece> tempPieces = b.getPieces();pieces = new e2dSet<e2dPiece>();for (e2dPiece p : tempPieces){

e2dPiece tempPiece = new e2dPiece(p);pieces.add(tempPiece);

}theBoard.updatePieceSet(pieces);updateBoard();

}

/*** The panel for the name** @author aja2002**/private class NamePanel extends JPanel{

/****/private static final long serialVersionUID = -4018506145380481106L;

String name;

Page 284: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

276 APPENDIX A. SOURCE CODE

public NamePanel(String n){

name = n;setPreferredSize(new Dimension(250, 70));

}

public void paintComponent(Graphics g){

super.paintComponent(g);g.setColor(Color.BLACK);

g.drawString(name, 50, 50);}

}

/*** private panel that paints the board** @author aja2002**/private class BoardGraphicsPanel extends JPanel implements

MouseMotionListener, MouseListener{

/****/

private static final long serialVersionUID = 7964559418466595868L;/** dont* worry* about* this*/

private int gWidth;/* width and height in pixels */

private int gHeight;

private int gGranulation;

private e2dSet<e2dPiece> pieceSet;/* set of pieces on the board */

private int gFocusX;/* the focuses */

Page 285: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 277

private int gFocusY;

private int xMid; /* mid values */

private int yMid;

private MouseEvent currentEvent; /* stores the last mouse event */

private e2dPiece currentPiece; /* stores the current working shape */

/*** constructor for the board graphics panel** @param w* the width in pixels* @param h* the height in pixels* @param gran* the granulation in pixels* @param fX* the focus to use in X direction* @param fY* the focus to use in Y direction* @param ps* the pieceset to render*/public BoardGraphicsPanel(int w, int h, int gran, int fX, int fY,

e2dSet<e2dPiece> ps){

gWidth = w;gHeight = h;gFocusX = fX;gFocusY = fY;gGranulation = gran;

pieceSet = ps; // pointer to the shapes in GUIe2dBoard class

setPreferredSize(new Dimension(gGranulation * gridWidth, gGranulation* gridHeight));

addMouseMotionListener(this);addMouseListener(this);currentEvent = null;currentPiece = null;outLinePiece = null;

}

Page 286: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

278 APPENDIX A. SOURCE CODE

/*** the painting method** @param g* the graphics component to do painting on*/

public void paintComponent(Graphics g){

g.setColor(Color.GRAY.darker().darker().darker());super.paintComponent(g);g.setColor(Color.GRAY.darker().darker().darker());

g.setColor(Color.black);/* sets the mid */xMid = (gWidth / gGranulation + gFocusX) / 2 * gGranulation;yMid = (gHeight / gGranulation + gFocusY) / 2 * gGranulation;

/* section that draws the grid */for (int x = 0; x <= gGranulation * gridWidth; x += granulation){

for (int y = 0; y <= gGranulation * gridHeight; y += granulation){

if (x == xMid || x == xMid - 1 || x == xMid + 1){

g.drawLine(x - 1, 0, x - 1, gGranulation * gridHeight);g.drawLine(x + 1, 0, x + 1, gGranulation * gridHeight);

}if (y == yMid || y == yMid - 1 || y == yMid + 1){

g.drawLine(0, y - 1, gGranulation * gridWidth, y - 1);g.drawLine(0, y + 1, gGranulation * gridWidth, y + 1);

}g.drawLine(x, 0, x, gGranulation * gridHeight);g.drawLine(0, y, gGranulation * gridWidth, y);

}}

g.drawLine(0, gGranulation * gridHeight, gGranulation * gridWidth,gGranulation * gridHeight);

/* section that draws the pieces */for (int i = 0; i < pieceSet.size(); i++){

e2dPiece p = pieceSet.get(i);

Page 287: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 279

if (xMid + p.getX() * gGranulation >= 0|| xMid + p.getX() * gGranulation <= gWidth|| yMid - p.getY() * gGranulation >= 0|| yMid - p.getY() * gGranulation <= gHeight)

p.drawPiece(g, xMid, yMid, gGranulation);}

// draw a piece that follows the mouseif (currentEvent != null && !selectPhase){

int xCord = currentEvent.getX();int yCord = currentEvent.getY();if (xCord < gGranulation * gridWidth

&& yCord < gGranulation * gridHeight){

int gridXcord = 0;int gridYcord = 0;// see which grid space it is inwhile (gGranulation * gridXcord <= xCord){

gridXcord++;}while (gGranulation * gridYcord <= yCord){

gridYcord++;}// correctiongridXcord--;gridYcord--;int viewableXneg = (gWidth / gGranulation + focusX) / 2;int viewableYpos = (gHeight / gGranulation + focusY) / 2;// for gridXcord translation subtractgridXcord -= viewableXneg;// for gridYcord translation subtract and negategridYcord = -(gridYcord - viewableYpos);

if (outLinePiece != null){

// draw the required shape if not nulloutLinePiece.drawPieceOutline(g, gridXcord,gridYcord, xMid, yMid,

gGranulation);}

}

}

Page 288: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

280 APPENDIX A. SOURCE CODE

}

/*** updates which piece set to render** @param p* the piece set to render*/

public void updatePieceSet(e2dSet<e2dPiece> p){

pieceSet = p;}

/*** change the current piece set up** @param s* the new current piece*/

public void setCurrentPiece(e2dPiece s){

currentPiece = s;if (currentPiece != null){

outLinePiece = new e2dPiece(currentPiece);}

}

/*** change the granulation** @param the* new granulation*/

public void updateGraphicsGranulation(int gran){

gGranulation = gran;}

/*** change the focus charateristics** @param fx* the new focus in the x direction* @param fy

Page 289: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 281

* the new focus in the y direction*/public void updateGraphicsFocus(int fx, int fy){

gFocusX = fx;gFocusY = fy;xMid = (gWidth / gGranulation + gFocusX) / 2 * gGranulation;yMid = (gHeight / gGranulation + gFocusY) / 2 * gGranulation;

}

// mouse listening section

// for MouseMotionListener/*** Moused moved sets the current event so that a trail will* follow the mouse* if the play phase is set** @param e* the MouseEvent**/public void mouseMoved(MouseEvent e){

currentEvent = e;repaint();

}

/*** Never Used*/public void mouseDragged(MouseEvent e){

}

// for MouseListener/*** Never Used*/public void mousePressed(MouseEvent e){

// mouse clicked down}

/**

Page 290: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

282 APPENDIX A. SOURCE CODE

* never used*/

public void mouseReleased(MouseEvent e){

// mouse click up}

/*** never used*/

public void mouseEntered(MouseEvent e){

// for when the mouse entered the panel

}

/*** set the current event to null so that the trail stops rendering*/

public void mouseExited(MouseEvent e){

// leave the screen set currentEvent to null// and repaintcurrentEvent = null;repaint();

}

/*** Handles all possible situations for a click on the board including* selecting and playing a piece*/

public void mouseClicked(MouseEvent e){

// determine what grid number it is in without cartusion translationint xCord = e.getX();int yCord = e.getY();// if in play regionif (xCord < gGranulation * gridWidth&& yCord < gGranulation * gridHeight){

int gridXcord = 0;int gridYcord = 0;// see which grid space it is inwhile (gGranulation * gridXcord <= xCord){

Page 291: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 283

gridXcord++;}while (gGranulation * gridYcord <= yCord){

gridYcord++;}

// correctiongridXcord--;gridYcord--;

// translate into cartusion// determine the viewableXneg and viewableYposint viewableXneg = (gWidth / gGranulation + focusX) / 2;int viewableYpos = (gHeight / gGranulation + focusY) / 2;

// for gridXcord translation subtractgridXcord -= viewableXneg;// for gridYcord translation subtract and negategridYcord = -(gridYcord - viewableYpos);

if (selectPhase){

if (theTop.moveFromBoard){

for (int i = 0; i < pieceSet.size(); i++){

e2dPiece p = (e2dPiece) pieceSet.get(i);if (p.isOnPiece(gridXcord, gridYcord)){

selectedPieces.add(p);}selectedPieces.trimToSize();

}/* Dialoge box by Hugh Gordon */if (!selectedPieces.isEmpty()){

if (selectedPieces.size() > 1){

ArrayList<String> options= new ArrayList<String>();

// Create an array of the text and components to// be displayed.

Page 292: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

284 APPENDIX A. SOURCE CODE

String msgString1 = "You have clicked on "+ "two pieces.\nPlease choose"+ " the one you would"+ " like to select.\n";

String tmp;tmp = "";for (int i = 0; i < selectedPieces.size(); i++){tmp = (i + 1) + " @ ("

+ ((e2dPiece) selectedPieces.get(i)).getX()+ ","+ ((e2dPiece)selectedPieces.get(i)).getY()+ ")";options.add(tmp);

}

// Create an array specifying the number of// dialog buttons// and their text.Object[] possibilities = options.toArray();

String s = (String) JOptionPane.showInputDialog(theTop,msgString1, "Piece Conflict", JOptionPane.PLAIN_MESSAGE,

null, possibilities, possibilities[0]);

if (s != null){

String[] tempArray;

tempArray = s.split(" @");Integer tint = new Integer(tempArray[0]);

selectedPiece = (selectedPieces.get(tint.intValue() - 1));} else{

selectedPieces.clear();}

} else{

selectedPiece = selectedPieces.get(0);

selectedPieces.clear();// set the piece selected for drawing purposes// note this a pointer to the piece that is in// the

Page 293: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 285

// piece set for pieces on the boardselectedPiece.setSelected(true);

}

selectedPieces.clear();// set the piece as the current piece in the frame,// send// copy with new Zeroed coordinatesif (selectedPiece != null){

if (theTop.moveToBag || theTop.moveToHand){

e2dPiece[] returnPieces = new e2dPiece[2];returnPieces[0] = new e2dPiece(selectedPiece);

if (theTop.moveToBag)returnPieces[0].putInBag();

if (theTop.moveToHand)returnPieces[0].putInHand();

returnPieces[0].setSelected(false);returnPieces[1] = new e2dPiece(selectedPiece);theTop.setPlayedPiece(returnPieces);theTop.unselect();

} else{

selectedPiece.setSelected(true);e2dPiece setPiece = new e2dPiece(selectedPiece);// setPiece.setSelected(false);theTop.setCurrentPiece(setPiece);// repaint so the user knows which piece was// selectedrepaint();selectPhase = false;

}}

}

}} else if (theTop.moveToBoard){

// add the piece and repaintif (selectedPiece == null && outLinePiece != null)

Page 294: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

286 APPENDIX A. SOURCE CODE

{e2dPiece[] returnPieces = new e2dPiece[2];returnPieces[0] = new e2dPiece(currentPiece);returnPieces[0].putOnBoard(gridXcord, gridYcord);returnPieces[1] = new e2dPiece(currentPiece);theTop.setPlayedPiece(returnPieces);

} else{

outLinePiece.putOnBoard(gridXcord, gridYcord);outLinePiece.setSelected(false);e2dPiece[] returnPieces = new e2dPiece[2];returnPieces[0] = new e2dPiece(outLinePiece);returnPieces[1] = new e2dPiece(selectedPiece);theTop.setPlayedPiece(returnPieces);pieceSet.add(new e2dPiece(outLinePiece));theTop.unselect();outLinePiece = null;

}

theTop.unselect();selectPhase = true;repaint();// zoomToPieces();

}}

}

}

}

A.7.3 GUIe2dCurrentPiecePanel

/******************************************************************************** GUIe2dCyrrentPiecePanel.java** Written By Adam Aviv*/package e2dGUI;

import java.awt.BorderLayout; import javax.swing.JPanel;

import e2dCore.*;

/**

Page 295: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 287

* The panel used to display the currently selected piece** @author aja2002**/

public class GUIe2dCurrentPiecePanel extends JPanel {

/****/private static final long serialVersionUID = -7437344056977271121L;

private e2dPiece theCurrentPiece;

private int panelWidth;

private int panelHeight;

private int granulation;

// true for select, flase for play

private GUIe2dPieceGraphicsPanel drawPanel;

/*** construct a new GUIe2dCurrentPiecePanel with the default conditions**/public GUIe2dCurrentPiecePanel(){

theCurrentPiece = null;panelHeight = 120;panelWidth = 120;granulation = 40;

drawPanel = new GUIe2dPieceGraphicsPanel(panelWidth, panelHeight,granulation);

this.setLayout(new BorderLayout());this.add(drawPanel, BorderLayout.CENTER);

}

/*** updates what piece to display in the current piece panel*

Page 296: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

288 APPENDIX A. SOURCE CODE

* @param p* the piece to display*/public void updateCurrentPiece(e2dPiece p){

if (p != null){

theCurrentPiece = new e2dPiece(p);

granulation = drawPanel.updateCurrentPiece(theCurrentPiece);

}else{

theCurrentPiece = p;granulation = drawPanel.updateCurrentPiece(theCurrentPiece);

}}

}

A.7.4 GUIe2dFrame

/******************************************************************************** GUIe2dFrame.java** Written By Adam Aviv and Hugh Gordon*/

package e2dGUI;

import java.awt.BorderLayout; import java.awt.Color; importjava.awt.Container; import java.awt.Dimension; importjava.awt.Graphics; import java.awt.GridLayout; importjava.awt.event.ActionEvent; import java.awt.event.ActionListener;import java.awt.event.WindowAdapter; importjava.awt.event.WindowEvent;

import javax.swing.JButton; import javax.swing.JFrame; importjavax.swing.JPanel; import javax.swing.JScrollPane; importjavax.swing.JTextArea; import javax.swing.ScrollPaneConstants;import javax.swing.WindowConstants;

import e2dCore.EmptySetException; import e2dCore.e2dGameState;import e2dCore.e2dPiece; import e2dCore.e2dPlayer; importe2dCore.e2dSet;

Page 297: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 289

/*** The top most frame for the GUI handles all possible events that could occur* inside the GUI without outside interference** @author aja2002**/

public class GUIe2dFrame extends JFrame {

/****/private static final long serialVersionUID = -717585854364558933L;

private GUIe2dBoard theBoard;

private GUIe2dCurrentPiecePanel cPanel;

private e2dPiece theCurrentPiece;

private GUIe2dBagViewPanel bPanel;

private GUIe2dHandViewPanel hPanel;

private NamePanel bname;

private NamePanel hname;

private e2dGameState gameState;

// for current slected piece viewprivate JButton rRotateButton;

private JButton lRotateButton;

private JButton xFlipButton;

private JButton yFlipButton;

private JButton unselectButton;

private e2dPiece[] playedPiece;

private JFrame pieceChooseFrame;

private JFrame handsFrame = null;

Page 298: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

290 APPENDIX A. SOURCE CODE

private JPanel handsPanel = null;

public boolean moveFromHand = false;

public boolean moveFromBoard = false;

public boolean moveFromBag = false;

public boolean moveFromSet = false;

public boolean moveToHand = false;

public boolean moveToBag = false;

public boolean moveToBoard = false;

/*** sets moveToHand to true**/public void setMoveFromHand(){

moveFromHand = true;}

/*** sts moveFromBoard to true**/public void setMoveFromBoard(){

moveFromBoard = true;}

/*** sets moveFromBag to true**/public void setMoveFromBag(){

moveFromBag = true;}

/*** sets moveFromSet to true

Page 299: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 291

**/public void setMoveFromSet(){

moveFromSet = true;}

/*** sets moveToHand to true**/public void setMoveToHand(){

moveToHand = true;}

/*** sets moveToBag to true**/public void setMoveToBag(){

moveToBag = true;}

/*** sets moveToBoard to true**/public void setMoveToBoard(){

moveToBoard = true;}

/*** resets all move from attributes back to false**/public void resetMoveFrom(){

moveFromSet = moveFromHand = moveFromBoard = moveFromBag = false;}

/*** resets all move to attributes back to false*

Page 300: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

292 APPENDIX A. SOURCE CODE

*/public void resetMoveTo(){

moveToBoard = moveToHand = moveToBag = false;}

/*** special synchronized function for interaction with the GUIe2dInteractor* that blocks until playedPiece is set** @return the array of playedPiece with reference 0 the to and reference 1* the from*/public synchronized e2dPiece[] getPlayedPiece(){

while (playedPiece[0] == null){

try{

wait();} catch (InterruptedException e){}

}notifyAll();e2dPiece[] tempPiece = new e2dPiece[2];tempPiece[0] = new e2dPiece(playedPiece[0]);if (playedPiece[1] == null)

tempPiece[1] = null;else

tempPiece[1] = new e2dPiece(playedPiece[1]);playedPiece[0] = null;playedPiece[1] = null;return tempPiece;

}

/*** special synchronized function for interaction with the GUIe2dInteractor* that blocks untill playedPiece is set back to nll** @param p* what to set playedPiece to*/public synchronized void setPlayedPiece(e2dPiece[] p){

Page 301: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 293

while (playedPiece[0] != null){

try{

wait();} catch (InterruptedException e){}

}if (pieceChooseFrame != null){

pieceChooseFrame.setAlwaysOnTop(false);pieceChooseFrame.setVisible(false);pieceChooseFrame = null;

}playedPiece = p;notifyAll();

}

/*** another synchronized function that resets the played piece back to false in* case playedPiece is locked by another function, it will block**/public synchronized void resetPlayedPiece(){

playedPiece[0] = null;playedPiece[1] = null;

}

/*** resets all move to and move from variables**/public void resetAll(){

resetMoveFrom();resetMoveTo();

}

private JTextArea mesg_area;

// phase is true for select, and false for playprivate boolean phase = true;

Page 302: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

294 APPENDIX A. SOURCE CODE

public e2dGameState getGameState(){return gameState;}/*** construct a new GUI for e2d from a gameState** @param b* the gameState to do construction from*/public GUIe2dFrame(e2dGameState b){

super("e2d");playedPiece = new e2dPiece[2];resetPlayedPiece();gameState = b;

bname = new NamePanel("The Bag");hname = new NamePanel(gameState.getCurrPlayer().getName() + "’s hand");

addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

System.exit(0);}

});

this.setResizable(false);theBoard = new GUIe2dBoard(gameState.getBoard(), this);JPanel topCPanel = new JPanel();cPanel = new GUIe2dCurrentPiecePanel();

if (gameState.getFlags().canRotate()){

rRotateButton = new JButton("R Rotate");lRotateButton = new JButton("L Rotate");

} else{

rRotateButton = new JButton("NO ROTATION");lRotateButton = new JButton("NO ROTATION");

}if (gameState.getFlags().canFlipX())

xFlipButton = new JButton("X Flip");else

xFlipButton = new JButton("NO X FLIP");

Page 303: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 295

if (gameState.getFlags().canFlipY())yFlipButton = new JButton("Y Flip");

elseyFlipButton = new JButton("NO Y FLIP");

unselectButton = new JButton("Unselect Piece");

unselectButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

if(moveFromBag && !gameState.getFlags().canViewBag()){

addMessage("Can’t unselect this piece\n");}else if(moveFromSet && !gameState.getFlags().canViewHands()){

addMessage("Can’t unselect this piece\n");}else{

unselect();}

}});

/* Set up message area by Hugh Gordon */

mesg_area = new JTextArea("Game Messages:\n");mesg_area.setRows(4);

rRotateButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

if (theCurrentPiece != null){

if (gameState.getFlags().canRotate()){

theCurrentPiece.rotateR();if (theBoard.isSelectedFromBoard()){

theBoard.getSelectedPiece().rotateR();}theBoard.setTheCurrentPiece(theCurrentPiece);

Page 304: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

296 APPENDIX A. SOURCE CODE

cPanel.updateCurrentPiece(theCurrentPiece);} else{

addMessage("May Not Rotate\n");}

}}

});

lRotateButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

if (theCurrentPiece != null){

if (gameState.getFlags().canRotate()){

theCurrentPiece.rotateL();if (theBoard.isSelectedFromBoard()){

theBoard.getSelectedPiece().rotateL();}theBoard.setTheCurrentPiece(theCurrentPiece);cPanel.updateCurrentPiece(theCurrentPiece);

} else{

addMessage("May Not Rotate\n");}

}}

});xFlipButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

if (theCurrentPiece != null){

if (gameState.getFlags().canFlipX()){

theCurrentPiece.flipX();if (theBoard.isSelectedFromBoard()){

theBoard.getSelectedPiece().flipX();}theBoard.setTheCurrentPiece(theCurrentPiece);

Page 305: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 297

cPanel.updateCurrentPiece(theCurrentPiece);} else{

addMessage("MAY NOT FLIP X\n");}

}}

});yFlipButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

if (theCurrentPiece != null){

if (gameState.getFlags().canFlipY()){

theCurrentPiece.flipY();if (theBoard.isSelectedFromBoard()){

theBoard.getSelectedPiece().flipY();}theBoard.setTheCurrentPiece(theCurrentPiece);cPanel.updateCurrentPiece(theCurrentPiece);

} else{

addMessage("MAY NOT FLIP Y\n");}

}}

});

topCPanel.setLayout(new BorderLayout());

JPanel northNorthPanel = new JPanel();JPanel northPanel = new JPanel();JPanel southPanel = new JPanel();

northPanel.setLayout(new GridLayout(1, 2));southPanel.setLayout(new GridLayout(1, 2));northNorthPanel.setLayout(new GridLayout(2, 1));southPanel.add(lRotateButton);southPanel.add(rRotateButton);northPanel.add(xFlipButton);northPanel.add(yFlipButton);

Page 306: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

298 APPENDIX A. SOURCE CODE

northNorthPanel.add(unselectButton);northNorthPanel.add(northPanel);

topCPanel.add(northNorthPanel, BorderLayout.NORTH);topCPanel.add(southPanel, BorderLayout.SOUTH);topCPanel.add(cPanel, BorderLayout.CENTER);

JPanel bagPanel = new JPanel();bagPanel.setLayout(new BorderLayout());

JPanel handPanel = new JPanel();handPanel.setLayout(new BorderLayout());

if (gameState.getFlags().canViewBag()){

bPanel = new GUIe2dBagViewPanel(gameState.getBag(), this);JScrollPane bScrollPane = new JScrollPane(bPanel);bScrollPane.setPreferredSize(new Dimension(600, 150));bagPanel.add(bScrollPane, BorderLayout.SOUTH);bagPanel.add(bname, BorderLayout.NORTH);

} else{

bPanel = null;JButton drawButton = new JButton("DRAW");drawButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

if (moveFromBag){

e2dPiece p = gameState.getBag().getMemberAtRandom();e2dPiece[] returnPieces = new e2dPiece[2];if(p == null){

addMessage("Bag is empty\n");}else{

returnPieces[0] = new e2dPiece(p);if (moveToHand || moveToBag){

if (moveToBag)returnPieces[0].putInBag();

Page 307: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 299

if (moveToHand)returnPieces[0].putInHand();

returnPieces[1] = new e2dPiece(p);setPlayedPiece(returnPieces);

}

elsesetCurrentPiece(returnPieces[0]);

}}

}

});bagPanel.setPreferredSize(new Dimension(600, 150));bagPanel.add(drawButton, BorderLayout.CENTER);

}

hPanel = new GUIe2dHandViewPanel(this);hname = new NamePanel(gameState.getCurrPlayer().getName());hPanel.setHand(gameState.getCurrPlayer());hPanel.validate();JScrollPane hScrollPane = new JScrollPane(hPanel);hScrollPane.setPreferredSize(new Dimension(140, 500));handPanel.add(hScrollPane, BorderLayout.SOUTH);handPanel.add(hname, BorderLayout.NORTH);

if (gameState.getFlags().canViewHands()){

handsFrame = new JFrame("All Players Hands");handsFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

handsPanel = new JPanel();handsPanel.setLayout(new GridLayout(gameState.getPlayers().size(),1));

for (e2dPlayer p : gameState.getPlayers()){

JPanel tempPanel = new JPanel(new BorderLayout());NamePanel n = new NamePanel(p.getName(), 300, 60);GUIe2dPieceSelectionPanel psp = new GUIe2dPieceSelectionPanel(p

.getHand());JScrollPane scroll = new JScrollPane(psp,

ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

scroll.setPreferredSize(new Dimension(300, 140));

Page 308: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

300 APPENDIX A. SOURCE CODE

tempPanel.add(n, BorderLayout.NORTH);tempPanel.add(scroll, BorderLayout.SOUTH);handsPanel.add(tempPanel);

}JScrollPane outHandsScrollPane = new JScrollPane(handsPanel,

ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

outHandsScrollPane.setPreferredSize(new Dimension(310, 500));

handsFrame.add(outHandsScrollPane);handsFrame.pack();

}

theBoard.setTheCurrentPiece(theCurrentPiece);cPanel.updateCurrentPiece(theCurrentPiece);

Container thisFrame = this.getContentPane();

thisFrame.setLayout(new BorderLayout());

JPanel eastPanel = new JPanel();JScrollPane pPane = new JScrollPane(mesg_area);eastPanel.setLayout(new GridLayout(2, 1));eastPanel.setPreferredSize(new Dimension(250, this.getHeight()));eastPanel.add(topCPanel);eastPanel.add(pPane);

JPanel centerPanel = new JPanel();

/* Set up messages under board */

centerPanel.setLayout(new BorderLayout());centerPanel.add(theBoard, BorderLayout.NORTH);

thisFrame.add(centerPanel, BorderLayout.CENTER);thisFrame.add(eastPanel, BorderLayout.EAST);thisFrame.add(bagPanel, BorderLayout.SOUTH);thisFrame.add(handPanel, BorderLayout.WEST);pack();

// handsFrame.validate();

}

/**

Page 309: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 301

* a special private class that displays a name in a graphics panel** @author aja2002**/private class NamePanel extends JPanel{

/****/private static final long serialVersionUID = -4018506145380481106L;

String name;

public NamePanel(String n){

name = n;setPreferredSize(new Dimension(100, 70));

}

public NamePanel(String n, int w, int h){

name = n;setPreferredSize(new Dimension(w, h));

}

public void paintComponent(Graphics g){

super.paintComponent(g);g.setColor(Color.BLACK);

g.drawString(name, 50, 50);}

}

/*** sets the currentPiece across all relevent frames** @param piece* the piece to set the current piece to*/public void setCurrentPiece(e2dPiece piece){

if (phase == true){

theCurrentPiece = new e2dPiece(piece);

Page 310: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

302 APPENDIX A. SOURCE CODE

theBoard.setTheCurrentPiece(new e2dPiece(theCurrentPiece));// set the phase to play phasephase = false;theBoard.setPhase(false);cPanel.updateCurrentPiece(new e2dPiece(theCurrentPiece));

}

}

/*** sets the currentPiece to null across all frames**/public void unselect(){

theBoard.setTheCurrentPiece(null);cPanel.updateCurrentPiece(null);// revert back to select phasephase = true;theBoard.setPhase(true);theCurrentPiece = null;if (bPanel != null)

bPanel.unselect();

}

/*** adds a message to the message area of the GUI** @param msg* the message to display*/public void addMessage(final String msg){

mesg_area.append(msg);}

/*** given a new state of the game, update EVERYTHING!!!!!!!!!!!!** @param g* the new state of the game in a e2dGameState*/public void updateTheGameState(e2dGameState g){

gameState = g;

Page 311: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 303

hname = new NamePanel(gameState.getCurrPlayer().getName());hPanel.setHand(gameState.getCurrPlayer());hPanel.validate();if (gameState.getFlags().canViewBag()){

bPanel.setBag(g.getBag());bPanel.validate();

}theBoard.setBoard(gameState.getBoard());theBoard.validate();

if (gameState.getFlags().canViewHands()){

handsPanel.removeAll();for (e2dPlayer p : gameState.getPlayers()){

JPanel tempPanel = new JPanel(new BorderLayout());NamePanel n = new NamePanel(p.getName(), 300, 60);GUIe2dPieceSelectionPanel psp = new GUIe2dPieceSelectionPanel(p

.getHand());JScrollPane scroll = new JScrollPane(psp,

ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

scroll.setPreferredSize(new Dimension(300, 140));tempPanel.add(n, BorderLayout.NORTH);tempPanel.add(scroll, BorderLayout.SOUTH);handsPanel.add(tempPanel);

}

handsPanel.validate();}this.validate();

}

/*** Opens a new frame that user needs to choose a piece from** @param pieces* the pieces to put in the frame for choosing* @param title* the title of the frame*/public void showAPieceSelectionFrame(e2dSet<? extends e2dPiece> pieces,

String title){

Page 312: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

304 APPENDIX A. SOURCE CODE

if(pieces.size() <= 0){

throw new EmptySetException("The set is empty");}pieceChooseFrame = new JFrame(title);

GUIe2dPieceSelectionPanel psp = new GUIe2dPieceSelectionPanel(pieces, this);JPanel top = new JPanel();top.setPreferredSize(new Dimension(300, 140));top.add(psp);pieceChooseFrame

.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);pieceChooseFrame.setResizable(false);pieceChooseFrame.add(top);pieceChooseFrame.pack();pieceChooseFrame.setLocationRelativeTo(this);pieceChooseFrame.setAlwaysOnTop(true);pieceChooseFrame.setVisible(true);

}

public void showAPieceDrawFrame(e2dSet<? extends e2dPiece> pieces, String title){

if(pieces.size() <= 0){

throw new EmptySetException("The set is empty");}pieceChooseFrame = new JFrame(title);JPanel top = new JPanel();top.setPreferredSize(new Dimension(300,150));final e2dSet<? extends e2dPiece> finalPieces = pieces;JButton drawButton = new JButton("DRAW");drawButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

if (moveFromSet){

e2dPiece p = finalPieces.getMemberAtRandom();e2dPiece[] returnPieces = new e2dPiece[2];if(p == null){

addMessage("Set is empty\n");}else{

Page 313: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 305

returnPieces[0] = new e2dPiece(p);if (moveToHand || moveToBag){

if (moveToBag)returnPieces[0].putInBag();

if (moveToHand)returnPieces[0].putInHand();

returnPieces[1] = new e2dPiece(p);setPlayedPiece(returnPieces);

}

elsesetCurrentPiece(returnPieces[0]);

}}

}});top.add(drawButton);pieceChooseFrame.add(top);

pieceChooseFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);pieceChooseFrame.setResizable(false);pieceChooseFrame.add(top);pieceChooseFrame.pack();pieceChooseFrame.setLocationRelativeTo(this);pieceChooseFrame.setAlwaysOnTop(true);pieceChooseFrame.setVisible(true);

}

/*** returns the selcted piece from a piece choose frame and closes the frame** @param p* the piece choosen*/public void returnSelectedPiece(e2dPiece p){

if (moveToHand || moveToBag){

pieceChooseFrame.setAlwaysOnTop(false);pieceChooseFrame.setVisible(false);pieceChooseFrame = null;

Page 314: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

306 APPENDIX A. SOURCE CODE

e2dPiece[] returnPieces = new e2dPiece[2];

if (moveToHand){

returnPieces[0] = new e2dPiece(p);returnPieces[0].putInHand();returnPieces[1] = new e2dPiece(p);setPlayedPiece(returnPieces);

}if (moveToBag){

returnPieces[0] = new e2dPiece(p);returnPieces[0].putInBag();returnPieces[1] = new e2dPiece(p);setPlayedPiece(returnPieces);

}} else{

setCurrentPiece(new e2dPiece(p));}

}

/*** closes down the GUI**/public void closeDown(){

if (handsFrame != null){

handsFrame.setVisible(false);handsFrame = null;

}this.setVisible(false);

}

/*** sets up the GUI**/public void setUp(){

this.setVisible(true);if (handsFrame != null){

Page 315: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 307

handsFrame.setLocation(914, 0);handsFrame.setVisible(true);

}

}

}

A.7.5 GUIe2dHandViewPanel

/******************************************************************************** GUIe2dHandViewPanel** written by Adam Aviv and Hugh Gordon*/

package e2dGUI;

import e2dCore.*;

import java.awt.GridLayout;

import javax.swing.JPanel;

/*** A class designed to view a hand from a given player** @author aja2002 hhg2103**/

public class GUIe2dHandViewPanel extends JPanel {

/****/private static final long serialVersionUID = 1L;

private e2dSet<e2dPiece> pieces;

private e2dSet<GUIe2dPieceGraphicsPanel> piecesPanels;

private JPanel displayPanel;

private e2dPiece selectedPiece = null;

private GUIe2dFrame theTop;

Page 316: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

308 APPENDIX A. SOURCE CODE

/*** constructs a new hand view panel given this sets of pieces** @param p* the set of pieces to display* @param t* the top frame to communicate to*/public GUIe2dHandViewPanel(e2dSet<e2dPiece> p, GUIe2dFrame t){

pieces = p; // pointer to the list, global update

theTop = t;

displayPanel = new JPanel();piecesPanels = new e2dSet<GUIe2dPieceGraphicsPanel>();displayPanel.setLayout(new GridLayout(pieces.size(), 1));for (int i = 0; i < pieces.size(); i++){

e2dPiece piece = pieces.get(i);GUIe2dPieceGraphicsPanel tempPanel = new GUIe2dPieceGraphicsPanel(120,

120, 40, this, i);tempPanel.updateCurrentPiece(piece.clone());

piecesPanels.add(i, tempPanel);

// add it to the viewable paneldisplayPanel.add(tempPanel);

}

this.add(displayPanel);}

/*** sets up a hand view panel without a set of pieces to display** @param t* the top frame to communicate with*/

public GUIe2dHandViewPanel(GUIe2dFrame t){

pieces = new e2dSet<e2dPiece>();

theTop = t;

Page 317: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 309

displayPanel = new JPanel();piecesPanels = new e2dSet<GUIe2dPieceGraphicsPanel>();displayPanel.setLayout(new GridLayout(pieces.size(), 1));for (int i = 0; i < pieces.size(); i++){

e2dPiece piece = pieces.get(i);GUIe2dPieceGraphicsPanel tempPanel = new GUIe2dPieceGraphicsPanel(120,

120, 40, this, i);tempPanel.updateCurrentPiece(piece.clone());

piecesPanels.add(i, tempPanel);

// add it to the viewable paneldisplayPanel.add(tempPanel);

}

this.add(displayPanel);}

/*** updates the hand view player given a new player** @param curPlayer* the new players hand to display*/public void setHand(e2dPlayer curPlayer){

pieces = curPlayer.getHand();

displayPanel.removeAll();piecesPanels = new e2dSet<GUIe2dPieceGraphicsPanel>();displayPanel.setLayout(new GridLayout(pieces.size(), 1));for (int i = 0; i < pieces.size(); i++){

e2dPiece piece = pieces.get(i);GUIe2dPieceGraphicsPanel tempPanel = new GUIe2dPieceGraphicsPanel(120,

120, 40, this, i);tempPanel.updateCurrentPiece(new e2dPiece(piece));

piecesPanels.add(i, tempPanel);

// add it to the viewable paneldisplayPanel.add(tempPanel);

}

Page 318: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

310 APPENDIX A. SOURCE CODE

displayPanel.validate();this.validate();

}

/*** the method that gets called when a selection occured in the panel** @param index* the index of the panel clicked on*/public void clicked(int index){

if (theTop.moveFromHand){

if (!pieces.isEmpty() && index < pieces.size()){

selectedPiece = pieces.get(index);if (theTop.moveToHand || theTop.moveToBag){

if (theTop.moveToHand){

e2dPiece[] returnPieces = new e2dPiece[2];returnPieces[0] = new e2dPiece(selectedPiece);returnPieces[0].putInHand();returnPieces[1] = new e2dPiece(selectedPiece);theTop.setPlayedPiece(returnPieces);

}if (theTop.moveToBag){

e2dPiece[] returnPieces = new e2dPiece[2];returnPieces[0] = new e2dPiece(selectedPiece);returnPieces[0].putInBag();returnPieces[1] = new e2dPiece(selectedPiece);theTop.setPlayedPiece(returnPieces);

}} else

theTop.setCurrentPiece(new e2dPiece(selectedPiece));}

}}

/*** sets the state so nothing is selected**/public void unselect()

Page 319: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 311

{selectedPiece = null;

}}

A.7.6 GUIe2dInteractor

/******************************************************************************** GUIe2dInteractor.java** Written by Adam Aviv*/

package e2dGUI;

import java.awt.Dimension; import java.awt.GridLayout; importjava.awt.event.ActionEvent; import java.awt.event.ActionListener;import java.awt.event.WindowAdapter; importjava.awt.event.WindowEvent; import java.util.ArrayList;

import javax.swing.JButton; import javax.swing.JFrame; importjavax.swing.JOptionPane; import javax.swing.JTextArea;

import e2dCore.EmptySetException; importe2dCore.NoSuchPlayerException; import e2dCore.e2dGameState; importe2dCore.e2dInteractor; import e2dCore.e2dPiece; importe2dCore.e2dPlayer; import e2dCore.e2dSet;

/*** The GUIe2dInteractor is a class used to interact with the GUI from the* e2dCore** @author aja2002**/

public class GUIe2dInteractor implements e2dInteractor, Runnable {

private GUIe2dFrame theFrame;

/*** The Constructor takes in an e2dGameState and constructs theFrame using the* gamesState, then calls the run() fuction for the thread** @param gs* the game state*/

Page 320: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

312 APPENDIX A. SOURCE CODE

public GUIe2dInteractor(e2dGameState gs){

theFrame = new GUIe2dFrame(gs);run();

}

/*** Closes theFrame and opens a new frame that displays the winners and their* score** @param winners* and e2dSet containing the e2dPlayers that won*/public void tellGameOver(e2dSet<e2dPlayer> winners){

theFrame.closeDown();// theFrame.setVisible(false);JFrame finalFrame = new JFrame("GAME OVER");finalFrame.setPreferredSize(new Dimension(500, 500));finalFrame.setLocation(200, 200);finalFrame.setLayout(new GridLayout(2, 1));finalFrame.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

System.exit(0);}

});JTextArea textArea = new JTextArea(winners.size(), 15);for (e2dPlayer p : winners){

textArea.append(p.getName() + " with a score of " + p.getScore());}

JButton okButton = new JButton("OK");okButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

System.exit(0);

}

});

Page 321: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 313

finalFrame.add(textArea);finalFrame.add(okButton);finalFrame.pack();finalFrame.setVisible(true);

}

/*** print a messages to the GUI’s Game Messages** @param msg* the message to send*/public void print(String msg) throws IllegalArgumentException{

JOptionPane.showMessageDialog(theFrame, msg);

}

/*** updates the GUI giving the current game state** @param gs* the new gameState*/public void updateGameState(e2dGameState gs){

theFrame.updateTheGameState(gs);

}

/*** Opens a new frame containing the set of pieces to choose from to be moved* to the dest** @param dest* the destination* @return the piece that was moved*/public e2dPiece[] moveFromSet(int dest, e2dSet<? extends e2dPiece> s){

if(s.size() <=0 ){

throw new EmptySetException("Empty move from set");}

Page 322: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

314 APPENDIX A. SOURCE CODE

theFrame.resetAll();theFrame.resetPlayedPiece();theFrame.setMoveFromSet();theFrame.showAPieceSelectionFrame(s, "Select From This Set\n");if (dest == e2dInteractor.DEST_BAG){

theFrame.addMessage("Move from Set to Bag\n");theFrame.setMoveToBag();e2dPiece[] returnPiece = theFrame.getPlayedPiece();theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece;

}if (dest == e2dInteractor.DEST_BOARD){

theFrame.addMessage("Move from Set to the board\n");theFrame.setMoveToBoard();e2dPiece[] returnPiece = theFrame.getPlayedPiece();

returnPiece[0].putOnBoard(returnPiece[0].getX(), returnPiece[0].getY());theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece;

}if (dest == e2dInteractor.DEST_CURRHAND){

theFrame.addMessage("Move from Set to the your hand\n");theFrame.setMoveToHand();e2dPiece[] returnPiece = theFrame.getPlayedPiece();theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece;

}return null;

}

/*** allows the currentPlayer to choose from the board and move the piece to the

* destination** @param dest* the destination* @return an array of e2dPiece where index 0 is the new location, and index 1* is the original location on the board*/

Page 323: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 315

public e2dPiece[] moveFromBoard(int dest){

if(theFrame.getGameState().getBoard().getPieces().size() <=0 ){

throw new EmptySetException("No pieces on board");}

theFrame.resetAll();theFrame.resetPlayedPiece();theFrame.setMoveFromBoard();if (dest == e2dInteractor.DEST_BAG){

theFrame.addMessage("Move from Board to the Bag\n");theFrame.setMoveToBag();e2dPiece[] returnPiece = theFrame.getPlayedPiece();theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece;

}if (dest == e2dInteractor.DEST_BOARD){

theFrame.addMessage("Move from Board to the Board\n");theFrame.setMoveToBoard();e2dPiece[] returnPiece = theFrame.getPlayedPiece();

returnPiece[0].putOnBoard(returnPiece[0].getX(), returnPiece[0].getY());theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece;

}if (dest == e2dInteractor.DEST_CURRHAND){

theFrame.addMessage("Move a piece from the board to the your hand\n");theFrame.setMoveToHand();e2dPiece[] returnPiece = theFrame.getPlayedPiece();theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece;

}

return null;}

/*** Tells the GUI to allow the current player to play from his hand to dest*

Page 324: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

316 APPENDIX A. SOURCE CODE

* @param dest* the destination* @return the piece that was moved*/public e2dPiece[] moveFromCurrHand(int dest){

if(theFrame.getGameState().getCurrPlayer().getHand().size() <= 0){

throw new EmptySetException("No pieces in current players hand");}theFrame.resetAll();theFrame.resetPlayedPiece();theFrame.setMoveFromHand();if (dest == e2dInteractor.DEST_BAG){

theFrame.addMessage("Move from Hand into the Bag\n");theFrame.setMoveToBag();e2dPiece[] returnPiece = theFrame.getPlayedPiece();theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece;

}if (dest == e2dInteractor.DEST_BOARD){

theFrame.addMessage("Move from Hand on to the Board\n");theFrame.setMoveToBoard();e2dPiece[] returnPiece = theFrame.getPlayedPiece();theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece;

}if (dest == e2dInteractor.DEST_CURRHAND){

theFrame.resetAll();theFrame.resetPlayedPiece();return null;

}return null;

}

/*** Allows the Current user to play a piece from the bag to a destination** @param dest* the destination

Page 325: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 317

* @return the piece that was moved*/public e2dPiece[] moveFromBag(int dest){

if(theFrame.getGameState().getBag().size() <= 0){

throw new EmptySetException("No pieces in bag");}theFrame.resetAll();theFrame.resetPlayedPiece();theFrame.setMoveFromBag();

if (dest == e2dInteractor.DEST_BAG){

theFrame.resetAll();theFrame.resetPlayedPiece();return null;

}if (dest == e2dInteractor.DEST_BOARD){

theFrame.addMessage("Move a Piece from the Bag to the Board\n");theFrame.setMoveToBoard();e2dPiece[] returnPiece = theFrame.getPlayedPiece();theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece;

}if (dest == e2dInteractor.DEST_CURRHAND){

theFrame.addMessage("Movae a Piece from the Bag to the Hand\n");theFrame.setMoveToHand();e2dPiece[] returnPiece = theFrame.getPlayedPiece();theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece;

}return null;

}

/*** Allows the current player to play from an players hand to the dest** @param dest* the destination* @param from* the player, whos hand the choice is made from

Page 326: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

318 APPENDIX A. SOURCE CODE

* @return the piece that was moved*/public e2dPiece[] moveFromSomeHand(int dest, e2dPlayer from)

throws NoSuchPlayerException{

if(from.getHand().size() <= 0){

throw new EmptySetException("Hand has no pieces");}theFrame.resetAll();theFrame.resetPlayedPiece();theFrame.setMoveFromSet();if(!theFrame.getGameState().getFlags().canViewHands()){

theFrame.showAPieceDrawFrame(from.getHand(), "draw from " +from.getName()+"’s Hand");

}else{

theFrame.showAPieceSelectionFrame(from.getHand(), from.getName()+ "’s Hand");

}if (dest == e2dInteractor.DEST_BAG){

theFrame.addMessage("Move from Set to Bag\n");theFrame.setMoveToBag();e2dPiece[] returnPiece = theFrame.getPlayedPiece();theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece;

}if (dest == e2dInteractor.DEST_BOARD){

theFrame.addMessage("Move from Set to the board\n");theFrame.setMoveToBoard();e2dPiece[] returnPiece = theFrame.getPlayedPiece();theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece;

}if (dest == e2dInteractor.DEST_CURRHAND){

theFrame.addMessage("Move from Set to the your hand\n");theFrame.setMoveToHand();e2dPiece[] returnPiece = theFrame.getPlayedPiece();

Page 327: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 319

theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece;

}return null;

}

/*** allows the current user to move a pice from the to player to the from* player** @param to* the player where the piece is going to* @param from* the player weher the pice came from* @return the piece that was moved*/public e2dPiece[] moveFromSomeHandToSomeHand(e2dPlayer to, e2dPlayer from)

throws NoSuchPlayerException{

if(from.getHand().size() <= 0){

throw new EmptySetException("Hand has no pieces");}theFrame.resetAll();theFrame.resetPlayedPiece();theFrame.setMoveFromSet();theFrame.setMoveToHand();theFrame.showAPieceSelectionFrame(from.getHand(), from.getName()

+ "’s Hand to " + to.getName() + "’s hand");e2dPiece[] returnPiece = theFrame.getPlayedPiece();theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece;

}

/*** The run fuction*/public void run(){

theFrame.setUp();

}

/**

Page 328: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

320 APPENDIX A. SOURCE CODE

* asks the user for a choice** @param s* the choices to be made* @return the string choosen*/public String makeChoice(ArrayList<String> s){

String returnString = null;while (returnString == null){

returnString = (String) JOptionPane.showInputDialog(theFrame,"Please Make A Choice", "Choice", JOptionPane.QUESTION_MESSAGE, null,

s.toArray(), s.get(0));}return returnString;

}

/*** ask the user for a choice with a title** @param title* the title to use* @param s* the set of choices in string* @return the string choosen*/public String makeChoice(String title, ArrayList<String> s){

String returnString = null;while (returnString == null){

returnString = (String) JOptionPane.showInputDialog(theFrame,"Please Make A Choice", title, JOptionPane.QUESTION_MESSAGE, null, s

.toArray(), s.get(0));}

return returnString;}

public e2dPiece[] moveFromSetToHand(e2dSet<? extends e2dPiece> from,e2dPlayer to) throws NoSuchPlayerException

{if(from.size() <= 0){

Page 329: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 321

throw new EmptySetException("ser has no pieces");}theFrame.resetAll();theFrame.resetPlayedPiece();theFrame.setMoveFromSet();

theFrame.showAPieceSelectionFrame(from, "Select From This Set To Remove");theFrame.setMoveToHand();e2dPiece[] returnPiece = theFrame.getPlayedPiece();theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece;

}

public e2dPiece removeFromSet(e2dSet<? extends e2dPiece> from){

if(from.size() <= 0){

throw new EmptySetException("set has no pieces");}theFrame.resetAll();theFrame.resetPlayedPiece();theFrame.setMoveFromSet();theFrame.addMessage("Remove a piece from the set\n");theFrame.setMoveToHand();e2dPiece[] returnPiece = theFrame.getPlayedPiece();theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece[0];

}

public e2dPiece removeFromBag(){

if(theFrame.getGameState().getBag().size() <= 0){

throw new EmptySetException("Bag has no pieces");}theFrame.resetAll();theFrame.resetPlayedPiece();theFrame.setMoveFromBag();theFrame.addMessage("Remove a piece from the Bag\n");theFrame.setMoveToHand();e2dPiece[] returnPiece = theFrame.getPlayedPiece();theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece[0];

}

Page 330: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

322 APPENDIX A. SOURCE CODE

public e2dPiece removeFromCurrHand(){

if(theFrame.getGameState().getCurrPlayer().getHand().size() <= 0){

throw new EmptySetException("Hand has no pieces");}theFrame.resetAll();theFrame.resetPlayedPiece();theFrame.setMoveFromHand();theFrame.addMessage("Remove a piece from your hand\n");theFrame.setMoveToHand();e2dPiece[] returnPiece = theFrame.getPlayedPiece();theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece[0];

}

public e2dPiece removeFromHand(e2dPlayer fromPlayer){

if(fromPlayer.getHand().size() <= 0){

throw new EmptySetException("Hand has no pieces");}theFrame.resetAll();theFrame.resetPlayedPiece();theFrame.setMoveFromHand();theFrame.addMessage("Remove a piece from " + fromPlayer.getName()

+ "’s hand\n");theFrame.setMoveToHand();// could be bag, doesn’t really mattere2dPiece[] returnPiece = theFrame.getPlayedPiece();theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece[0];

}

public e2dPiece removeFromBoard(){

if(theFrame.getGameState().getBoard().getPieces().size() <= 0){

throw new EmptySetException("Board has no pieces");}theFrame.resetAll();theFrame.resetPlayedPiece();theFrame.setMoveFromBoard();

Page 331: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 323

theFrame.addMessage("Remove a piece from the board\n");theFrame.setMoveToHand();e2dPiece[] returnPiece = theFrame.getPlayedPiece();theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece[0];

}

public e2dPiece[] moveFromBagToHand(e2dPlayer to){

if(theFrame.getGameState().getBag().size() <= 0){

throw new EmptySetException("Bag has no pieces");}theFrame.resetAll();theFrame.resetPlayedPiece();theFrame.setMoveFromBag();theFrame.addMessage("Movae a Piece from the Bag to the " + to.getName()

+ "’s Hand\n");theFrame.setMoveToHand();e2dPiece[] returnPiece = theFrame.getPlayedPiece();theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece;

}

public e2dPiece[] moveFromBoardToHand(e2dPlayer to)throws NoSuchPlayerException{

if(theFrame.getGameState().getBag().size() <= 0){

throw new EmptySetException("Bag has no pieces");}theFrame.resetAll();theFrame.resetPlayedPiece();theFrame.setMoveFromBoard();theFrame.addMessage("Movae a Piece from the Board to the " + to.getName()

+ "’s Hand\n");theFrame.setMoveToHand();e2dPiece[] returnPiece = theFrame.getPlayedPiece();theFrame.resetAll();theFrame.resetPlayedPiece();return returnPiece;

}

Page 332: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

324 APPENDIX A. SOURCE CODE

}

A.7.7 GUIe2dPieceGraphicsPanel

/******************************************************************************** GUIe2dPieceGraphicsPanel** Written by Adam Aviv*/

package e2dGUI;

import java.awt.Color; import java.awt.Dimension; importjava.awt.Graphics; import java.awt.event.MouseEvent; importjava.awt.event.MouseListener; importjava.awt.event.MouseMotionListener; import javax.swing.JPanel;

import e2dCore.e2dBasicShape; import e2dCore.e2dPiece; importe2dCore.e2dShape; import e2dCore.e2dSet;

/*** A generic graphics panel specifically designed to display a piece** @author aja2002**/

public class GUIe2dPieceGraphicsPanel extends JPanel implementsMouseListener,

MouseMotionListener{

/****/private static final long serialVersionUID = 7724880388515069714L;

private int gWidth;

private int gHeight;

private int gGranulation;

private int xMid;

private int yMid;

private e2dPiece currentPiece;

Page 333: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 325

private int index;

private GUIe2dHandViewPanel hvPanel;

private GUIe2dBagViewPanel bvPanel;

private GUIe2dPieceSelectionPanel psPanel;

/*** constructor for a piece graphics panel if no top panel to communicate* with** @param w* the width in pixels* @param h* the height in pixels* @param g* the granulation in pixels*/public GUIe2dPieceGraphicsPanel(int w, int h, int g){

gWidth = w;gHeight = h;gGranulation = g;hvPanel = null;bvPanel = null;psPanel = null;index = -1;

setPreferredSize(new Dimension(gWidth, gHeight));currentPiece = null;addMouseMotionListener(this);addMouseListener(this);

}

/*** constructor to communicate with a hand view panel** @param w* the width in pixels* @param h* the height in pixels* @param g* the granulation* @param hv

Page 334: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

326 APPENDIX A. SOURCE CODE

* the hand view panel to communicate with* @param i* the index of the piece graphics panel*/

public GUIe2dPieceGraphicsPanel(int w, int h, int g,GUIe2dHandViewPanel hv, int i)

{gWidth = w;gHeight = h;gGranulation = g;hvPanel = hv;bvPanel = null;psPanel = null;index = i;

setPreferredSize(new Dimension(gWidth, gHeight));currentPiece = null;addMouseMotionListener(this);addMouseListener(this);

}

/*** construcotr to communicate with a bag view panel** @param w* the width in pixels* @param h* the height in pixels* @param g* the granulation* @param bv* the bag view panel to comunicate with* @param i* the index of the piece graphics panel*/public GUIe2dPieceGraphicsPanel(int w, int h, int g, GUIe2dBagViewPanel bv,

int i){

gWidth = w;gHeight = h;gGranulation = g;hvPanel = null;bvPanel = bv;psPanel = null;index = i;

Page 335: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 327

setPreferredSize(new Dimension(gWidth, gHeight));currentPiece = null;addMouseMotionListener(this);addMouseListener(this);

}

/*** constructor to communicate with a piece selection panel** @param w* the width in pixels* @param h* the height in pixels* @param g* the granulation in pixels* @param ps* the piece selection panel to communicate with* @param i* the index of the piece graphics panel*/public GUIe2dPieceGraphicsPanel(int w, int h, int g,

GUIe2dPieceSelectionPanel ps, int i){

gWidth = w;gHeight = h;gGranulation = g;hvPanel = null;bvPanel = null;psPanel = ps;index = i;

setPreferredSize(new Dimension(gWidth, gHeight));currentPiece = null;addMouseMotionListener(this);addMouseListener(this);

}

/*** the paint component for the piece graphics panel*/public void paintComponent(Graphics g){

g.setColor(Color.GRAY.darker().darker().darker());super.paintComponent(g);

Page 336: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

328 APPENDIX A. SOURCE CODE

g.setColor(Color.GRAY.darker().darker().darker());

g.setColor(Color.black);

/* sets the mid */xMid = (gWidth / gGranulation) / 2 * gGranulation;yMid = (gHeight / gGranulation) / 2 * gGranulation;

if (currentPiece != null){

currentPiece.drawPieceInPanel(g, xMid, yMid, gGranulation);}

}

/*** update the index of the piece graphics panel** @param i* the new index*/public void updateIndex(int i){

index = i;}

/*** updates the piece the piece graphics panel is displaying** @param p* the new piece* @return the new granulation or zero if the currentPiece is null*/public int updateCurrentPiece(e2dPiece p){

currentPiece = p;if (currentPiece != null){

// get the gridWidth and gridHeight of the pieceint xMax = 0;int yMax = 0;

e2dSet<e2dShape> shapes = currentPiece.getShapes();for (e2dShape s : shapes){

for (e2dBasicShape b : s.getBasicShapes())

Page 337: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 329

{if (b.getOffX() > xMax || b.getOffY() < -xMax){

if (b.getOffX() > 0)xMax = b.getOffX();

if (b.getOffX() < 0)xMax = -b.getOffX();

}if (b.getOffY() > yMax || b.getOffY() < -yMax){

if (b.getOffY() > 0)yMax = b.getOffY();

if (b.getOffY() < 0)yMax = -b.getOffY();

}}

}yMax++;xMax++;int compare = 1;if (xMax >= yMax)

compare = xMax;if (yMax > xMax)

compare = yMax;// correctioncompare += 2;compare *= 2; // make possible to handle all rotates and flips// get the granulation that gets 2*max, so perfect center

while (gWidth / gGranulation > compare|| gHeight / gGranulation > compare)

{gGranulation++;

}while (gWidth / gGranulation < compare

|| gHeight / gGranulation < compare){

gGranulation--;}

// repaint with the new granulation

repaint();return gGranulation;

}else

Page 338: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

330 APPENDIX A. SOURCE CODE

{repaint();return 0;

}}

/*** calls the top panels clicked function*/public void mouseClicked(MouseEvent arg0){

if (bvPanel != null){

bvPanel.clicked(index);}else if (hvPanel != null){

hvPanel.clicked(index);}else if (psPanel != null){

psPanel.clicked(index);}

}

/*** never used*/public void mousePressed(MouseEvent e){

}

/*** never used*/public void mouseReleased(MouseEvent e){

}

/*** never used*/public void mouseEntered(MouseEvent e)

Page 339: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 331

{

}

/*** never used*/public void mouseExited(MouseEvent e){

}

/*** never used*/public void mouseDragged(MouseEvent e){

}

/*** never used*/public void mouseMoved(MouseEvent e){

}

}

A.7.8 GUIe2dPieceSelectionPanel

/******************************************************************************** GUIe2dPieceSelectionPanel.java** Written by Adam Aviv*/

package e2dGUI;

import java.awt.Dimension; import java.awt.GridLayout;

import javax.swing.JPanel; import javax.swing.JScrollPane;

import e2dCore.e2dPiece; import e2dCore.e2dSet;

/**

Page 340: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

332 APPENDIX A. SOURCE CODE

* A nice panel for displaying a choice of pieces** @author aja2002**/

public class GUIe2dPieceSelectionPanel extends JPanel {

private static final long serialVersionUID = 1L;

private e2dSet<? extends e2dPiece> pieces;

private e2dSet<GUIe2dPieceGraphicsPanel> piecesPanels;

private JPanel displayPanel;

private boolean clickable;

private GUIe2dFrame theTop;

JScrollPane scrollPane;

/*** a constutor to create a new piece selection panel with a set of pieces* and a top frame to communicate to** @param p* the set of pieces to display* @param t* the top frame to communicate with*/

public GUIe2dPieceSelectionPanel(e2dSet<? extends e2dPiece> p,GUIe2dFrame t)

{pieces = p; // pointer to the list, global update

clickable = true;

theTop = t;

displayPanel = new JPanel();piecesPanels = new e2dSet<GUIe2dPieceGraphicsPanel>();setLayout(new GridLayout(pieces.size(), 1));for (int i = 0; i < pieces.size(); i++){

e2dPiece piece = pieces.get(i);GUIe2dPieceGraphicsPanel tempPanel = new GUIe2dPieceGraphicsPanel(

Page 341: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.7. E2DGUI 333

120, 120, 40, this, i);tempPanel.updateCurrentPiece(piece.clone());

piecesPanels.add(i, tempPanel);

// add it to the viewable paneldisplayPanel.add(tempPanel);

}

scrollPane = new JScrollPane(displayPanel);scrollPane.setPreferredSize(new Dimension(400, 140));this.add(scrollPane);

}

/*** construct a piece selection panel with just a set of pieces to display a* no top frame to communicate with** @param p* the set of pieces to display*/public GUIe2dPieceSelectionPanel(e2dSet<e2dPiece> p){

pieces = p; // pointer to the list, global update

clickable = false;

theTop = null;

displayPanel = new JPanel();piecesPanels = new e2dSet<GUIe2dPieceGraphicsPanel>();setLayout(new GridLayout(pieces.size(), 1));for (int i = 0; i < pieces.size(); i++){

e2dPiece piece = pieces.get(i);GUIe2dPieceGraphicsPanel tempPanel = new GUIe2dPieceGraphicsPanel(

120, 120, 40, this, i);tempPanel.updateCurrentPiece(piece.clone());

piecesPanels.add(i, tempPanel);

// add it to the viewable paneldisplayPanel.add(tempPanel);

}

this.add(displayPanel);

Page 342: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

334 APPENDIX A. SOURCE CODE

}

/*** make the piece selection frame unclickable**/public void setUnclickable(){

clickable = false;}

/*** function called by the pieceGraphicsPanel when clicked** @param index* the index of the pieceGraphicsPanel that was clicked*/public void clicked(int index){

if (clickable){

theTop.returnSelectedPiece(new e2dPiece(pieces.get(index)));}

}}

A.8 e2d Test Programs

A.8.1 Hello World

/********************************HelloWorld.e2d**A primitive program in e2d with one piece,*and prints "Hello World" when the game ends*by placing the piece on the board*******************************/

piece hello [square(1);

]

Init [Players += p1;Bag += hello;

]

Page 343: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.8. E2D TEST PROGRAMS 335

pattern legal [not(exists piece p in Board ( (p.loc_x < Board.width)and (p.loc_y < Board.height) )); ]

pattern end [not(exists piece p in Bag);]

Turn [play from Bag;

]

End [print "Hello World";Winners += Players;

]

A.8.2 Domain

Properties += {black, white}; black.image := blue; white.image :=white;

piece cross {x} [rect(3,1) property x;

u: square(1) property x;d: square(1) property x;

]

piece largeT {x} [rect(1,3) property x;

r^: square(1) property x;l^: square(1) property x;

]

piece longbar {x} [rect(1,5) property x;

]

piece sq {x} [square(2) property x;

]

piece smallT {x} [rect(1,3) property x;

r: square(1) property x;]

piece angle {x} [

Page 344: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

336 APPENDIX A. SOURCE CODE

rect(1,2) property x;r^: square(1) property x;

]

piece mediumbar {x} [rect(1,3) property x;

]

piece smallbar {x} [rect(1,2) property x;

]

Init [Board.height := 9;Board.width := 9;Bag += {cross(black)}*2;Bag += {largeT(black)}*2;Bag += {longbar(black)}*2;Bag += {sq(black)}*2;Bag += {smallT(black)}*2;Bag += {angle(black)}*4;Bag += {mediumbar(black)}*6;Bag += {smallbar(black)}*5;Players += {blackplayer, whiteplayer};reveal Bag;may flip;may rotate;

]

pattern legal [not (exists piece p in Board (p overlaps currPiece));

]

pattern end [forall piece p in Bag (not playable p);

]

pattern adj_to_curr [forall piece p in Board (p adjacent currPiece);action change:

property c;if currPlayer = blackplayer[ c := black; ]else[ c := white; ]foreach piece m in matched(p)

Page 345: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.8. E2D TEST PROGRAMS 337

[ m.x := c; ]]

Turn [property color;if currPlayer = blackplayer [color := black;]else [color := white;]foreach piece p in Bag[p.x := color;

]

play from Bag;

adj_to_curr.change;]

End [int blackscore;int whitescore;foreach piece q in Board[foreach shape s in q[if s.prop = black [blackscore += s.width*s.height;]else [whitescore += s.width*s.height;]

]]

if blackscore > whitescore [Winners += blackplayer;]else [Winners += whiteplayer;]

]

A.8.3 Latin Squares

Properties += {red, green, blue, yellow}; red.image := red;green.image := green; blue.image := blue; yellow.image := yellow;

piece sq {x} [square(1) property x;

]

Init [Board.width := 4;Board.height := 4;

Page 346: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

338 APPENDIX A. SOURCE CODE

Bag += sq*4;

Players += {p1};

]

pattern legal [not(exists piece pp in Board pp overlaps currPiece);

]

pattern end [not (exists piece k in Bag);

]

Turn [play from Bag;

]

End [bool loser := false;foreach piece pa in Board[

foreach piece pb in Board[

if(not(pa.loc_x=pb.loc_x and pa.loc_y=pb.loc_y)and pa.x=pb.x and (pa.loc_x=pb.loc_x or pa.loc_y=pb.loc_y))

[loser:=true;

]]

]

if(not loser)[

Winners += {p1};]

]

A.8.4 Tic-Tac-Toe

Properties += {x, o}; x.image := blue; o.image := white;

piece mark {col} [square(1) property col;

]

Page 347: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.8. E2D TEST PROGRAMS 339

Init [Board.height := 3;Board.width := 3;

Bag += {mark(x)}*9;

Players += {xplayer, oplayer};]

pattern legal [not(exists piece p in Board p overlaps currPiece);

]

pattern end [not(exists piece p in Board (exists piece q in Board (exists piece s in Board

(p.col=q.col and p.col=s.col and (q.loc_x-p.loc_x=p.loc_x-s.loc_x)and (q.loc_y-p.loc_y=p.loc_y-s.loc_y)))));

]

Turn [property marktype;if (currPlayer = xplayer)[ marktype := x; ]else[ marktype := o; ]

foreach piece p in Bag[

p.col := marktype;]

play from Bag;]

End [foreach piece q in Board[

foreach piece r in Board[

foreach piece s in Board[

]]

]

Page 348: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

340 APPENDIX A. SOURCE CODE

]

A.8.5 Fill Piece

Properties += {strange, normal};

piece strangeshape [rect(3,2) property strange;r_: square(1) property strange;ru<: square(2) property strange;rur^: rect(3,1) property strange;ruru>: rect(4,1) property strange;

]

piece toplay [rect(3,1) property normal;

]

Init [Players += p1;piece s := strangeshape;piece r;s.loc.x := 0;s.loc.y := 0;Board += s;Bag += toplay*6;may rotate;

]

pattern legal [action add: r := r join currPiece;

]

pattern end [empty(Bag);

]

Turn [draw;play;legal.add;

]

End [if s within r[Winners += p1;]

Page 349: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.8. E2D TEST PROGRAMS 341

else[print "HAHA you suck."]

]

A.8.6 Fit Pieces

/***************************Example1.e2d**Two Players compete two "fit" more pieces*togeather then the other**************************/

Properties +={Black, White};

Black.image := black; White.image := white;

piece bot {x} [rect(2,1) property x alias R;u>: rect (1,1) property x alias U;

]

piece top {x} [rect(2,1) property x alias R;d<:rect(1,1) property x alias D;attachment: D(dr,y) <-> bot.U(dl,y);

]

Init [Players += {p1, p2};p1.score := 0;p2.score := 0;maynot flip;maynot rotate;Bag += {top(White)}*10;Bag += {top(Black)}*10;Bag += {bot(Black)}*10;Bag += {bot(White)}*10;

]

pattern legal [//not(exists piece q in Board (currPiece overlaps q));true;

]

pattern end [//We end when the bag is empty

Page 350: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

342 APPENDIX A. SOURCE CODE

not(exists piece p in Bag);]

pattern filled_piece [exists piece p in Board p attaches currPiece;action a:if(currPiece.x=White)[ p1.score+=1; print "Go p1!";]else[ p2.score+=1; print "Go p2!";]

]

Turn [draw;if(currPlayer = p1)[ currPiece.x := White; ]else[ currPiece.x := Black; ]play;filled_piece.a;

]

End [if (p1.score < p2.score)[Winners += p2;]else[if p1.score > p2.score[ Winners += p1;]]

]

A.8.7 Strange Game

Properties += P; P.image := red;

piece longl [rect(3,1) alias A;attachment: A(r) <-> A(l);

]

Init [Bag += {longl}*10;

Page 351: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 343

Board.width:=6;Board.height:=5;

]

pattern legal [//not(exists piece p in Board currPiece overlaps p);true;]

pattern end [not(exists piece p in Bag);]

pattern neato [exists piece p in Board p attaches currPiece; actionscore: print "Score!";]

Turn [draw;play;neato.score;

]

End []

A.9 e2dCore and e2dGUI Tests

A.9.1 CanViewHandsTest

package e2dTest;

import java.awt.Color;

import e2dGUI.*; import e2dCore.*;

public class CanViewHandsTest {

/*** @param args*/public static void main(String[] args){

e2dGameState gs = new e2dGameState();

e2dPiece crossBlue = new e2dPiece();crossBlue.addShape(0, 0, 3, 1, new e2dProperty(Color.BLUE));crossBlue.addShape(1, 1, 1, 1, new e2dProperty(Color.BLUE));crossBlue.addShape(1, -1, 1, 1, new e2dProperty(Color.BLUE));

Page 352: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

344 APPENDIX A. SOURCE CODE

e2dPiece crossWhite = new e2dPiece();crossWhite.addShape(0, 0, 3, 1, new e2dProperty(Color.WHITE));crossWhite.addShape(1, 1, 1, 1, new e2dProperty(Color.WHITE));crossWhite.addShape(1, -1, 1, 1, new e2dProperty(Color.WHITE));

e2dPiece largeTBlue = new e2dPiece();largeTBlue.addShape(0, 0, 1, 3, new e2dProperty(Color.BLUE));largeTBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));largeTBlue.addShape(-1, 0, 1, 1, new e2dProperty(Color.BLUE));

e2dPiece largeTWhite = new e2dPiece();largeTWhite.addShape(0, 0, 1, 3, new e2dProperty(Color.WHITE));largeTWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));largeTWhite.addShape(-1, 0, 1, 1, new e2dProperty(Color.WHITE));

e2dPiece squareBlue = new e2dPiece();squareBlue.addShape(0, 0, 2, 2, new e2dProperty(Color.BLUE));

e2dPiece squareWhite = new e2dPiece();squareWhite.addShape(0, 0, 2, 2, new e2dProperty(Color.BLUE));

e2dPiece smallTBlue = new e2dPiece();smallTBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));smallTBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));smallTBlue.addShape(-1, 0, 1, 1, new e2dProperty(Color.BLUE));

e2dPiece smallTWhite = new e2dPiece();smallTWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));smallTWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));smallTWhite.addShape(-1, 0, 1, 1, new e2dProperty(Color.WHITE));

e2dPiece longbarBlue = new e2dPiece();longbarBlue.addShape(0, 0, 1, 5, new e2dProperty(Color.BLUE));

e2dPiece longbarWhite = new e2dPiece();longbarWhite.addShape(0, 0, 1, 5, new e2dProperty(Color.WHITE));

e2dPiece angleBlue = new e2dPiece();angleBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));angleBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));

e2dPiece angleWhite = new e2dPiece();angleWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));angleWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));

Page 353: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 345

e2dPiece mediumbarBlue = new e2dPiece();mediumbarBlue.addShape(0, 0, 1, 3, new e2dProperty(Color.BLUE));

e2dPiece mediumbarWhite = new e2dPiece();mediumbarWhite.addShape(0, 0, 1, 3, new e2dProperty(Color.WHITE));

e2dPiece smallbarBlue = new e2dPiece();smallbarBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));

e2dPiece smallbarWhite = new e2dPiece();smallbarWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));

e2dPlayer p1 = new e2dPlayer();p1.setName("p1");p1.addPieceToHand(crossBlue);p1.addPieceToHand(largeTBlue);p1.addPieceToHand(longbarBlue);p1.addPieceToHand(squareBlue);p1.addPieceToHand(smallTBlue);p1.addPieceToHand(angleBlue);p1.addPieceToHand(mediumbarBlue);p1.addPieceToHand(smallbarBlue);

gs.addPlayer(p1);

e2dPlayer p2 = new e2dPlayer();p2.setName("p2");p2.addPieceToHand(crossWhite);p2.addPieceToHand(largeTWhite);p2.addPieceToHand(longbarWhite);p2.addPieceToHand(squareWhite);p2.addPieceToHand(smallTWhite);p2.addPieceToHand(angleWhite);p2.addPieceToHand(mediumbarWhite);p2.addPieceToHand(smallbarWhite);

gs.addPlayer(p2);

e2dPlayer p3 = new e2dPlayer();p3.setName("p3");p3.addPieceToHand(crossBlue);p3.addPieceToHand(largeTBlue);p3.addPieceToHand(longbarBlue);p3.addPieceToHand(squareBlue);p3.addPieceToHand(smallTBlue);p3.addPieceToHand(angleBlue);

Page 354: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

346 APPENDIX A. SOURCE CODE

p3.addPieceToHand(mediumbarBlue);p3.addPieceToHand(smallbarBlue);

gs.addPlayer(p3);

e2dPlayer p4 = new e2dPlayer();p4.setName("p4");p4.addPieceToHand(crossWhite);p4.addPieceToHand(largeTWhite);p4.addPieceToHand(longbarWhite);p4.addPieceToHand(squareWhite);p4.addPieceToHand(smallTWhite);p4.addPieceToHand(angleWhite);p4.addPieceToHand(mediumbarWhite);p4.addPieceToHand(smallbarWhite);

gs.addPlayer(p4);

gs.addPieceToBag(crossWhite);gs.addPieceToBag(crossBlue);gs.addPieceToBag(smallTWhite);gs.addPieceToBag(smallTBlue);gs.addPieceToBag(largeTWhite);gs.addPieceToBag(largeTBlue);gs.addPieceToBag(squareWhite);gs.addPieceToBag(squareBlue);gs.addPieceToBag(angleWhite);gs.addPieceToBag(angleBlue);gs.addPieceToBag(longbarWhite);gs.addPieceToBag(longbarBlue);gs.addPieceToBag(mediumbarWhite);gs.addPieceToBag(mediumbarBlue);gs.addPieceToBag(smallbarWhite);gs.addPieceToBag(smallbarBlue);

gs.getFlags().mayNotFlip();gs.getFlags().mayRotate();gs.getFlags().revealBag();gs.getFlags().revealHands();

gs.getBoard().setHeight(9);gs.getBoard().setWidth(9);

gs.setCurrPlayer(p2);

GUIe2dInteractor interactor = new GUIe2dInteractor(gs);

Page 355: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 347

interactor.updateGameState(gs);e2dPiece played = interactor.moveFromBag(e2dInteractor.DEST_CURRHAND)[0];

gs.removePieceFromBag(played);gs.addPieceToCurrPlayerHand(played);interactor.updateGameState(gs);

}

}

A.9.2 EqualsTest

package e2dTest;

import java.awt.Color;

import e2dCore.*;

public class EqualsTest {public static void main(String[] args){

e2dProperty blue = new e2dProperty(Color.BLUE);e2dProperty red = new e2dProperty(Color.RED);

e2dPiece crossBlue = new e2dPiece();crossBlue.addShape(0, 0, 3, 1, blue);crossBlue.addShape(1, -1, 1, 1, blue);crossBlue.addShape(1, 1, 1, 1, blue);

e2dPiece crossBlue2 = new e2dPiece();crossBlue2.addShape(0, 0, 3, 1, blue);crossBlue2.addShape(1, -1, 1, 1, blue);crossBlue2.addShape(1, 1, 1, 1, blue);

e2dPiece oneByOne = new e2dPiece();oneByOne.addShape(0, 0, red);

e2dPiece oneByOne2 = new e2dPiece();oneByOne2.addShape(0, 0, red);

System.out.println("1x1: reflexive: " + oneByOne.equals(oneByOne));System.out.println("1x1: a ?= b: " + oneByOne.equals(oneByOne2));System.out.println("1x1: b ?= a: " + oneByOne2.equals(oneByOne));

// test reflexivity

Page 356: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

348 APPENDIX A. SOURCE CODE

System.out.println("Refelxive equals: " + crossBlue.equals(crossBlue));

// test different instances equal and equal commutesSystem.out.println("Equals different instance: "

+ crossBlue.equals(crossBlue2));System.out.println("Equals commutes: " + crossBlue2.equals(crossBlue));

e2dPiece outOfOrderCrossBlue = new e2dPiece();outOfOrderCrossBlue.addShape(0, 0, 3, 1, blue);outOfOrderCrossBlue.addShape(1, 1, 1, 1, blue);outOfOrderCrossBlue.addShape(1, -1, 1, 1, blue);

// test that order doesn’t matterSystem.out.println("Equals ignores creation order: "

+ crossBlue.equals(outOfOrderCrossBlue));System.out.println("Equals commutes when order differs: "

+ outOfOrderCrossBlue.equals(crossBlue));

e2dPiece vertFirstCrossBlue = new e2dPiece();vertFirstCrossBlue.addShape(0, 0, 1, 3, blue);vertFirstCrossBlue.addShape(-1, 1, 1, 1, blue);vertFirstCrossBlue.addShape(1, 1, 1, 1, blue);

// test that geometrically equivalent constructs are equalSystem.out.println("Equals finds geometrically equivalent constructs equal: "

+ crossBlue.equals(vertFirstCrossBlue));System.out.println("Equals commutes over geometrically equivalent constructs: "

+ vertFirstCrossBlue.equals(crossBlue));

e2dPiece crossRed = new e2dPiece();crossRed.addShape(0, 0, 3, 1, red);crossRed.addShape(1, -1, 1, 1, red);crossRed.addShape(1, 1, 1, 1, red);

// test different instances equal and equal commutesSystem.out.println("Different properties are different: "

+ !crossBlue.equals(crossRed));System.out.println("Equals commutes over different properties: "

+ !crossRed.equals(crossBlue));

}}

Page 357: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 349

A.9.3 GUItest1

package e2dTest;

/******************************************************************************** This is a program to test display options of the GUI** @author adam**/

import java.awt.Color;

import e2dCore.*; import e2dGUI.*;

public class GUItest1 {

/*** @param args*/public static void main(String[] args){

// TODO Auto-generated method stub

e2dGameState gs = new e2dGameState();

e2dPiece theCurrentPiece;theCurrentPiece = new e2dPiece();theCurrentPiece.addShape(0, 0, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(0, 1, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(0, -1, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(-1, 0, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(1, 0, new e2dProperty(Color.BLUE));

for (int i = 0; i < 2; i++){

gs.getBag().add(theCurrentPiece.clone());// gameState.hand.add((BoardPiece)theCurrentPiece.clone());

}

theCurrentPiece = new e2dPiece();theCurrentPiece.addShape(0, 0, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(0, 1, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(1, 1, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(1, 0, new e2dProperty(Color.BLUE));

Page 358: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

350 APPENDIX A. SOURCE CODE

for (int i = 0; i < 2; i++){

gs.getBag().add(theCurrentPiece.clone());// gameState.hand.add((BoardPiece)theCurrentPiece.clone());

}

theCurrentPiece = new e2dPiece();theCurrentPiece.addShape(-2, 0, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(-1, 0, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(0, 0, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(1, 0, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(2, 0, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(0, -1, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(0, -2, new e2dProperty(Color.BLUE));for (int i = 0; i < 2; i++){

gs.getBag().add(theCurrentPiece.clone());// gameState.hand.add((BoardPiece)theCurrentPiece.clone());

}

theCurrentPiece = new e2dPiece();theCurrentPiece.addShape(0, 0, new e2dProperty(Color.RED));theCurrentPiece.addShape(1, 0, new e2dProperty(Color.RED));

for (int i = 0; i < 2; i++){

gs.getBag().add(theCurrentPiece.clone());// gameState.hand.add((BoardPiece)theCurrentPiece.clone());

}

GUIe2dFrame frame = new GUIe2dFrame(gs);

frame.setVisible(true);

}

}

A.9.4 GUItest2

package e2dTest;

import java.awt.Color;

import e2dCore.e2dGameState; import e2dCore.e2dPiece; importe2dCore.e2dProperty; import e2dGUI.GUIe2dFrame;

Page 359: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 351

public class GUItest2 {

public static void main(String args[]){

e2dGameState gs = new e2dGameState();

e2dPiece p = new e2dPiece();p.addShape(0, 0, 4, 1);p.addShape(1, 1, 1, 3, new e2dProperty(Color.BLUE));

gs.getBag().add(p);

GUIe2dFrame f = new GUIe2dFrame(gs);

f.setVisible(true);

}}

A.9.5 GUItest3

package e2dTest;

import java.awt.Color;

import e2dCore.e2dGameState; import e2dCore.e2dInteractor; importe2dCore.e2dPiece; import e2dCore.e2dProperty; importe2dGUI.GUIe2dInteractor;

public class GUItest3 {

public static void main(String args[]){

e2dGameState gs = new e2dGameState();

e2dPiece theCurrentPiece;theCurrentPiece = new e2dPiece();theCurrentPiece.addShape(0, 0, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(0, 1, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(0, -1, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(-1, 0, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(1, 0, new e2dProperty(Color.BLUE));

for (int i = 0; i < 2; i++){

Page 360: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

352 APPENDIX A. SOURCE CODE

gs.getBag().add(theCurrentPiece.clone());// gameState.hand.add((BoardPiece)theCurrentPiece.clone());

}

theCurrentPiece = new e2dPiece();theCurrentPiece.addShape(0, 0, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(0, 1, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(1, 1, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(1, 0, new e2dProperty(Color.BLUE));

for (int i = 0; i < 2; i++){

gs.getBag().add(theCurrentPiece.clone());// gameState.hand.add((BoardPiece)theCurrentPiece.clone());

}

theCurrentPiece = new e2dPiece();theCurrentPiece.addShape(-2, 0, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(-1, 0, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(0, 0, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(1, 0, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(2, 0, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(0, -1, new e2dProperty(Color.BLUE));theCurrentPiece.addShape(0, -2, new e2dProperty(Color.BLUE));for (int i = 0; i < 2; i++){

gs.getBag().add(theCurrentPiece.clone());// gameState.hand.add((BoardPiece)theCurrentPiece.clone());

}

theCurrentPiece = new e2dPiece();theCurrentPiece.addShape(0, 0, new e2dProperty(Color.RED));theCurrentPiece.addShape(1, 0, new e2dProperty(Color.RED));

for (int i = 0; i < 2; i++){

gs.getBag().add(theCurrentPiece.clone());// gameState.hand.add((BoardPiece)theCurrentPiece.clone());

}

GUIe2dInteractor interactor = new GUIe2dInteractor(gs);

interactor.moveFromBag(e2dInteractor.DEST_BOARD);

}

Page 361: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 353

}

A.9.6 HelloWorldTest

package e2dTest;

import e2dCore.*; import e2dGUI.*;

public class HelloWorldTest {

/*** @param args*/public static void main(String[] args){

e2dGameState gs = new e2dGameState();

e2dPiece p = new e2dPiece();p.addShape(0, 0);

e2dPlayer player = new e2dPlayer();player.setName("Adam");gs.addPlayer(player);gs.setCurrPlayer(player);gs.addPieceToBag(p);

GUIe2dInteractor interactor = new GUIe2dInteractor(gs);

e2dPiece played = interactor.moveFromBag(e2dInteractor.DEST_BOARD)[0];

gs.removePieceFromBag(played);gs.addPieceToBoard(played);

interactor.updateGameState(gs);interactor.print("Hello World");gs.addWinner(player);interactor.tellGameOver(gs.getWinners());

}

}

A.9.7 MakeChoiceTest

package e2dTest;

Page 362: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

354 APPENDIX A. SOURCE CODE

import java.util.ArrayList;

import e2dCore.*; import e2dGUI.*;

public class MakeChoiceTest {

/*** @param args*/public static void main(String[] args){

e2dGameState gs = new e2dGameState();e2dPlayer p1 = new e2dPlayer();p1.setName("p1");

gs.setCurrPlayer(p1);GUIe2dInteractor interactor = new GUIe2dInteractor(gs);

ArrayList<String> choices = new ArrayList<String>();

String choice1 = "CHOICE 1";choices.add(choice1);

String choice2 = "CHOICE 2";choices.add(choice2);

String choice3 = "CHOICE 3";choices.add(choice3);

String response;

response = interactor.makeChoice(choices);

System.out.println(response);

response = interactor.makeChoice("YO PUNK", choices);

System.out.println(response);

}

}

A.9.8 MoveFromBagTest

package e2dTest;

Page 363: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 355

import java.awt.Color;

import e2dCore.e2dGameState; import e2dCore.e2dInteractor; importe2dCore.e2dPiece; import e2dCore.e2dPlayer; importe2dCore.e2dProperty; import e2dCore.e2dSet; import e2dCore.e2dShape;import e2dGUI.GUIe2dInteractor;

public class MoveFromBagTest {

/*** @param args*/public static void main(String[] args){

e2dGameState gs = new e2dGameState();

e2dSet<e2dPiece> pieces = new e2dSet<e2dPiece>();

e2dPiece crossBlue = new e2dPiece();crossBlue.addShape(0, 0, 3, 1, new e2dProperty(Color.BLUE));crossBlue.addShape(1, 1, 1, 1, new e2dProperty(Color.BLUE));crossBlue.addShape(1, -1, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(crossBlue);

e2dPiece crossWhite = new e2dPiece();crossWhite.addShape(0, 0, 3, 1, new e2dProperty(Color.WHITE));crossWhite.addShape(1, 1, 1, 1, new e2dProperty(Color.WHITE));crossWhite.addShape(1, -1, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(crossWhite);

e2dPiece largeTBlue = new e2dPiece();largeTBlue.addShape(0, 0, 1, 3, new e2dProperty(Color.BLUE));largeTBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));largeTBlue.addShape(-1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(largeTBlue);

e2dPiece largeTWhite = new e2dPiece();largeTWhite.addShape(0, 0, 1, 3, new e2dProperty(Color.WHITE));largeTWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));largeTWhite.addShape(-1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(largeTWhite);

Page 364: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

356 APPENDIX A. SOURCE CODE

e2dPiece squareBlue = new e2dPiece();squareBlue.addShape(0, 0, 2, 2, new e2dProperty(Color.BLUE));

pieces.add(squareBlue);

e2dPiece squareWhite = new e2dPiece();squareWhite.addShape(0, 0, 2, 2, new e2dProperty(Color.WHITE));

pieces.add(squareWhite);

e2dPiece smallTBlue = new e2dPiece();smallTBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));smallTBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));smallTBlue.addShape(-1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(smallTBlue);

e2dPiece smallTWhite = new e2dPiece();smallTWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));smallTWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));smallTWhite.addShape(-1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(smallTWhite);

e2dPiece longbarBlue = new e2dPiece();longbarBlue.addShape(0, 0, 1, 5, new e2dProperty(Color.BLUE));

pieces.add(longbarBlue);

e2dPiece longbarWhite = new e2dPiece();longbarWhite.addShape(0, 0, 1, 5, new e2dProperty(Color.WHITE));

pieces.add(longbarWhite);

e2dPiece angleBlue = new e2dPiece();angleBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));angleBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(angleBlue);

e2dPiece angleWhite = new e2dPiece();angleWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));angleWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(angleWhite);

Page 365: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 357

e2dPiece mediumbarBlue = new e2dPiece();mediumbarBlue.addShape(0, 0, 1, 3, new e2dProperty(Color.BLUE));

pieces.add(mediumbarBlue);

e2dPiece mediumbarWhite = new e2dPiece();mediumbarWhite.addShape(0, 0, 1, 3, new e2dProperty(Color.WHITE));

pieces.add(mediumbarWhite);

e2dPiece smallbarBlue = new e2dPiece();smallbarBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));

pieces.add(smallbarBlue);

e2dPiece smallbarWhite = new e2dPiece();smallbarWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));

pieces.add(smallbarWhite);gs.getFlags().mayFlip();gs.getFlags().mayRotate();gs.getFlags().revealBag();

if (gs.getFlags() == null)System.out.println("OH FUCK");

for (e2dPiece p : pieces){

p.setFlags(gs.getFlags());}

e2dPlayer p1 = new e2dPlayer();p1.setName("p1");p1.addPieceToHand(crossBlue);p1.addPieceToHand(largeTBlue);p1.addPieceToHand(longbarBlue);p1.addPieceToHand(squareBlue);p1.addPieceToHand(smallTBlue);p1.addPieceToHand(angleBlue);p1.addPieceToHand(mediumbarBlue);p1.addPieceToHand(smallbarBlue);

gs.addPlayer(p1);

gs.addPieceToBag(crossWhite);

Page 366: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

358 APPENDIX A. SOURCE CODE

gs.addPieceToBag(crossBlue);gs.addPieceToBag(smallTWhite);gs.addPieceToBag(smallTBlue);gs.addPieceToBag(largeTWhite);gs.addPieceToBag(largeTBlue);gs.addPieceToBag(squareWhite);gs.addPieceToBag(squareBlue);gs.addPieceToBag(angleWhite);gs.addPieceToBag(angleBlue);gs.addPieceToBag(longbarWhite);gs.addPieceToBag(longbarBlue);gs.addPieceToBag(mediumbarWhite);gs.addPieceToBag(mediumbarBlue);gs.addPieceToBag(smallbarWhite);gs.addPieceToBag(smallbarBlue);

gs.getBoard().setHeight(9);gs.getBoard().setWidth(9);

gs.setCurrPlayer(p1);

GUIe2dInteractor interactor = new GUIe2dInteractor(gs);interactor.updateGameState(gs);

e2dPiece[] played;

int i=0;while(true){

played = interactor.moveFromBag(e2dInteractor.DEST_BOARD);gs.removePieceFromBag(played[1]);gs.addPieceToBoard(played[0]);interactor.updateGameState(gs);

for(e2dPiece p : gs.getBag()){

for(e2dShape s : p.getShapes()){

if(i%2 == 0){

s.setProperty(new e2dProperty(Color.BLUE));}else{

s.setProperty(new e2dProperty(Color.RED));

Page 367: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 359

}}

}

interactor.updateGameState(gs);i++;

/*played = interactor.moveFromBag(e2dInteractor.DEST_CURRHAND);gs.removePieceFromBag(played[1]);gs.addPieceToCurrPlayerHand(played[0]);interactor.updateGameState(gs);*/}//if (null != interactor.moveFromBag(e2dInteractor.DEST_BAG))// System.out.println("ERROR");

}

}

A.9.9 MoveFromBoardTest

package e2dTest;

import java.awt.Color;

import e2dCore.e2dGameState; import e2dCore.e2dInteractor; importe2dCore.e2dPiece; import e2dCore.e2dPlayer; importe2dCore.e2dProperty; import e2dCore.e2dSet; importe2dGUI.GUIe2dInteractor;

public class MoveFromBoardTest {

/*** @param args*//*** @param args*/public static void main(String[] args){

e2dGameState gs = new e2dGameState();

e2dSet<e2dPiece> pieces = new e2dSet<e2dPiece>();

Page 368: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

360 APPENDIX A. SOURCE CODE

e2dPiece crossBlue = new e2dPiece();crossBlue.addShape(0, 0, 3, 1, new e2dProperty(Color.BLUE));crossBlue.addShape(1, 1, 1, 1, new e2dProperty(Color.BLUE));crossBlue.addShape(1, -1, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(crossBlue);

e2dPiece crossWhite = new e2dPiece();crossWhite.addShape(0, 0, 3, 1, new e2dProperty(Color.WHITE));crossWhite.addShape(1, 1, 1, 1, new e2dProperty(Color.WHITE));crossWhite.addShape(1, -1, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(crossWhite);

e2dPiece largeTBlue = new e2dPiece();largeTBlue.addShape(0, 0, 1, 3, new e2dProperty(Color.BLUE));largeTBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));largeTBlue.addShape(-1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(largeTBlue);

e2dPiece largeTWhite = new e2dPiece();largeTWhite.addShape(0, 0, 1, 3, new e2dProperty(Color.WHITE));largeTWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));largeTWhite.addShape(-1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(largeTWhite);

e2dPiece squareBlue = new e2dPiece();squareBlue.addShape(0, 0, 2, 2, new e2dProperty(Color.BLUE));

pieces.add(squareBlue);

e2dPiece squareWhite = new e2dPiece();squareWhite.addShape(0, 0, 2, 2, new e2dProperty(Color.WHITE));

pieces.add(squareWhite);

e2dPiece smallTBlue = new e2dPiece();smallTBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));smallTBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));smallTBlue.addShape(-1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(smallTBlue);

e2dPiece smallTWhite = new e2dPiece();

Page 369: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 361

smallTWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));smallTWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));smallTWhite.addShape(-1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(smallTWhite);

e2dPiece longbarBlue = new e2dPiece();longbarBlue.addShape(0, 0, 1, 5, new e2dProperty(Color.BLUE));

pieces.add(longbarBlue);

e2dPiece longbarWhite = new e2dPiece();longbarWhite.addShape(0, 0, 1, 5, new e2dProperty(Color.WHITE));

pieces.add(longbarWhite);

e2dPiece angleBlue = new e2dPiece();angleBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));angleBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(angleBlue);

e2dPiece angleWhite = new e2dPiece();angleWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));angleWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(angleWhite);

e2dPiece mediumbarBlue = new e2dPiece();mediumbarBlue.addShape(0, 0, 1, 3, new e2dProperty(Color.BLUE));

pieces.add(mediumbarBlue);

e2dPiece mediumbarWhite = new e2dPiece();mediumbarWhite.addShape(0, 0, 1, 3, new e2dProperty(Color.WHITE));

pieces.add(mediumbarWhite);

e2dPiece smallbarBlue = new e2dPiece();smallbarBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));

pieces.add(smallbarBlue);

e2dPiece smallbarWhite = new e2dPiece();smallbarWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));

Page 370: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

362 APPENDIX A. SOURCE CODE

pieces.add(smallbarWhite);

gs.getFlags().mayNotFlip();gs.getFlags().mayRotate();gs.getFlags().revealBag();

//gs.getBoard().setHeight(9);//gs.getBoard().setWidth(9);

for (e2dPiece p : pieces){

p.setFlags(gs.getFlags());}e2dPlayer p1 = new e2dPlayer();p1.setName("p1");p1.addPieceToHand(crossBlue);p1.addPieceToHand(largeTBlue);p1.addPieceToHand(longbarBlue);p1.addPieceToHand(squareBlue);p1.addPieceToHand(smallTBlue);p1.addPieceToHand(angleBlue);p1.addPieceToHand(mediumbarBlue);p1.addPieceToHand(smallbarBlue);

gs.addPlayer(p1);

gs.addPieceToBag(crossWhite);gs.addPieceToBag(crossBlue);gs.addPieceToBag(smallTWhite);gs.addPieceToBag(smallTBlue);gs.addPieceToBag(largeTWhite);gs.addPieceToBag(largeTBlue);gs.addPieceToBag(squareWhite);gs.addPieceToBag(squareBlue);gs.addPieceToBag(angleWhite);gs.addPieceToBag(angleBlue);gs.addPieceToBag(longbarWhite);gs.addPieceToBag(longbarBlue);gs.addPieceToBag(mediumbarWhite);gs.addPieceToBag(mediumbarBlue);gs.addPieceToBag(smallbarWhite);gs.addPieceToBag(smallbarBlue);

gs.setCurrPlayer(p1);

GUIe2dInteractor interactor = new GUIe2dInteractor(gs);

Page 371: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 363

gs.getBoard().putPiece(new e2dPiece(1, 1, smallbarWhite));gs.getBoard().putPiece(new e2dPiece(-4, -1, crossBlue));gs.getBoard().putPiece(new e2dPiece(-2, 3, angleWhite));

interactor.updateGameState(gs);

e2dPiece[] played = new e2dPiece[2];

played = interactor.moveFromBoard(e2dInteractor.DEST_BAG);gs.getBoard().removePiece(played[1]);gs.addPieceToBag(played[0]);interactor.updateGameState(gs);

played = interactor.moveFromBoard(e2dInteractor.DEST_CURRHAND);gs.getBoard().removePiece(played[1]);gs.addPieceToCurrPlayerHand(played[0]);interactor.updateGameState(gs);

played = interactor.moveFromBoard(e2dInteractor.DEST_BOARD);gs.getBoard().removePiece(played[1]);gs.addPieceToBoard(played[0]);interactor.updateGameState(gs);

}

}

A.9.10 MoveFromCurrHandTest

package e2dTest;

import java.awt.Color;

import e2dCore.e2dGameState; import e2dCore.e2dInteractor; importe2dCore.e2dPiece; import e2dCore.e2dPlayer; importe2dCore.e2dProperty; import e2dCore.e2dSet; importe2dGUI.GUIe2dInteractor;

public class MoveFromCurrHandTest {

/*** @param args*/public static void main(String[] args){

Page 372: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

364 APPENDIX A. SOURCE CODE

e2dGameState gs = new e2dGameState();

e2dSet<e2dPiece> pieces = new e2dSet<e2dPiece>();

e2dPiece crossBlue = new e2dPiece();crossBlue.addShape(0, 0, 3, 1, new e2dProperty(Color.BLUE));crossBlue.addShape(1, 1, 1, 1, new e2dProperty(Color.BLUE));crossBlue.addShape(1, -1, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(crossBlue);

e2dPiece crossWhite = new e2dPiece();crossWhite.addShape(0, 0, 3, 1, new e2dProperty(Color.WHITE));crossWhite.addShape(1, 1, 1, 1, new e2dProperty(Color.WHITE));crossWhite.addShape(1, -1, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(crossWhite);

e2dPiece largeTBlue = new e2dPiece();largeTBlue.addShape(0, 0, 1, 3, new e2dProperty(Color.BLUE));largeTBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));largeTBlue.addShape(-1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(largeTBlue);

e2dPiece largeTWhite = new e2dPiece();largeTWhite.addShape(0, 0, 1, 3, new e2dProperty(Color.WHITE));largeTWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));largeTWhite.addShape(-1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(largeTWhite);

e2dPiece squareBlue = new e2dPiece();squareBlue.addShape(0, 0, 2, 2, new e2dProperty(Color.BLUE));

pieces.add(squareBlue);

e2dPiece squareWhite = new e2dPiece();squareWhite.addShape(0, 0, 2, 2, new e2dProperty(Color.WHITE));

pieces.add(squareWhite);

e2dPiece smallTBlue = new e2dPiece();smallTBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));smallTBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));smallTBlue.addShape(-1, 0, 1, 1, new e2dProperty(Color.BLUE));

Page 373: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 365

pieces.add(smallTBlue);

e2dPiece smallTWhite = new e2dPiece();smallTWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));smallTWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));smallTWhite.addShape(-1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(smallTWhite);

e2dPiece longbarBlue = new e2dPiece();longbarBlue.addShape(0, 0, 1, 5, new e2dProperty(Color.BLUE));

pieces.add(longbarBlue);

e2dPiece longbarWhite = new e2dPiece();longbarWhite.addShape(0, 0, 1, 5, new e2dProperty(Color.WHITE));

pieces.add(longbarWhite);

e2dPiece angleBlue = new e2dPiece();angleBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));angleBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(angleBlue);

e2dPiece angleWhite = new e2dPiece();angleWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));angleWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(angleWhite);

e2dPiece mediumbarBlue = new e2dPiece();mediumbarBlue.addShape(0, 0, 1, 3, new e2dProperty(Color.BLUE));

pieces.add(mediumbarBlue);

e2dPiece mediumbarWhite = new e2dPiece();mediumbarWhite.addShape(0, 0, 1, 3, new e2dProperty(Color.WHITE));

pieces.add(mediumbarWhite);

e2dPiece smallbarBlue = new e2dPiece();smallbarBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));

pieces.add(smallbarBlue);

Page 374: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

366 APPENDIX A. SOURCE CODE

e2dPiece smallbarWhite = new e2dPiece();smallbarWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));

pieces.add(smallbarWhite);

for (e2dPiece p : pieces){

p.putInHand();}e2dPlayer p1 = new e2dPlayer();p1.setName("p1");p1.addPieceToHand(new e2dPiece(crossBlue));p1.addPieceToHand(new e2dPiece(largeTBlue));p1.addPieceToHand(new e2dPiece(longbarBlue));p1.addPieceToHand(new e2dPiece(squareBlue));p1.addPieceToHand(new e2dPiece(smallTBlue));p1.addPieceToHand(new e2dPiece(angleBlue));p1.addPieceToHand(new e2dPiece(mediumbarBlue));p1.addPieceToHand(new e2dPiece(smallbarBlue));

gs.addPlayer(p1);

for (e2dPiece p : pieces){

p.putInBag();}

gs.addPieceToBag(new e2dPiece(crossWhite));gs.addPieceToBag(new e2dPiece(crossBlue));gs.addPieceToBag(new e2dPiece(smallTWhite));gs.addPieceToBag(new e2dPiece(smallTBlue));gs.addPieceToBag(new e2dPiece(largeTWhite));gs.addPieceToBag(new e2dPiece(largeTBlue));gs.addPieceToBag(new e2dPiece(squareWhite));gs.addPieceToBag(new e2dPiece(squareBlue));gs.addPieceToBag(new e2dPiece(angleWhite));gs.addPieceToBag(new e2dPiece(angleBlue));gs.addPieceToBag(new e2dPiece(longbarWhite));gs.addPieceToBag(new e2dPiece(longbarBlue));gs.addPieceToBag(new e2dPiece(mediumbarWhite));gs.addPieceToBag(new e2dPiece(mediumbarBlue));gs.addPieceToBag(new e2dPiece(smallbarWhite));gs.addPieceToBag(new e2dPiece(smallbarBlue));

gs.getFlags().mayNotFlip();

Page 375: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 367

gs.getFlags().mayRotate();gs.getFlags().revealBag();

gs.getBoard().setHeight(9);gs.getBoard().setWidth(9);

gs.setCurrPlayer(p1);

GUIe2dInteractor interactor = new GUIe2dInteractor(gs);interactor.updateGameState(gs);

e2dPiece[] played = new e2dPiece[2];while(true){

try{interactor.updateGameState(gs);

played = interactor.moveFromCurrHand(e2dInteractor.DEST_BOARD);gs.addPieceToBoard(played[0]);gs.removePieceFromPlayer(played[1], gs.getCurrPlayer());interactor.updateGameState(gs);

played = interactor.moveFromCurrHand(e2dInteractor.DEST_CURRHAND);

if (played != null)System.out.println("ERROR");

played = interactor.moveFromCurrHand(e2dInteractor.DEST_BAG);gs.addPieceToBag(played[0]);gs.removePieceFromPlayer(played[1], gs.getCurrPlayer());interactor.updateGameState(gs);}catch(Exception e){e.printStackTrace();}

}}

}

A.9.11 MoveFromSetTest

package e2dTest;

import java.awt.Color;

import e2dCore.*; import e2dGUI.*;

public class MoveFromSetTest {

/**

Page 376: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

368 APPENDIX A. SOURCE CODE

* @param args*/public static void main(String[] args){

e2dGameState gs = new e2dGameState();

e2dSet<e2dPiece> pieces = new e2dSet<e2dPiece>();

e2dPiece crossBlue = new e2dPiece();crossBlue.addShape(0, 0, 3, 1, new e2dProperty(Color.BLUE));crossBlue.addShape(1, 1, 1, 1, new e2dProperty(Color.BLUE));crossBlue.addShape(1, -1, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(crossBlue);

e2dPiece crossWhite = new e2dPiece();crossWhite.addShape(0, 0, 3, 1, new e2dProperty(Color.WHITE));crossWhite.addShape(1, 1, 1, 1, new e2dProperty(Color.WHITE));crossWhite.addShape(1, -1, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(crossWhite);

e2dPiece largeTBlue = new e2dPiece();largeTBlue.addShape(0, 0, 1, 3, new e2dProperty(Color.BLUE));largeTBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));largeTBlue.addShape(-1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(largeTBlue);

e2dPiece largeTWhite = new e2dPiece();largeTWhite.addShape(0, 0, 1, 3, new e2dProperty(Color.WHITE));largeTWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));largeTWhite.addShape(-1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(largeTWhite);

e2dPiece squareBlue = new e2dPiece();squareBlue.addShape(0, 0, 2, 2, new e2dProperty(Color.BLUE));

pieces.add(squareBlue);

e2dPiece squareWhite = new e2dPiece();squareWhite.addShape(0, 0, 2, 2, new e2dProperty(Color.WHITE));

pieces.add(squareWhite);

Page 377: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 369

e2dPiece smallTBlue = new e2dPiece();smallTBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));smallTBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));smallTBlue.addShape(-1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(smallTBlue);

e2dPiece smallTWhite = new e2dPiece();smallTWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));smallTWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));smallTWhite.addShape(-1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(smallTWhite);

e2dPiece longbarBlue = new e2dPiece();longbarBlue.addShape(0, 0, 1, 5, new e2dProperty(Color.BLUE));

pieces.add(longbarBlue);

e2dPiece longbarWhite = new e2dPiece();longbarWhite.addShape(0, 0, 1, 5, new e2dProperty(Color.WHITE));

pieces.add(longbarWhite);

e2dPiece angleBlue = new e2dPiece();angleBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));angleBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(angleBlue);

e2dPiece angleWhite = new e2dPiece();angleWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));angleWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(angleWhite);

e2dPiece mediumbarBlue = new e2dPiece();mediumbarBlue.addShape(0, 0, 1, 3, new e2dProperty(Color.BLUE));

pieces.add(mediumbarBlue);

e2dPiece mediumbarWhite = new e2dPiece();mediumbarWhite.addShape(0, 0, 1, 3, new e2dProperty(Color.WHITE));

pieces.add(mediumbarWhite);

Page 378: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

370 APPENDIX A. SOURCE CODE

e2dPiece smallbarBlue = new e2dPiece();smallbarBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));

pieces.add(smallbarBlue);

e2dPiece smallbarWhite = new e2dPiece();smallbarWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));

pieces.add(smallbarWhite);

e2dPlayer p1 = new e2dPlayer();p1.setName("p1");p1.addPieceToHand(crossBlue);p1.addPieceToHand(largeTBlue);p1.addPieceToHand(longbarBlue);p1.addPieceToHand(squareBlue);p1.addPieceToHand(smallTBlue);p1.addPieceToHand(angleBlue);p1.addPieceToHand(mediumbarBlue);p1.addPieceToHand(smallbarBlue);

gs.addPlayer(p1);

gs.addPieceToBag(crossWhite);gs.addPieceToBag(crossBlue);gs.addPieceToBag(smallTWhite);gs.addPieceToBag(smallTBlue);gs.addPieceToBag(largeTWhite);gs.addPieceToBag(largeTBlue);gs.addPieceToBag(squareWhite);gs.addPieceToBag(squareBlue);gs.addPieceToBag(angleWhite);gs.addPieceToBag(angleBlue);gs.addPieceToBag(longbarWhite);gs.addPieceToBag(longbarBlue);gs.addPieceToBag(mediumbarWhite);gs.addPieceToBag(mediumbarBlue);gs.addPieceToBag(smallbarWhite);gs.addPieceToBag(smallbarBlue);

gs.getFlags().mayNotFlip();gs.getFlags().mayRotate();gs.getFlags().revealBag();

gs.getBoard().setHeight(9);gs.getBoard().setWidth(9);

Page 379: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 371

gs.setCurrPlayer(p1);

GUIe2dInteractor interactor = new GUIe2dInteractor(gs);interactor.updateGameState(gs);e2dPiece played = interactor.moveFromSet(e2dInteractor.DEST_BOARD,

pieces)[0];

gs.addPieceToBoard(played);interactor.updateGameState(gs);

played = interactor.moveFromSet(e2dInteractor.DEST_BAG, pieces)[0];gs.addPieceToBag(played);interactor.updateGameState(gs);

played = interactor.moveFromSet(e2dInteractor.DEST_CURRHAND, pieces)[0];gs.addPieceToCurrPlayerHand(played);interactor.updateGameState(gs);

}

}

A.9.12 MoveFromSomeHandTest

package e2dTest;

import java.awt.Color;

import e2dCore.e2dGameState; import e2dCore.e2dInteractor; importe2dCore.e2dPiece; import e2dCore.e2dPlayer; importe2dCore.e2dProperty; import e2dCore.e2dSet; importe2dGUI.GUIe2dInteractor;

public class MoveFromSomeHandTest {

/*** @param args*/public static void main(String[] args){

e2dGameState gs = new e2dGameState();

e2dSet<e2dPiece> pieces = new e2dSet<e2dPiece>();

e2dPiece crossBlue = new e2dPiece();crossBlue.addShape(0, 0, 3, 1, new e2dProperty(Color.BLUE));

Page 380: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

372 APPENDIX A. SOURCE CODE

crossBlue.addShape(1, 1, 1, 1, new e2dProperty(Color.BLUE));crossBlue.addShape(1, -1, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(crossBlue);

e2dPiece crossWhite = new e2dPiece();crossWhite.addShape(0, 0, 3, 1, new e2dProperty(Color.WHITE));crossWhite.addShape(1, 1, 1, 1, new e2dProperty(Color.WHITE));crossWhite.addShape(1, -1, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(crossWhite);

e2dPiece largeTBlue = new e2dPiece();largeTBlue.addShape(0, 0, 1, 3, new e2dProperty(Color.BLUE));largeTBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));largeTBlue.addShape(-1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(largeTBlue);

e2dPiece largeTWhite = new e2dPiece();largeTWhite.addShape(0, 0, 1, 3, new e2dProperty(Color.WHITE));largeTWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));largeTWhite.addShape(-1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(largeTWhite);

e2dPiece squareBlue = new e2dPiece();squareBlue.addShape(0, 0, 2, 2, new e2dProperty(Color.BLUE));

pieces.add(squareBlue);

e2dPiece squareWhite = new e2dPiece();squareWhite.addShape(0, 0, 2, 2, new e2dProperty(Color.WHITE));

pieces.add(squareWhite);

e2dPiece smallTBlue = new e2dPiece();smallTBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));smallTBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));smallTBlue.addShape(-1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(smallTBlue);

e2dPiece smallTWhite = new e2dPiece();smallTWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));smallTWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));

Page 381: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 373

smallTWhite.addShape(-1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(smallTWhite);

e2dPiece longbarBlue = new e2dPiece();longbarBlue.addShape(0, 0, 1, 5, new e2dProperty(Color.BLUE));

pieces.add(longbarBlue);

e2dPiece longbarWhite = new e2dPiece();longbarWhite.addShape(0, 0, 1, 5, new e2dProperty(Color.WHITE));

pieces.add(longbarWhite);

e2dPiece angleBlue = new e2dPiece();angleBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));angleBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(angleBlue);

e2dPiece angleWhite = new e2dPiece();angleWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));angleWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(angleWhite);

e2dPiece mediumbarBlue = new e2dPiece();mediumbarBlue.addShape(0, 0, 1, 3, new e2dProperty(Color.BLUE));

pieces.add(mediumbarBlue);

e2dPiece mediumbarWhite = new e2dPiece();mediumbarWhite.addShape(0, 0, 1, 3, new e2dProperty(Color.WHITE));

pieces.add(mediumbarWhite);

e2dPiece smallbarBlue = new e2dPiece();smallbarBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));

pieces.add(smallbarBlue);

e2dPiece smallbarWhite = new e2dPiece();smallbarWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));

pieces.add(smallbarWhite);

Page 382: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

374 APPENDIX A. SOURCE CODE

gs.getFlags().mayFlip();gs.getFlags().mayRotate();gs.getFlags().revealBag();//gs.getFlags().revealHands();

for (e2dPiece p : pieces){

p.setFlags(gs.getFlags());}

e2dPlayer p1 = new e2dPlayer();p1.setName("p1");p1.addPieceToHand(new e2dPiece(crossBlue));p1.addPieceToHand(new e2dPiece(largeTBlue));p1.addPieceToHand(new e2dPiece(longbarBlue));p1.addPieceToHand(new e2dPiece(squareBlue));p1.addPieceToHand(new e2dPiece(smallTBlue));p1.addPieceToHand(new e2dPiece(angleBlue));p1.addPieceToHand(new e2dPiece(mediumbarBlue));p1.addPieceToHand(new e2dPiece(smallbarBlue));

gs.addPlayer(p1);

e2dPlayer p2 = new e2dPlayer();p2.setName("p2");p2.addPieceToHand(new e2dPiece(crossWhite));p2.addPieceToHand(new e2dPiece(largeTWhite));p2.addPieceToHand(new e2dPiece(longbarWhite));p2.addPieceToHand(new e2dPiece(squareWhite));p2.addPieceToHand(new e2dPiece(smallTWhite));p2.addPieceToHand(new e2dPiece(angleWhite));p2.addPieceToHand(new e2dPiece(mediumbarWhite));p2.addPieceToHand(new e2dPiece(smallbarWhite));

gs.addPlayer(p2);

e2dPlayer p3 = new e2dPlayer();p3.setName("p3");p3.addPieceToHand(new e2dPiece(crossBlue));p3.addPieceToHand(new e2dPiece(largeTBlue));p3.addPieceToHand(new e2dPiece(longbarBlue));p3.addPieceToHand(new e2dPiece(squareBlue));p3.addPieceToHand(new e2dPiece(smallTBlue));p3.addPieceToHand(new e2dPiece(angleBlue));p3.addPieceToHand(new e2dPiece(mediumbarBlue));p3.addPieceToHand(new e2dPiece(smallbarBlue));

Page 383: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 375

gs.addPlayer(p3);

e2dPlayer p4 = new e2dPlayer();p4.setName("p4");p4.addPieceToHand(new e2dPiece(crossWhite));p4.addPieceToHand(new e2dPiece(largeTWhite));p4.addPieceToHand(new e2dPiece(longbarWhite));p4.addPieceToHand(new e2dPiece(squareWhite));p4.addPieceToHand(new e2dPiece(smallTWhite));p4.addPieceToHand(new e2dPiece(angleWhite));p4.addPieceToHand(new e2dPiece(mediumbarWhite));p4.addPieceToHand(new e2dPiece(smallbarWhite));

gs.addPlayer(p4);

gs.addPieceToBag(new e2dPiece(crossWhite));gs.addPieceToBag(new e2dPiece(crossBlue));gs.addPieceToBag(new e2dPiece(smallTWhite));gs.addPieceToBag(new e2dPiece(smallTBlue));gs.addPieceToBag(new e2dPiece(largeTWhite));gs.addPieceToBag(new e2dPiece(largeTBlue));gs.addPieceToBag(new e2dPiece(squareWhite));gs.addPieceToBag(new e2dPiece(squareBlue));gs.addPieceToBag(new e2dPiece(angleWhite));gs.addPieceToBag(new e2dPiece(angleBlue));gs.addPieceToBag(new e2dPiece(longbarWhite));gs.addPieceToBag(new e2dPiece(longbarBlue));gs.addPieceToBag(new e2dPiece(mediumbarWhite));gs.addPieceToBag(new e2dPiece(mediumbarBlue));gs.addPieceToBag(new e2dPiece(smallbarWhite));gs.addPieceToBag(new e2dPiece(smallbarBlue));

gs.setCurrPlayer(p1);

GUIe2dInteractor interactor = new GUIe2dInteractor(gs);

e2dPiece[] played = new e2dPiece[2];

played = interactor.moveFromSomeHand(e2dInteractor.DEST_BAG, p2);gs.removePieceFromPlayer(played[1], p2);gs.addPieceToBag(played[0]);interactor.updateGameState(gs);

played = interactor.moveFromSomeHand(e2dInteractor.DEST_BAG, p3);gs.removePieceFromPlayer(played[1], p3);

Page 384: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

376 APPENDIX A. SOURCE CODE

gs.addPieceToBag(played[0]);interactor.updateGameState(gs);

played = interactor.moveFromSomeHand(e2dInteractor.DEST_BAG, p4);gs.removePieceFromPlayer(played[1], p4);gs.addPieceToBag(played[0]);interactor.updateGameState(gs);

played = interactor.moveFromSomeHand(e2dInteractor.DEST_BOARD, p2);gs.removePieceFromPlayer(played[1], p2);gs.addPieceToBoard(played[0]);interactor.updateGameState(gs);

played = interactor.moveFromSomeHand(e2dInteractor.DEST_BOARD, p3);gs.removePieceFromPlayer(played[1], p3);gs.addPieceToBoard(played[0]);interactor.updateGameState(gs);

played = interactor.moveFromSomeHand(e2dInteractor.DEST_BOARD, p4);gs.removePieceFromPlayer(played[1], p4);gs.addPieceToBoard(played[0]);interactor.updateGameState(gs);

played = interactor.moveFromSomeHand(e2dInteractor.DEST_CURRHAND, p2);gs.removePieceFromPlayer(played[1], p2);gs.addPieceToCurrPlayerHand(played[0]);interactor.updateGameState(gs);

played = interactor.moveFromSomeHand(e2dInteractor.DEST_CURRHAND, p3);gs.removePieceFromPlayer(played[1], p3);gs.addPieceToCurrPlayerHand(played[0]);interactor.updateGameState(gs);

played = interactor.moveFromSomeHand(e2dInteractor.DEST_CURRHAND, p4);gs.removePieceFromPlayer(played[1], p4);gs.addPieceToCurrPlayerHand(played[0]);interactor.updateGameState(gs);

}

}

A.9.13 MoveFromSomeHandToSomeHandTest

package e2dTest;

Page 385: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 377

import java.awt.Color;

import e2dCore.e2dGameState; import e2dCore.e2dPiece; importe2dCore.e2dPlayer; import e2dCore.e2dProperty; importe2dCore.e2dSet; import e2dGUI.GUIe2dInteractor;

public class MoveFromSomeHandToSomeHandTest {

/*** @param args*/public static void main(String[] args){

e2dGameState gs = new e2dGameState();

e2dSet<e2dPiece> pieces = new e2dSet<e2dPiece>();

e2dPiece crossBlue = new e2dPiece();crossBlue.addShape(0, 0, 3, 1, new e2dProperty(Color.BLUE));crossBlue.addShape(1, 1, 1, 1, new e2dProperty(Color.BLUE));crossBlue.addShape(1, -1, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(crossBlue);

e2dPiece crossWhite = new e2dPiece();crossWhite.addShape(0, 0, 3, 1, new e2dProperty(Color.WHITE));crossWhite.addShape(1, 1, 1, 1, new e2dProperty(Color.WHITE));crossWhite.addShape(1, -1, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(crossWhite);

e2dPiece largeTBlue = new e2dPiece();largeTBlue.addShape(0, 0, 1, 3, new e2dProperty(Color.BLUE));largeTBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));largeTBlue.addShape(-1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(largeTBlue);

e2dPiece largeTWhite = new e2dPiece();largeTWhite.addShape(0, 0, 1, 3, new e2dProperty(Color.WHITE));largeTWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));largeTWhite.addShape(-1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(largeTWhite);

e2dPiece squareBlue = new e2dPiece();

Page 386: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

378 APPENDIX A. SOURCE CODE

squareBlue.addShape(0, 0, 2, 2, new e2dProperty(Color.BLUE));

pieces.add(squareBlue);

e2dPiece squareWhite = new e2dPiece();squareWhite.addShape(0, 0, 2, 2, new e2dProperty(Color.WHITE));

pieces.add(squareWhite);

e2dPiece smallTBlue = new e2dPiece();smallTBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));smallTBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));smallTBlue.addShape(-1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(smallTBlue);

e2dPiece smallTWhite = new e2dPiece();smallTWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));smallTWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));smallTWhite.addShape(-1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(smallTWhite);

e2dPiece longbarBlue = new e2dPiece();longbarBlue.addShape(0, 0, 1, 5, new e2dProperty(Color.BLUE));

pieces.add(longbarBlue);

e2dPiece longbarWhite = new e2dPiece();longbarWhite.addShape(0, 0, 1, 5, new e2dProperty(Color.WHITE));

pieces.add(longbarWhite);

e2dPiece angleBlue = new e2dPiece();angleBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));angleBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(angleBlue);

e2dPiece angleWhite = new e2dPiece();angleWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));angleWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(angleWhite);

e2dPiece mediumbarBlue = new e2dPiece();

Page 387: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 379

mediumbarBlue.addShape(0, 0, 1, 3, new e2dProperty(Color.BLUE));

pieces.add(mediumbarBlue);

e2dPiece mediumbarWhite = new e2dPiece();mediumbarWhite.addShape(0, 0, 1, 3, new e2dProperty(Color.WHITE));

pieces.add(mediumbarWhite);

e2dPiece smallbarBlue = new e2dPiece();smallbarBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));

pieces.add(smallbarBlue);

e2dPiece smallbarWhite = new e2dPiece();smallbarWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));

pieces.add(smallbarWhite);

gs.getFlags().mayFlip();gs.getFlags().mayRotate();gs.getFlags().revealBag();gs.getFlags().revealHands();

for (e2dPiece p : pieces){

p.setFlags(gs.getFlags());}

e2dPlayer p1 = new e2dPlayer();p1.setName("p1");p1.addPieceToHand(new e2dPiece(crossBlue));p1.addPieceToHand(new e2dPiece(largeTBlue));p1.addPieceToHand(new e2dPiece(longbarBlue));p1.addPieceToHand(new e2dPiece(squareBlue));p1.addPieceToHand(new e2dPiece(smallTBlue));p1.addPieceToHand(new e2dPiece(angleBlue));p1.addPieceToHand(new e2dPiece(mediumbarBlue));p1.addPieceToHand(new e2dPiece(smallbarBlue));

gs.addPlayer(p1);

e2dPlayer p2 = new e2dPlayer();p2.setName("p2");p2.addPieceToHand(new e2dPiece(crossWhite));p2.addPieceToHand(new e2dPiece(largeTWhite));

Page 388: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

380 APPENDIX A. SOURCE CODE

p2.addPieceToHand(new e2dPiece(longbarWhite));p2.addPieceToHand(new e2dPiece(squareWhite));p2.addPieceToHand(new e2dPiece(smallTWhite));p2.addPieceToHand(new e2dPiece(angleWhite));p2.addPieceToHand(new e2dPiece(mediumbarWhite));p2.addPieceToHand(new e2dPiece(smallbarWhite));

gs.addPlayer(p2);

e2dPlayer p3 = new e2dPlayer();p3.setName("p3");p3.addPieceToHand(new e2dPiece(crossBlue));p3.addPieceToHand(new e2dPiece(largeTBlue));p3.addPieceToHand(new e2dPiece(longbarBlue));p3.addPieceToHand(new e2dPiece(squareBlue));p3.addPieceToHand(new e2dPiece(smallTBlue));p3.addPieceToHand(new e2dPiece(angleBlue));p3.addPieceToHand(new e2dPiece(mediumbarBlue));p3.addPieceToHand(new e2dPiece(smallbarBlue));

gs.addPlayer(p3);

e2dPlayer p4 = new e2dPlayer();p4.setName("p4");p4.addPieceToHand(new e2dPiece(crossWhite));p4.addPieceToHand(new e2dPiece(largeTWhite));p4.addPieceToHand(new e2dPiece(longbarWhite));p4.addPieceToHand(new e2dPiece(squareWhite));p4.addPieceToHand(new e2dPiece(smallTWhite));p4.addPieceToHand(new e2dPiece(angleWhite));p4.addPieceToHand(new e2dPiece(mediumbarWhite));p4.addPieceToHand(new e2dPiece(smallbarWhite));

gs.addPlayer(p4);

gs.addPieceToBag(new e2dPiece(crossWhite));gs.addPieceToBag(new e2dPiece(crossBlue));gs.addPieceToBag(new e2dPiece(smallTWhite));gs.addPieceToBag(new e2dPiece(smallTBlue));gs.addPieceToBag(new e2dPiece(largeTWhite));gs.addPieceToBag(new e2dPiece(largeTBlue));gs.addPieceToBag(new e2dPiece(squareWhite));gs.addPieceToBag(new e2dPiece(squareBlue));gs.addPieceToBag(new e2dPiece(angleWhite));gs.addPieceToBag(new e2dPiece(angleBlue));gs.addPieceToBag(new e2dPiece(longbarWhite));

Page 389: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 381

gs.addPieceToBag(new e2dPiece(longbarBlue));gs.addPieceToBag(new e2dPiece(mediumbarWhite));gs.addPieceToBag(new e2dPiece(mediumbarBlue));gs.addPieceToBag(new e2dPiece(smallbarWhite));gs.addPieceToBag(new e2dPiece(smallbarBlue));

gs.setCurrPlayer(p1);

GUIe2dInteractor interactor = new GUIe2dInteractor(gs);

e2dPiece[] played = new e2dPiece[2];

played = interactor.moveFromSomeHandToSomeHand(p2, p3);gs.removePieceFromPlayer(played[1], p3);gs.addPieceToPlayer(played[0], p2);interactor.updateGameState(gs);

played = interactor.moveFromSomeHandToSomeHand(p3, p4);gs.removePieceFromPlayer(played[1], p4);gs.addPieceToPlayer(played[0], p3);interactor.updateGameState(gs);

}

}

A.9.14 MoveToBoardAdjacencyTest

package e2dTest;

import java.awt.Color;

import e2dCore.e2dGameState; import e2dCore.e2dInteractor; importe2dCore.e2dPiece; import e2dCore.e2dPlayer; importe2dCore.e2dProperty; import e2dCore.e2dSet; importe2dGUI.GUIe2dInteractor;

public class MoveToBoardAdjacencyTest {

/*** @param args*/public static void main(String[] args){

// TODO Auto-generated method stube2dGameState gs = new e2dGameState();

Page 390: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

382 APPENDIX A. SOURCE CODE

e2dSet<e2dPiece> pieces = new e2dSet<e2dPiece>();

e2dPiece crossBlue = new e2dPiece();crossBlue.addShape(0, 0, 3, 1, new e2dProperty(Color.BLUE));crossBlue.addShape(1, 1, 1, 1, new e2dProperty(Color.BLUE));crossBlue.addShape(1, -1, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(crossBlue);

e2dPiece crossWhite = new e2dPiece();crossWhite.addShape(0, 0, 3, 1, new e2dProperty(Color.WHITE));crossWhite.addShape(1, 1, 1, 1, new e2dProperty(Color.WHITE));crossWhite.addShape(1, -1, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(crossWhite);

e2dPiece largeTBlue = new e2dPiece();largeTBlue.addShape(0, 0, 1, 3, new e2dProperty(Color.BLUE));largeTBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));largeTBlue.addShape(-1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(largeTBlue);

e2dPiece largeTWhite = new e2dPiece();largeTWhite.addShape(0, 0, 1, 3, new e2dProperty(Color.WHITE));largeTWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));largeTWhite.addShape(-1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(largeTWhite);

e2dPiece squareBlue = new e2dPiece();squareBlue.addShape(0, 0, 2, 2, new e2dProperty(Color.BLUE));

pieces.add(squareBlue);

e2dPiece squareWhite = new e2dPiece();squareWhite.addShape(0, 0, 2, 2, new e2dProperty(Color.WHITE));

pieces.add(squareWhite);

e2dPiece smallTBlue = new e2dPiece();smallTBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));smallTBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));smallTBlue.addShape(-1, 0, 1, 1, new e2dProperty(Color.BLUE));

Page 391: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 383

pieces.add(smallTBlue);

e2dPiece smallTWhite = new e2dPiece();smallTWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));smallTWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));smallTWhite.addShape(-1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(smallTWhite);

e2dPiece longbarBlue = new e2dPiece();longbarBlue.addShape(0, 0, 1, 5, new e2dProperty(Color.BLUE));

pieces.add(longbarBlue);

e2dPiece longbarWhite = new e2dPiece();longbarWhite.addShape(0, 0, 1, 5, new e2dProperty(Color.WHITE));

pieces.add(longbarWhite);

e2dPiece angleBlue = new e2dPiece();angleBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));angleBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(angleBlue);

e2dPiece angleWhite = new e2dPiece();angleWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));angleWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(angleWhite);

e2dPiece mediumbarBlue = new e2dPiece();mediumbarBlue.addShape(0, 0, 1, 3, new e2dProperty(Color.BLUE));

pieces.add(mediumbarBlue);

e2dPiece mediumbarWhite = new e2dPiece();mediumbarWhite.addShape(0, 0, 1, 3, new e2dProperty(Color.WHITE));

pieces.add(mediumbarWhite);

e2dPiece smallbarBlue = new e2dPiece();smallbarBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));

pieces.add(smallbarBlue);

Page 392: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

384 APPENDIX A. SOURCE CODE

e2dPiece smallbarWhite = new e2dPiece();smallbarWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));

pieces.add(smallbarWhite);

gs.getFlags().mayNotFlip();gs.getFlags().mayRotate();gs.getFlags().revealBag();

// gs.getBoard().setHeight(9);// gs.getBoard().setWidth(9);

for (e2dPiece p : pieces){

p.setFlags(gs.getFlags());}

e2dPlayer p1 = new e2dPlayer();p1.setName("p1");p1.addPieceToHand(crossBlue);p1.addPieceToHand(largeTBlue);p1.addPieceToHand(longbarBlue);p1.addPieceToHand(squareBlue);p1.addPieceToHand(smallTBlue);p1.addPieceToHand(angleBlue);p1.addPieceToHand(mediumbarBlue);p1.addPieceToHand(smallbarBlue);

gs.addPlayer(p1);

e2dPiece onBoardPiece = new e2dPiece(-4, -1, crossWhite);gs.getBoard().putPiece(onBoardPiece);gs.setCurrPlayer(p1);

GUIe2dInteractor interactor = new GUIe2dInteractor(gs);interactor.updateGameState(gs);

e2dPiece[] played = new e2dPiece[2];

while (true){

played = interactor.moveFromCurrHand(e2dInteractor.DEST_BOARD);gs.removePieceFromPlayer(played[1], gs.getCurrPlayer());gs.addPieceToBoard(played[0]);interactor.updateGameState(gs);

Page 393: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 385

// test adjacencyif (onBoardPiece.adjacent(played[0])){

interactor.print("Are adjacent");} else{

interactor.print("Are not adjacent");}

}

}

}

A.9.15 PieceSelectionPanelTest

package e2dTest;

import java.awt.Color; import java.awt.Dimension; importjava.awt.GridLayout;

import javax.swing.JFrame; import javax.swing.JScrollPane; importjavax.swing.ScrollPaneConstants;

import e2dCore.*; import e2dGUI.*;

public class PieceSelectionPanelTest {

/*** @param args* ignored*/public static void main(String[] args){

JFrame frame = new JFrame("Is name");

e2dSet<e2dPiece> pieces = new e2dSet<e2dPiece>();

e2dPiece crossBlue = new e2dPiece();crossBlue.addShape(0, 0, 3, 1, new e2dProperty(Color.BLUE));crossBlue.addShape(1, 1, 1, 1, new e2dProperty(Color.BLUE));crossBlue.addShape(1, -1, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(crossBlue);

Page 394: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

386 APPENDIX A. SOURCE CODE

e2dPiece crossWhite = new e2dPiece();crossWhite.addShape(0, 0, 3, 1, new e2dProperty(Color.WHITE));crossWhite.addShape(1, 1, 1, 1, new e2dProperty(Color.WHITE));crossWhite.addShape(1, -1, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(crossWhite);

e2dPiece largeTBlue = new e2dPiece();largeTBlue.addShape(0, 0, 1, 3, new e2dProperty(Color.BLUE));largeTBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));largeTBlue.addShape(-1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(largeTBlue);

e2dPiece largeTWhite = new e2dPiece();largeTWhite.addShape(0, 0, 1, 3, new e2dProperty(Color.WHITE));largeTWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));largeTWhite.addShape(-1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(largeTWhite);

e2dPiece squareBlue = new e2dPiece();squareBlue.addShape(0, 0, 2, 2, new e2dProperty(Color.BLUE));

pieces.add(squareBlue);

e2dPiece squareWhite = new e2dPiece();squareWhite.addShape(0, 0, 2, 2, new e2dProperty(Color.WHITE));

pieces.add(squareWhite);

e2dPiece smallTBlue = new e2dPiece();smallTBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));smallTBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));smallTBlue.addShape(-1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(smallTBlue);

e2dPiece smallTWhite = new e2dPiece();smallTWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));smallTWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));smallTWhite.addShape(-1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(smallTWhite);

e2dPiece longbarBlue = new e2dPiece();

Page 395: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 387

longbarBlue.addShape(0, 0, 1, 5, new e2dProperty(Color.BLUE));

pieces.add(longbarBlue);

e2dPiece longbarWhite = new e2dPiece();longbarWhite.addShape(0, 0, 1, 5, new e2dProperty(Color.WHITE));

pieces.add(longbarWhite);

e2dPiece angleBlue = new e2dPiece();angleBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));angleBlue.addShape(1, 0, 1, 1, new e2dProperty(Color.BLUE));

pieces.add(angleBlue);

e2dPiece angleWhite = new e2dPiece();angleWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));angleWhite.addShape(1, 0, 1, 1, new e2dProperty(Color.WHITE));

pieces.add(angleWhite);

e2dPiece mediumbarBlue = new e2dPiece();mediumbarBlue.addShape(0, 0, 1, 3, new e2dProperty(Color.BLUE));

pieces.add(mediumbarBlue);

e2dPiece mediumbarWhite = new e2dPiece();mediumbarWhite.addShape(0, 0, 1, 3, new e2dProperty(Color.WHITE));

pieces.add(mediumbarWhite);

e2dPiece smallbarBlue = new e2dPiece();smallbarBlue.addShape(0, 0, 1, 2, new e2dProperty(Color.BLUE));

pieces.add(smallbarBlue);

e2dPiece smallbarWhite = new e2dPiece();smallbarWhite.addShape(0, 0, 1, 2, new e2dProperty(Color.WHITE));

pieces.add(smallbarWhite);

frame.setLayout(new GridLayout(4, 1));for (int i = 0; i < 4; i++){

GUIe2dPieceSelectionPanel psp = new GUIe2dPieceSelectionPanel(pieces);

Page 396: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

388 APPENDIX A. SOURCE CODE

JScrollPane scroll = new JScrollPane(psp,ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

scroll.setPreferredSize(new Dimension(500, 140));

frame.add(scroll);}frame.pack();frame.setVisible(true);

}

}

A.9.16 PieceTest

/************************ Piece tests by Hugh Gordon***********************/

package e2dTest;

import e2dCore.*;

public class PieceTest {final static boolean DEBUG = true;

static int adjacent(e2dPiece a, e2dPiece b){

// Test adjacency both ways return 0 on not adjacent, 1 on adjacent, -1 on// error

boolean adj = false;

if (a.adjacent(b)){

if (DEBUG)System.out.println("Adjacent");

adj = true;} else{

if (DEBUG)System.out.println("Not Adjacent");

}

Page 397: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 389

if (b.adjacent(a) != adj){

if (DEBUG)System.out.println("Two way adjacency does NOT match");

return -1;}

if (adj)return 1;

return 0;}

static int overlaps(e2dPiece a, e2dPiece b){

// Test overlaps both ways, return 0 on not overlaps, 1 on overlaps, -1 on// error

boolean over = false;

if (a.overlaps(b)){

if (DEBUG)System.out.println("Overlaps");

over = true;} else if (DEBUG)

System.out.println("Not overlaps");

if (b.overlaps(a) != over){

if (DEBUG)System.out.println("Two way overlaps does NOT match");

return -1;}if (over)

return 1;return 0;

}

static int equals(e2dPiece a, e2dPiece b){

boolean equal = false;if (a.equals(b)){

if (DEBUG)System.out.println("Equals");

Page 398: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

390 APPENDIX A. SOURCE CODE

equal = true;} else if (DEBUG)

System.out.println("Not Equal");

if (b.equals(a) != equal){

if (DEBUG)System.out.println("Two way equals does NOT match");

return -1;}if (equal)

return 1;return 0;

}

/*** @param args*/public static void main(String[] args){

boolean fail = false;int temp = 0;e2dFlags flag = new e2dFlags();flag.mayFlip();flag.mayRotate();

// Start simple

System.out.println("Piece test starting.");// Default Constructorse2dPiece test1 = new e2dPiece();e2dPiece test2 = new e2dPiece();

test1.setFlags(flag);test2.setFlags(flag);// Add shapes (two blocks at the origin)test1.addShape(0, 0);test2.addShape(0, 0);

// Put it on the boardtest1.putOnBoard(0, 0);test2.putOnBoard(0, 1);

System.out.println("Level One tests starting.");

Page 399: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 391

System.out.println("");// Test for adjacencytemp = adjacent(test1, test2);if (temp == -1 || temp == 0){

System.out.println("\tAdjacency Failed");fail = true;

}

// Test for overlapstemp = overlaps(test1, test2);if (temp == -1 || temp == 1) // Shouldn’t overlap now{

System.out.println("\tOverlaps Failed");fail = true;

}

// Test for equalitytemp = equals(test1, test2);if (temp == -1 || temp == 0){

System.out.println("\tEquals Failed");fail = true;

}

// Lets move them so they overlaptest2.putOnBoard(0, 0);

// Test for overlapstemp = overlaps(test1, test2);if (temp == -1 || temp == 0){

System.out.println("\tOverlaps Failed");fail = true;

}

// Test for adjacency should be false!temp = adjacent(test1, test2);if (temp == -1 || temp == 1){

System.out.println("\tAdjacency Failed");fail = true;

}

System.out.println("Level One tests complete.\nStarting level 2");/*

Page 400: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

392 APPENDIX A. SOURCE CODE

* Start level two (not one by one squares anymore)*/

test1.addShape(0, 1);test2.addShape(1, 0);

test1.putOnBoard(0, 0);test2.putOnBoard(0, 1);

for (e2dShape s : test1.getShapes()){

for (e2dBasicShape b : s.getBasicShapes()){

System.out.println("test1: " + "(" + b.getBoardX() + ","+ b.getBoardY() + ")");

}}// Test for adjacencytemp = adjacent(test1, test2);if (temp == -1 || temp == 0){

System.out.println("\tAdjacency Failed");fail = true;

}

// Test for overlapstemp = overlaps(test1, test2);if (temp == -1 || temp == 1) // Shouldn’t overlap now{

System.out.println("\tOverlaps Failed");fail = true;

}

// Test for equalitytemp = equals(test1, test2);if (temp == -1 || temp == 0){

System.out.println("\tEquals Failed");fail = true;

}

test2.putOnBoard(0, 0); // Overlap them

// Test for adjacency should be true

e2dPiece t1 = new e2dPiece();e2dPiece t2 = new e2dPiece();

Page 401: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.9. E2DCORE AND E2DGUI TESTS 393

t1.setFlags(flag);t2.setFlags(flag);t1.addShape(0, 0);t2.addShape(0, 0);t1.addShape(0, 1);t2.addShape(1, 0);t1.putOnBoard(0, 0);// t2.putOnBoard(0,1);t2.putOnBoard(0, 0);temp = adjacent(t1, t2);// temp=adjacent(test1,test2);if (temp == -1 || temp == 0){

System.out.println("\tAdjacency Failed");fail = true;

}

// Test for overlapstemp = overlaps(test1, test2);if (temp == -1 || temp == 0){

System.out.println("\tOverlaps Failed");}

// Now change the flags and test againflag.mayNotRotate();

// Test for equality should be falsetemp = equals(test1, test2);if (temp == -1 || temp == 1){

System.out.println("\tEquals Failed");fail = true;

}

if (fail){

System.out.println("Piece Tests failed");System.exit(1); // We failed :(

}System.out.println("Piece tests sucsessfull");

}

}

Page 402: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

394 APPENDIX A. SOURCE CODE

A.9.17 RemoveFromSetTest

package e2dTest; import java.awt.Color;

import e2dCore.*; public class RemoveFromSetTest {

/*** @param args*/public static void main(String[] args){

e2dSet<e2dPiece> s = new e2dSet<e2dPiece>();e2dProperty blue = new e2dProperty(Color.BLUE);e2dProperty red = new e2dProperty(Color.RED);

e2dPiece crossBlue = new e2dPiece();crossBlue.addShape(0,0,3,1, blue);crossBlue.addShape(1,-1,1,1, blue);crossBlue.addShape(1,1,1,1, blue);

s.add(crossBlue);System.out.println("Added piece to set. s size: " + s.size());s.remove(crossBlue);System.out.println("Removed a piece from set. s size: " + s.size());

}

}

A.9.18 RemovePieceFromBagTest

package e2dTest;

import java.awt.Color;

import e2dCore.e2dGameState; import e2dCore.e2dPiece; importe2dCore.e2dProperty;

public class RemovePieceFromBagTest {

/*** @param args*/public static void main(String[] args){

Page 403: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.10. SEMANTIC ANALYZER TESTS 395

e2dGameState gs = new e2dGameState();

e2dPiece longbarWhite = new e2dPiece();longbarWhite.addShape(0, 0, 1, 5, new e2dProperty(Color.WHITE));

longbarWhite.putInBag();gs.addPieceToBag(longbarWhite);System.out.println(gs.getBag().size());

gs.removePieceFromBag(new e2dPiece(longbarWhite));System.out.println(gs.getBag().size());

}

}

A.10 Semantic Analyzer Tests

package e2dParser;

import java.io.*; import java.util.ArrayList;

/*** Test Controller for e2d Semantic Analyzer* @author Luqman Skye*/

public class e2dSATestsController {public static void main(String[] args){

e2dSATests st = new e2dSATests();st.runTests();

}}

/*** Tests for e2d Semantic Analyzer* @author Luqman Skye**/

class e2dSATests {/** Instantiation of Semantic Analyzer */

public e2dSemanticAnalyzer sa = new e2dSemanticAnalyzer(newe2dSymbolTable());

/**

Page 404: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

396 APPENDIX A. SOURCE CODE

* Runs the test suite*/public void runTests(){

try {calculateOffset_test();}catch (Exception e){System.out.println("CALCULATE_OFFSET: " + e.getMessage());}

try {alignment_aligncompat_test();}catch (Exception e){System.out.println("ALIGNMENT_ALIGNCOMPAT: " + e.getMessage());}

}

/*** Tests for {@link e2dParser.e2dSemanticAnalyzer#calculateOffset(String)}* @throws Exception*/private void calculateOffset_test() throws Exception{

ArrayList<Integer> l = new ArrayList<Integer>();sa.calculateOffset("u","_", l);sa.calculateOffset("l", "<", l);sa.calculateOffset("<","_",l);

}

/*** Tests for* {@link e2dParser.e2dSemanticAnalyzer#alignment_aligncompat(String,String)}* @throws Exception*/private void alignment_aligncompat_test() throws Exception{

sa.alignment_aligncompat("rd","<");sa.alignment_aligncompat("rdl","^");sa.alignment_aligncompat("rdl","<");sa.alignment_aligncompat("rdl","SUNSHINE");

}}

A.11 Main

/* Main.java* Authors: Luqman Skye, Nunzio Thron*/

Page 405: The e2d Programming Language for Two-Dimensional Spatial ...aviv/papers/e2d.pdf · The e2d Programming Language for Two-Dimensional Spatial Relationship Games The Five Tans Adam Aviv,

A.11. MAIN 397

import java.awt.event.WindowAdapter; importjava.awt.event.WindowEvent; import java.io.*; import antlr.*; importantlr.collections.*; import antlr.debug.misc.ASTFrame; importe2dParser.*;

public class Main {public static void main(String[] args) throws Exception{

String currFile = "hello";FileInputStream is = new FileInputStream(currFile+".e2d");FileWriter fw = new FileWriter("e2d_"+currFile+".java");e2dLexer lexer = new e2dLexer(is);e2dParser parser = new e2dParser(lexer);parser.e2dprog();AST t = parser.getAST();System.out.println(t.toStringTree());ASTFrame frame = new ASTFrame("The tree", t);frame.setVisible(true);frame.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

System.exit(0);}

});

e2dTreeWalker walker = new e2dTreeWalker();// Traverse the tree created by the parserString prog = walker.e2dprog(t, "e2d_"+currFile);fw.write(prog, 0, prog.length());fw.close();

}}