@slugbugblue/trax 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.eslintrc.yaml ADDED
@@ -0,0 +1,68 @@
1
+ root: true
2
+
3
+ extends:
4
+ - eslint:recommended
5
+
6
+ parserOptions:
7
+ sourceType: module
8
+
9
+ env:
10
+ node: true
11
+ es2021: true
12
+
13
+ globals:
14
+ crypto: readonly
15
+
16
+ rules:
17
+ curly:
18
+ - error
19
+ - multi-line
20
+ - consistent
21
+ dot-location:
22
+ - error
23
+ - property
24
+ dot-notation: warn
25
+ eqeqeq:
26
+ - warn
27
+ - smart
28
+ guard-for-in: warn
29
+ indent:
30
+ - warn
31
+ - 2
32
+ - MemberExpression: 0
33
+ SwitchCase: 1
34
+ linebreak-style:
35
+ - error
36
+ - unix
37
+ max-len:
38
+ - warn
39
+ - code: 119
40
+ tabWidth: 2
41
+ no-alert: error
42
+ no-caller: error
43
+ no-div-regex: warn
44
+ no-else-return:
45
+ - error
46
+ - allowElseIf: false
47
+ no-eval: error
48
+ no-extra-parens: warn
49
+ no-invalid-this: error
50
+ no-new: error
51
+ no-unused-vars:
52
+ - warn
53
+ - vars: all
54
+ args: all
55
+ caughtErrors: all
56
+ no-with: error
57
+ quotes:
58
+ - warn
59
+ - single
60
+ - avoidEscape: true
61
+ allowTemplateLiterals: true
62
+ semi:
63
+ - error
64
+ - never
65
+ - beforeStatementContinuationChars: always
66
+ wrap-iife:
67
+ - error
68
+ - inside
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2021 Chad Transtrum
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,119 @@
1
+ # Trax
2
+
3
+ Trax game-playing engine and etc.
4
+
5
+ ## Description
6
+
7
+ Trax is a two-player boardless board game invented by David Smith.
8
+ For more information about Trax,
9
+ including its rules and history,
10
+ see the official website at [traxgame.com][traxgame].
11
+
12
+ This goal of this javascript project
13
+ is to allow Trax to be played programmatically.
14
+ It can be used as an engine in a web browser
15
+ or in nodejs.
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ npm install @slugbugblue/trax
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ The main Trax engine is provided as `engine.js`,
26
+ which can be used as follows:
27
+
28
+ ```javascript
29
+ const Trax = require('@slugbugblue/trax')
30
+
31
+ let trax = new Trax()
32
+
33
+ trax.play('@0/')
34
+ ```
35
+
36
+ Explore the file `engine.js` for more information
37
+ until I get around to documenting the functionality.
38
+
39
+ ## Roadmap
40
+
41
+ * Documentation
42
+ * Test suite
43
+ * Command line interface
44
+ * Bot for solo games (?)
45
+ * Puzzles
46
+
47
+ ## Support
48
+
49
+ This project is built by [Chad Transtrum][ctrans]
50
+ for [slugbugblue.com][sbb].
51
+ Issues can be opened on the
52
+ [gitlab project page][repo].
53
+
54
+ ## Contributing
55
+
56
+ Contributions are welcome.
57
+ Ideally in the form of pull requests,
58
+ but feel free to open an issue with a bug report
59
+ or a suggestion as well.
60
+
61
+ ## Authors and acknowledgment
62
+
63
+ Many thanks to the late David Smith
64
+ for coming up with the idea of Trax
65
+ and for his generosity in allowing me to
66
+ add the game to [GoldToken.com][goldtoken].
67
+
68
+ Thanks to his widow Colleen Foley-Smith
69
+ for extending that generosity
70
+ to allow me to include Trax on [slugbugblue.com][sbb].
71
+
72
+ I would also like to extend a huge heartfelt appreciation
73
+ to the magnanimous [Donald G. Bailey][dgb],
74
+ who, through his excellent [book][traxbook],
75
+ taught me the basics (and more!) of Trax
76
+ and was always ready to share his insights
77
+ on the mechanics of the game,
78
+ various approaches to encoding its complexities,
79
+ and for his undeserved kindness
80
+ in indulging my many questions.
81
+
82
+ ## License
83
+
84
+ Copyright 2021 Chad Transtrum
85
+
86
+ Licensed under the Apache License, Version 2.0 (the "License");
87
+ you may not use the files in this project
88
+ except in compliance with the License.
89
+ You may obtain a copy of the License at
90
+
91
+ http://www.apache.org/licenses/LICENSE-2.0
92
+
93
+ Unless required by applicable law or agreed to in writing, software
94
+ distributed under the License is distributed on an "AS IS" BASIS,
95
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
96
+ See the License for the specific language governing permissions and
97
+ limitations under the License.
98
+
99
+ ## Trax rules copyright
100
+
101
+ In the United States, game mechanics may not be copyrighted,
102
+ however, the specific wording of game rules does fall under copyright law.
103
+
104
+ The official rules for Trax are found at http://traxgame.com/about_rules.php.
105
+
106
+ As Trax is a proprietary game,
107
+ these rules are the intellectual property
108
+ of David Smith and heirs,
109
+ and are not to be used without permission.
110
+
111
+
112
+
113
+ [ctrans]: mailto:chad@transtrum.net
114
+ [dgb]: mailto:donald@traxgame.com
115
+ [goldtoken]: https://goldtoken.com/
116
+ [repo]: https://gitlab.com/slugbugblue/trax
117
+ [sbb]: https://slugbugblue.com/
118
+ [traxbook]: http://traxgame.com/shop_book.php
119
+ [traxgame]: http://traxgame.com/
package/engine.js ADDED
@@ -0,0 +1,496 @@
1
+ /* Copyright 2021 Chad Transtrum
2
+ *
3
+ * Licensed under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License.
5
+ * You may obtain a copy of the License at
6
+ *
7
+ * http://www.apache.org/licenses/LICENSE-2.0
8
+ *
9
+ * Unless required by applicable law or agreed to in writing, software
10
+ * distributed under the License is distributed on an "AS IS" BASIS,
11
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ * See the License for the specific language governing permissions and
13
+ * limitations under the License.
14
+ */
15
+
16
+ // Trax internals. Woot.
17
+
18
+ // tile type names are determined by listing the color of line at each edge, clockwise
19
+ // and then sorted alphabetically and given a single letter name, so 'bbww' becomes 'a'
20
+ // which gives us six different tile names: a-f
21
+
22
+
23
+ // fun trax helper constants
24
+
25
+ const slash = { a: '\\', b: '+', c: '/', d: '/', e: '+', f: '\\' }
26
+
27
+ const symmetry = { // convert tile to different views
28
+ flip: { a: 'd', b: 'b', c: 'f', d: 'a', e: 'e', f: 'c' },
29
+ mirror: { a: 'c', b: 'b', c: 'a', d: 'f', e: 'e', f: 'd' },
30
+ swap: { a: 'f', b: 'e', c: 'd', d: 'c', e: 'b', f: 'a' },
31
+ counterclock: { a: 'c', b: 'e', c: 'f', d: 'a', e: 'b', f: 'd' },
32
+ }
33
+
34
+ const notation_regex = /^ *([@a-z]+) *(\d+) *([/\\+]) *$/i
35
+
36
+ const variants = ['trax', 'traxloop', 'trax8'] // known variants
37
+
38
+ // fun trax helper functions
39
+
40
+ // unexpected note: str.includes(t) is true if t is '' but false if t is undefined
41
+ const up_color = t => 'abc'.includes(t) ? 'b' : 'def'.includes(t) ? 'w' : false
42
+ const down_color = t => 'bdf'.includes(t) ? 'b' : 'ace'.includes(t) ? 'w' : false
43
+ const right_color = t => 'ade'.includes(t) ? 'b' : 'bcf'.includes(t) ? 'w' : false
44
+ const left_color = t => 'cef'.includes(t) ? 'b' : 'abd'.includes(t) ? 'w' : false
45
+ const squares_around = (x, y) => [{x:x-1,y},{x:x+1,y},{x,y:y-1},{x,y:y+1}]
46
+ const encode_col = col => { // for notation purposes: 0 -> @, 6 -> F, 28 -> AB
47
+ let n = ''
48
+ while (col > 0) {
49
+ n = String.fromCharCode(65 + (col - 1) % 26) + n
50
+ col = Math.floor((col - 1) / 26)
51
+ }
52
+ return n || '@'
53
+ }
54
+ const decode_col = col => { // turn letters back into numbers
55
+ col = col.toUpperCase()
56
+ let n = 0
57
+ while (col.length) {
58
+ n = n + (col.charCodeAt(0) - 64) * Math.pow(26, col.length - 1)
59
+ col = col.slice(1)
60
+ }
61
+ return n
62
+ }
63
+ const add_blank = code => { // encode missing tiles as digits 0-9, for 1-10 missing
64
+ let num = code.charCodeAt(code.length - 1) // this is NaN if code is empty, which is ok
65
+ if (num > 47 && num < 57) return code.slice(0, code.length -1) + String.fromCharCode(num + 1)
66
+ return code += '0'
67
+ }
68
+ // ugh, this is a dirty little function to get the length of an encoded position row
69
+ const code_row_len = row => row.replace(/[0-9]/g, n => '.'.repeat(Number(n)+1)).length
70
+
71
+ // this is where the magic happens
72
+ const Trax = class {
73
+ constructor (rules='trax', moves=[], id='trax') {
74
+ if (!variants.includes(rules)) rules = 'trax'
75
+ this.id = String(id)
76
+ this.rules = rules
77
+ this.move = 0
78
+ this.turn = 1
79
+ this.over = false
80
+ this.left = 1
81
+ this.right = 0
82
+ this.top = 1
83
+ this.bottom = 0
84
+ this.notation = ''
85
+ this.tiles = {}
86
+ this.path = []
87
+ this.count = 0
88
+ this.invalid = false
89
+ // moves might be a notation string
90
+ if (typeof moves === 'string') moves = moves.split(' ')
91
+ moves.forEach(move => {
92
+ if (typeof move === 'string') {
93
+ move = { move: this.move, notation: move }
94
+ }
95
+ this.play_move(move.move, move.notation)
96
+ })
97
+ }
98
+
99
+ save () { // in order to evaluate potential moves, we have to modify the state
100
+ return {
101
+ move: this.move,
102
+ turn: this.turn,
103
+ over: this.over,
104
+ left: this.left,
105
+ right: this.right,
106
+ top: this.top,
107
+ bottom: this.bottom,
108
+ notation: this.notation,
109
+ tiles: JSON.stringify(this.tiles),
110
+ path: JSON.stringify(this.path),
111
+ count: this.count,
112
+ invalid: this.invalid,
113
+ }
114
+ }
115
+
116
+ restore (saved) { // so we need to be able to restore it when we are done
117
+ this.move = saved.move
118
+ this.turn = saved.turn
119
+ this.over = saved.over
120
+ this.left = saved.left
121
+ this.right = saved.right
122
+ this.top = saved.top
123
+ this.bottom = saved.bottom
124
+ this.notation = saved.notation
125
+ this.tiles = JSON.parse(saved.tiles)
126
+ this.path = JSON.parse(saved.path)
127
+ this.count = saved.count
128
+ this.invalid = saved.invalid
129
+ }
130
+
131
+ get game_over () { // returns true if the game is over
132
+ return this.over
133
+ }
134
+
135
+ get winner () { // returns false if the game is still in progress
136
+ return this.over ? this.turn : false // or 1 or 2 for a win, or 0 for a tie
137
+ }
138
+
139
+ tile_id (x, y) {
140
+ return this.id + '-' + String(x) + 'x' + String(y)
141
+ }
142
+
143
+ add_tile (type, x, y) { // note: no validity checking is done here
144
+ const id = this.tile_id(x, y)
145
+ const tile = { type, x, y, id, move: this.move, seq: this.count }
146
+ if (type === 'x') {
147
+ this.invalid = true // invalid tile is being played
148
+ } else {
149
+ this.tiles[id] = tile
150
+ this.count++
151
+ this.left = Math.min(this.left, x)
152
+ this.right = Math.max(this.right, x)
153
+ this.top = Math.min(this.top, y)
154
+ this.bottom = Math.max(this.bottom, y)
155
+ }
156
+ return tile
157
+ }
158
+
159
+ tile_at (x, y) {
160
+ return (this.tiles[this.tile_id(x, y)] || {}).type
161
+ }
162
+
163
+ valid_tile (type, x, y) {
164
+ if (this.count === 0 && x === 0 && y === 0) return type === 'd' || type === 'e'
165
+ let up = down_color(this.tile_at(x, y - 1))
166
+ let down = up_color(this.tile_at(x, y + 1))
167
+ let left = right_color(this.tile_at(x - 1, y))
168
+ let right = left_color(this.tile_at(x + 1, y))
169
+ return (!up || up === up_color(type)) && (!down || down === down_color(type)) &&
170
+ (!left || left === left_color(type)) && (!right || right === right_color(type))
171
+ }
172
+
173
+ possible_tiles (x, y, s=false) { // s: slash (/ or \ or +)
174
+ let possibles = []
175
+ ;['a', 'b', 'c', 'd', 'e', 'f'].forEach(t => {
176
+ if ((!s || s === slash[t]) && this.valid_tile(t, x, y)) possibles.push(t)
177
+ })
178
+ return possibles
179
+ }
180
+
181
+ get height () {
182
+ return this.bottom - this.top + 1
183
+ }
184
+
185
+ get width () {
186
+ return this.right - this.left + 1
187
+ }
188
+
189
+ valid_location (x, y) {
190
+ if (this.over) return false
191
+ if (this.tile_at(x, y)) return false
192
+ if (this.count === 0 && x === 0 && y === 0) return true
193
+ if (this.rules === 'trax8') {
194
+ if (this.width > 7 && (x < this.left || x > this.right)) return false
195
+ if (this.height > 7 && (y < this.top || y > this.bottom)) return false
196
+ }
197
+ return this.tile_at(x-1, y) || this.tile_at(x+1, y) || this.tile_at(x, y-1) || this.tile_at(x, y+1)
198
+ }
199
+
200
+ possible_locations () {
201
+ let possibles = []
202
+ for (let x = this.left - 1 ; x <= this.right + 1 ; x++) {
203
+ for (let y = this.top -1 ; y <= this.bottom + 1 ; y ++) {
204
+ if (this.valid_location(x, y)) possibles.push({x, y})
205
+ }
206
+ }
207
+ return possibles
208
+ }
209
+
210
+ possible_moves () { // returns a list of every currently possible move
211
+ // as notations, ie ['@1+', '@1/', '@1\\', ...]
212
+ let possibles = []
213
+ if (this.over) return possibles // shortcut if the game is over
214
+ this.possible_locations().forEach(loc => {
215
+ this.possible_tiles(loc.x, loc.y).forEach(tile => {
216
+ let drop = this.drop_tile(tile, loc.x, loc.y, 'tentative')
217
+ if (drop.valid) possibles.push(drop.notation)
218
+ })
219
+ })
220
+ return possibles
221
+ }
222
+
223
+ forced_moves (x, y) { // we just played at x, y, so return all forced moves
224
+ let forced = []
225
+ let invalids = {}
226
+ let check = squares_around(x, y)
227
+ while (check.length) {
228
+ let pos = check.shift()
229
+ if (this.valid_location(pos.x, pos.y)) {
230
+ let possibles = this.possible_tiles(pos.x, pos.y)
231
+ if (possibles.length === 1) { // only 1 possible move
232
+ forced.push(this.add_tile(possibles[0], pos.x, pos.y))
233
+ check = check.concat(squares_around(pos.x, pos.y))
234
+ } else if (possibles.length === 0) { // no possible moves at all
235
+ let invalid = this.add_tile('x', pos.x, pos.y)
236
+ if (!invalids[invalid.id]) forced.push(invalid)
237
+ invalids[invalid.id] = true
238
+ }
239
+ }
240
+ }
241
+ return forced
242
+ }
243
+
244
+ notate (type, x, y) { // notation depends on the position of the board BEFORE the move
245
+ return encode_col(x - this.left + 1) + String(y - this.top + 1) + slash[type]
246
+ }
247
+
248
+ decode_notation (notation) { // return {type, x, y} from a notation
249
+ let r = { type: 'x', x: 0, y: 0 } // default to an invalid move
250
+ let match = notation.match(notation_regex)
251
+ if (match === null) return r
252
+ r.x = this.left - 1 + decode_col(match[1])
253
+ r.y = this.top - 1 + Number(match[2])
254
+ let possible = this.possible_tiles(r.x, r.y, match[3])
255
+ if (possible) r.type = possible[0]
256
+ return r
257
+ }
258
+
259
+ follow (color, x, y, from) {
260
+ let path = []
261
+ let id = this.tile_id(x, y)
262
+ let tile = this.tile_at(x, y)
263
+ while (tile && path[0] !== id) {
264
+ if (from !== 'top' && up_color(tile) === color) {
265
+ from = 'bottom'
266
+ y--
267
+ } else if (from !== 'bottom' && down_color(tile) === color) {
268
+ from = 'top'
269
+ y++
270
+ } else if (from !== 'left' && left_color(tile) === color) {
271
+ from = 'right'
272
+ x--
273
+ } else if (from !== 'right' && right_color(tile) === color) {
274
+ from = 'left'
275
+ x++
276
+ }
277
+ path.push(id)
278
+ id = this.tile_id(x, y)
279
+ tile = this.tile_at(x, y)
280
+ }
281
+ return { x, y, path }
282
+ }
283
+
284
+ find_ends (color, x, y) {
285
+ let ends = []
286
+ let tile = this.tile_at(x, y)
287
+ if (up_color(tile) === color) ends.push(this.follow(color, x, y, 'top'))
288
+ if (down_color(tile) === color) ends.push(this.follow(color, x, y, 'bottom'))
289
+ if (left_color(tile) === color) ends.push(this.follow(color, x, y, 'left'))
290
+ if (right_color(tile) === color) ends.push(this.follow(color, x, y, 'right'))
291
+ return ends
292
+ }
293
+
294
+ check_win (tiles) {
295
+ let winner = false
296
+ let colors = this.turn === 1 ? ['w', 'b'] : ['b', 'w'] // check win for current player first
297
+ colors.forEach(color => {
298
+ if (winner) return // skip the second player if the first has won
299
+ tiles.forEach(tile => {
300
+ if (winner) return // skip the remaining tiles once we find a win
301
+ let ends = this.find_ends(color, tile.x, tile.y)
302
+ if (ends.length !== 2) return // this should never happen, but if it does, don't die
303
+ if (ends[0].x === ends[1].x && ends[0].y === ends[1].y) {
304
+ winner = color // loop win
305
+ this.path = ends[0].path // both paths are essentially the same
306
+ } else if (this.rules !== 'traxloop') { // check for line win
307
+ if (this.width > 7 && Math.abs(ends[0].x - ends[1].x) > this.width ||
308
+ this.height > 7 && Math.abs(ends[0].y - ends[1].y) > this.height) {
309
+ winner = color // line win, paths need to be combined
310
+ this.path = ends[0].path.reverse().concat(ends[1].path.slice(1))
311
+ }
312
+ }
313
+ })
314
+ })
315
+ if (winner) {
316
+ this.over = true
317
+ this.turn = winner === 'w' ? 1 : 2
318
+ } else {
319
+ // 8x8 Trax can end in a tie once there are no valid moves left
320
+ if (this.rules === 'trax8' && this.possible_moves().length < 1) {
321
+ this.over = true
322
+ this.turn = 0 // tie
323
+ }
324
+ }
325
+ }
326
+
327
+ play (notation) { // fast and easy way to play a move
328
+ return this.drop_tile(notation)
329
+ }
330
+
331
+ play_move (move_num, notation) { // generic API call for drop_tile
332
+ if (move_num === this.move) return this.drop_tile(notation)
333
+ return { valid: false }
334
+ }
335
+
336
+ update_notation (notation) {
337
+ this.move++
338
+ let note = this.move +'. ' + notation
339
+ let line = this.notation.split('\n').pop()
340
+ if (line) {
341
+ note = (line.length + note.length > 79 ? '\n' : ' ') + note
342
+ }
343
+ this.notation += note
344
+ }
345
+
346
+ get moves () {
347
+ return this.notation.replace(/\n/g, ' ').split(' ').filter(n => !n.endsWith('.'))
348
+ }
349
+
350
+ drop_tile (type, x, y, tentative=false) { // pass in tentative to not save the move
351
+ let dropped = []
352
+ let notation = ''
353
+ let valid = false
354
+ if (['timeout', 'resign', 'draw', 'puzzled'].includes(type)) { // handle special events
355
+ this.over = true
356
+ if (type !== 'puzzled') { // puzzled: puzzle was not completed; this player wins
357
+ this.turn = this.turn === 1 ? 2 : 1 // timeout, resign means the other player wins
358
+ if (type === 'draw') this.turn = 0 // draw means we both win
359
+ }
360
+ this.update_notation(type)
361
+ notation = type
362
+ valid = true
363
+ } else {
364
+ if (type.search(notation_regex) === 0) { // we were passed a notation
365
+ ({ type, x, y } = this.decode_notation(type))
366
+ }
367
+ if (this.valid_location(x, y) && this.valid_tile(type, x, y)) {
368
+ valid = true
369
+ let saved = this.save() // just in case we need to roll back
370
+ notation = this.notate(type, x, y) // determine notation BEFORE we play the move
371
+ this.update_notation(notation)
372
+ dropped.push(this.add_tile(type, x, y)) // play the tile
373
+ dropped = dropped.concat(this.forced_moves(x, y)) // play all forced moves
374
+ if (!tentative) this.check_win(dropped, tentative)
375
+ if (this.invalid || tentative) {
376
+ valid = false
377
+ this.restore(saved) // abort! abort!
378
+ } else if (!this.over) {
379
+ this.turn = this.turn === 1 ? 2 : 1
380
+ }
381
+ }
382
+ }
383
+ return { dropped, notation, valid }
384
+ }
385
+
386
+ rotate_move (move) { // symmetry helper, rotate a move around the board
387
+ let match = move.match(notation_regex)
388
+ if (match === null) return move
389
+ let x = this.width + 1 - Number(match[2])
390
+ let y = decode_col(match[1])
391
+ let s = { '/': '\\', '\\': '/', '+': '+'}[match[3]]
392
+ return encode_col(x) + String(y) + s
393
+ }
394
+
395
+ provisional_notation (provisional) { // test a provisional move against the current state
396
+ let prov = provisional.split(';') // return false if the provisional move does not match
397
+ if (prov.length !== 4) return 'delete-provisional' // <-- if the provisional move is bad
398
+ let notation = false // otherwise, return the notation required to make the move
399
+ let rows = prov[1].split(':')
400
+ let cols = rows.reduce((acc, cur) => Math.max(acc, code_row_len(cur)), 0)
401
+ rows = rows.length
402
+ if (this.width > rows && this.height > cols || this.width > cols && this.height > rows) {
403
+ return 'delete-provisional' // current board is bigger than the provisional move
404
+ }
405
+ if (prov[1] === this.normalized) {
406
+ let move = prov[2]
407
+ let saved = this.save() // save this position
408
+ for (let i = 0 ; i < 4 && !notation; i++) { // try all four orientations because symmetry
409
+ this.drop_tile(move)
410
+ if (prov[3] === this.normalized) notation = move // this move matched!
411
+ this.restore(saved) // put the board back how it was
412
+ move = this.rotate_move(move) // rotate to the next orientation
413
+ }
414
+ }
415
+ return notation
416
+ }
417
+
418
+ get icon () {
419
+ return this.position_code()
420
+ }
421
+
422
+ // symmetry helper
423
+ position_code (right_to_left, bottom_to_top, rotate, swap_colors) {
424
+ const start_x = right_to_left ? this.right : this.left
425
+ const start_y = bottom_to_top ? this.bottom : this.top
426
+ const inc_x = right_to_left ? -1 : 1
427
+ const inc_y = bottom_to_top ? -1 : 1
428
+ let code = []
429
+ let line = ''
430
+ let x = start_x
431
+ let y = start_y
432
+ do {
433
+ let tile = this.tile_at(x, y) // normal tile for normal orientation
434
+ if (tile) {
435
+ if (right_to_left) tile = symmetry.mirror[tile]
436
+ if (bottom_to_top) tile = symmetry.flip[tile]
437
+ if (rotate) tile = symmetry.counterclock[tile]
438
+ if (swap_colors) tile = symmetry.swap[tile]
439
+ if (this.path.includes(this.tile_id(x, y))) {
440
+ tile = String.fromCharCode(tile.charCodeAt(0) + this.turn * 6)
441
+ }
442
+ line += tile
443
+ } else {
444
+ line = add_blank(line)
445
+ }
446
+ if (rotate) { // increment y more often than x
447
+ y += inc_y
448
+ if (y < this.top || y > this.bottom) {
449
+ y = start_y
450
+ x += inc_x
451
+ // remove final number and add to code
452
+ code.push(line.replace(/[0-9]+$/, ''))
453
+ line = ''
454
+ }
455
+ } else { // this is the standard order
456
+ x += inc_x
457
+ if (x < this.left || x > this.right) {
458
+ x = start_x
459
+ y += inc_y
460
+ // remove final number and add to code
461
+ code.push(line.replace(/[0-9]+$/, ''))
462
+ line = ''
463
+ }
464
+ }
465
+ } while (x >= this.left && x <= this.right && y >= this.top && y <= this.bottom)
466
+ if (rotate) code.reverse()
467
+ return code.join(':')
468
+ }
469
+
470
+ normalize (swap_colors=false) {
471
+ // trax has the potential for symmetry, so this gives us the ability to
472
+ // examine horizontal, vertical, and rotational symmetry for a color
473
+ // --- pass in a truthy value to get a position for the opposite color
474
+ let norm = 'z'
475
+ let bools = [true, false]
476
+ bools.forEach(r_to_l => {
477
+ bools.forEach(b_to_t => {
478
+ bools.forEach(rot => {
479
+ let code = this.position_code(r_to_l, b_to_t, rot, swap_colors)
480
+ if (code < norm) norm = code
481
+ })
482
+ })
483
+ })
484
+ return norm
485
+ }
486
+
487
+ get normalized () {
488
+ // the default call does not check for color symmetry, because you rarely need that
489
+ return this.normalize()
490
+ }
491
+ }
492
+
493
+ Trax.column = (col) => encode_col(col)
494
+ Trax.variants = variants
495
+
496
+ module.exports = Trax
package/jsconfig.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "compilerOptions": {
3
+ "module": "commonjs",
4
+ "target": "es2020"
5
+ },
6
+ "checkJs": true,
7
+ "exclude": ["node_modules"]
8
+ }
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@slugbugblue/trax",
3
+ "version": "0.1.0",
4
+ "description": "Trax game engine and friends",
5
+ "keywords": [
6
+ "trax",
7
+ "traxgame",
8
+ "engine"
9
+ ],
10
+ "homepage": "https://gitlab.com/slugbugblue/trax",
11
+ "bugs": "https://gitlab.com/slugbugblue/trax/issues",
12
+ "license": "Apache-2.0",
13
+ "author": "Chad Transtrum <chad@transtrum.net>",
14
+ "main": "engine.js",
15
+ "repository": "gitlab:slugbugblue/trax",
16
+ "scripts": {
17
+ "test": "tape tests.js"
18
+ },
19
+ "devDependencies": {
20
+ "eslint": "8.x",
21
+ "tape": "5.x",
22
+ "typescript": "^4.5.4",
23
+ "typescript-language-server": "^0.8.1"
24
+ },
25
+ "engines": {
26
+ "node": ">=16.0.0"
27
+ }
28
+ }
package/tty.js ADDED
@@ -0,0 +1,176 @@
1
+ /* Copyright 2021 Chad Transtrum
2
+ *
3
+ * Licensed under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License.
5
+ * You may obtain a copy of the License at
6
+ *
7
+ * http://www.apache.org/licenses/LICENSE-2.0
8
+ *
9
+ * Unless required by applicable law or agreed to in writing, software
10
+ * distributed under the License is distributed on an "AS IS" BASIS,
11
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ * See the License for the specific language governing permissions and
13
+ * limitations under the License.
14
+ */
15
+
16
+ // Console functions for Trax
17
+
18
+ /* eslint-disable no-console */
19
+
20
+ const Trax = require('./engine')
21
+
22
+ // fix Javascript's broken typeof
23
+ const TypeOf = o => ({}).toString.call(o).slice(8,-1)
24
+
25
+ const esc = '\x1b[' // start of console color escape code
26
+ const off = esc + 'm'
27
+
28
+ // display a message with optional color
29
+ const out = (message, fgcolor, bgcolor) => {
30
+ let ansi = fgcolor || bgcolor ? esc : ''
31
+ if (fgcolor) ansi += '38;5;' + fgcolor
32
+ if (bgcolor) ansi += '48;5;' + bgcolor
33
+ if (ansi) ansi += 'm'
34
+ console.log(ansi + message + off)
35
+ }
36
+
37
+
38
+ // a little magic to display the game in progress
39
+ const color_sets = { // Colors for terminal sequence: <Esc>[38;5;<color_num>m
40
+ trax: { b: 238, B: 57, e: 19, t: 74, w: 255, W: 184 },
41
+ trax8: { b: 236, B: 21, e: 58, t: 137, w: 254, W: 117 },
42
+ traxloop: { b: 235, B: 20, e: 17, t: 61, w: 253, W: 222 },
43
+ }
44
+
45
+ // return the ANSI codes to display a 3x1.5 block tile, one line at a time
46
+ const tile_tty = (set, tile, top) => { // top: true for first line, false for second
47
+ const ln = 'm\u2584' // lower half block -- with the leading m to terminate a terminal color escape sequence
48
+ const up = 'm\u2588' // full block
49
+ const lt = 'm\u2599' // lower half and left half block
50
+ const rt = 'm\u259f' // lower half and right half block
51
+ const fg = n => '38;5;' + String(set[n]) // foreground color_num
52
+ const bg = n => '48;5;' + String(set[n]) // background color_num
53
+ const sp = esc + bg('e') + 'm ' // lower space
54
+ // tiles are displayed on two lines; the top half of the first line is empty
55
+ // and the second half is composed of three characters, up color surrounded by tile color
56
+ const uptty = clr => esc + fg('t') + ';' + bg('e') + ln + esc + fg(clr) + ln + esc + fg('t') + ln + ' '
57
+ // the top half of the second line has both horizontal lines with a center transition
58
+ // while the bottom half is the tile background color surrounding the down color
59
+ const horiztty = clr => esc + fg('t') + ';' + bg(clr) + ln
60
+ const dntty = (clr, oppclr, char) => esc + fg(clr) + (char === up ? '' : ';' + bg(oppclr)) + char
61
+ // list of icon_char => tile line colors for easy reference in order up, right, down, left
62
+ const tiles = { a: 'bbww', b: 'bwbw', c: 'bwwb', d: 'wbbw', e: 'wbwb', f: 'wwbb' }
63
+ // quick access to tile color and its opposite in upper case
64
+ const colors = { b: 'b', w: 'w', B: 'w', W: 'b' }
65
+ if (!(tile in tiles)) { // winning paths are represented by adding 6 to the tile char code
66
+ tile = String.fromCharCode(tile.charCodeAt(0) - 6)
67
+ if (tile in tiles) {
68
+ colors.w = 'W'
69
+ colors.B = 'W'
70
+ } else { // and another six for a black win
71
+ tile = String.fromCharCode(tile.charCodeAt(0) - 6)
72
+ colors.b = 'B'
73
+ colors.W = 'B'
74
+ }
75
+ }
76
+ if (tile in tiles) {
77
+ tile = tiles[tile]
78
+ if (top) return uptty(colors[tile[0]])
79
+ let center_char = tile[1] === tile[2] ? rt : tile[2] === tile[3] ? lt : up
80
+ let centertty = dntty(colors[tile[2]], colors[tile[2].toUpperCase()], center_char)
81
+ return horiztty(colors[tile[3]]) + centertty + horiztty(colors[tile[1]]) + sp
82
+ }
83
+ if (top) return '??? '
84
+ return '\'\'\' '
85
+ }
86
+
87
+ const print_icon = (icon, set_name) => {
88
+ let set = color_sets[set_name] || color_sets.trax
89
+ const on = esc + '38;5;' + String(set.t) + ';48;5;' + String(set.e) + 'm'
90
+ let o1 = ' '
91
+ let o2 = '1 '
92
+ let row = 1
93
+ let width = 1
94
+ let info = []
95
+ let line_width = 0
96
+ while (icon.length) {
97
+ let c = icon[0]
98
+ icon = icon.slice(1)
99
+ if (c === ':') {
100
+ info.push({o: o1, w: line_width})
101
+ info.push({o: o2, w: line_width})
102
+ row++
103
+ width = Math.max(width, line_width)
104
+ line_width = 0
105
+ o1 = ' '
106
+ o2 = String(row).padEnd(3)
107
+ } else if (c >= '0' && c <= '9') {
108
+ let empty = Number(c) + 1
109
+ o1 += ' '.repeat(empty * 4)
110
+ o2 += ' '.repeat(empty * 4)
111
+ line_width += empty
112
+ } else {
113
+ o1 += tile_tty(set, c, 'top')
114
+ o2 += tile_tty(set, c)
115
+ line_width++
116
+ }
117
+ }
118
+ if (o1.length) {
119
+ info.push({o: o1, w: line_width})
120
+ info.push({o: o2, w: line_width})
121
+ width = Math.max(width, line_width)
122
+ }
123
+ let columns = process.stdout.columns || 0
124
+ let rows = process.stdout.rows || 0
125
+ if (width * 4 < columns - 4 && info.length < rows - 2) {
126
+ let col_out = ' '
127
+ for (let col = 1; col <= width; col++) {
128
+ col_out += ' ' + Trax.column(col).padEnd(3)
129
+ }
130
+ console.info(on + col_out.padEnd((width + 1) * 4) + off)
131
+ info.forEach(line => console.info(on + line.o + ''.padEnd((width - line.w) * 4) + ' ' + off))
132
+ console.info(on + ''.padEnd((width + 1) * 4) + off)
133
+ } else {
134
+ console.warn('Console is too small to display this game')
135
+ }
136
+ }
137
+
138
+ // flexible way to get a Trax game object
139
+ // game = existing Trax instance, or a string indicating the variant name
140
+ // moves = optional list or string of moves to be made on the game
141
+ // returns a Trax instance
142
+ const trax_game = (game='trax', moves) => {
143
+ let trax
144
+ if (game instanceof Trax) {
145
+ trax = game
146
+ if (moves) {
147
+ if (TypeOf(moves) === 'String') moves = moves.split(' ')
148
+ moves.forEach(move => trax.drop_tile(move))
149
+ }
150
+ } else {
151
+ trax = new Trax(game, moves, 'cli')
152
+ }
153
+ return trax
154
+ }
155
+
156
+ const display_game = (game='trax', moves='') => {
157
+ let trax = trax_game(game, moves)
158
+ console.info(trax.notation)
159
+ print_icon(trax.icon, trax.rules)
160
+ let name = {0: 'nobody', 1: 'white', 2: 'black'}[trax.turn]
161
+ if (trax.over) {
162
+ if (trax.turn) {
163
+ console.info(name + ' wins')
164
+ } else {
165
+ console.info('game ended in a draw')
166
+ }
167
+ } else if (trax.turn) {
168
+ console.info(name +' to play')
169
+ }
170
+ }
171
+
172
+ module.exports = {
173
+ display: display_game,
174
+ game: trax_game,
175
+ out,
176
+ }