Debian Codegraph @

texmf-dist/source/generic/reverxii/reverxii.dtx

raw
1 {\def\x{plain}\expandafter}\ifx\fmtname\x
2 \errmessage{Use LaTeX for the documentation reverxii.dtx. Play with reverxii.tex}
3 \fi
4 \documentclass{article}
5 \usepackage{shortvrb,verbatim}
6 \MakeShortVerb|
7 \title{\texttt{reverxii}\\
8 Playing Reversi in \TeX{}}
9 \author{Bruno Le Floch}
10 \date{November 6, 2021}
11 \newcommand{\cs}[1]{\texttt{\char`\\ #1}}
12 \newcommand{\meta}[1]{$\langle \mathit{#1}\rangle$}
13 \newcommand{\enquote}[1]{``#1''}
14 \begin{document}
15 \maketitle
16
17 \begin{abstract}
18 \texttt{reverxii.tex} is a $983$ character long \TeX{} program which
19 lets you play Reversi against your favorite typestting engine. To
20 play, run plain \TeX{} or \LaTeX{} (either the dvi or the pdf
21 engines), on the command line, on the file \texttt{reverxii.tex}. In
22 most distributions, this can mean running \texttt{tex reverxii.tex} in
23 a terminal. To typeset the documentation, run \LaTeX{} on
24 \texttt{reverxii.dtx}, with any engine (\emph{e.g.}, \texttt{pdflatex
25 reverxii.dtx}).
26 \end{abstract}
27
28 \section{The code}
29
30 Line breaks can be removed, and the stripped down code takes $983$
31 characters.
32 {\small \verbatiminput{reverxii.tex}}
33 In fact, the first line and |\ifx\>\:1\fi| are only used to support
34 \LaTeX{} and can be removed for plain \TeX{}. This reduces the code down to $938$ characters.
35
36 To play a two-player game, change |1=P| to |0=P| near the end:
37 this changes the computer player from $0$ to $1$, hence disabling it.
38
39 \section{Explanation}
40
41 \subsection{Some comments}
42
43 The name \texttt{reverxii.tex} is of course a reference to the infamous
44 \texttt{xii.tex}, also on CTAN, which typesets the lyrics of the
45 \textit{Twelve days of Christmas} using code that very few can understand.
46 In my case, I aimed for the shortest possible code, rather than the
47 most obfuscated. In particular, I did not assign weird catcodes
48 other than making most characters active.
49
50 Since I was aiming for short code, the text presented to the player
51 is concise, but hopefully enough to leave the game understandable
52 and usable. Despite aiming for short code, I thought it would be
53 neat to typeset a record of the game as it goes: after all, \TeX{}
54 is a typesetting program. This used up around $38$ characters, putting
55 me above the $900$ character line.
56
57 One technique used to make the code shorter is to rename any primitive
58 used more than once into a single active character. Also, counters
59 holding the information about the board are accessed directly by number.
60
61 A careful reader would notice that changing one of the remaining
62 one-character control sequences to active characters (|$| is still %$
63 unused) would gain one character. I didn't do it, because it messes
64 up the code-highlighting of my editor |:)|. Of course, I chose the
65 control sequences which are not active characters to be those appearing
66 the least, only twice each.
67
68 \subsubsection{On with the code!}
69
70 In \LaTeXe{}, detected by comparing the spaces |\>| and~|\:| (only one
71 of them is defined in plain \TeX{}), load a document class.
72 \begin{verbatim}
73 \ifx\>\:\documentclass{report}\fi
74 \end{verbatim}
75 We do not need \cs{begin}|{document}| because the text is eventually
76 typeset inside an \cs{halign} table, which means \cs{everypar} (and its
77 usual error) is never called.
78
79 First set up the page dimensions. This would not be enough for pdf output.
80 \begin{verbatim}
81 \vsize5cm
82 \hsize3cm
83 \end{verbatim}
84
85 Since plain \TeX{} does not provide the \cs{typeout} command, we are
86 using \cs{message}, hence need to setup a new line character. It is
87 arbitrarily chosen to be |*|, which will be made active and \cs{let}
88 to \cs{cr}.
89 \begin{verbatim}
90 \newlinechar`*
91 \end{verbatim}
92
93 Then a first loop to make many characters active. The loop ends when
94 reaching the trailing brace group: there we make spaces active, then
95 redefine |~| for the next loop. We still have an annoying |13~| in the
96 input stream. Introduce a short-hand for count registers whose number
97 starts with |1| (or in fact |11| in \LaTeX{} given the test
98 |\ifx\>\:1\fi|, see later for why we do this). Then remove |13| by
99 setting |\count11| to |213| (this counter is used for allocation later
100 on). The next loop is triggered by the |~| which we left.
101 \begin{verbatim}
102 \def~#1{\catcode`#113~}
103 ~IJKLMNOPQRSTUVWXYZjqz@.[|](/+^'";:?,_)!*
104 { 13\def~#1#2{\let#1#2~}\def+{\count\ifx\>\:1\fi1}+1=2}
105 \end{verbatim}
106
107 At this stage, |~| is defined to take two arguments, \cs{let} the
108 first to the second, and repeat. As announced |*| becomes \cs{cr},
109 so that it will be a new line both in messages and in alignments.
110 We try to keep a relatively consistent naming scheme: opening
111 conditionals are left delimiters, \cs{or} and \cs{else} are
112 middle delimiters, and \cs{fi} is a right bracket. Other primitives
113 which are used a lot are also given short names. The loop ends by
114 redefining |~| to \cs{def}.
115 \begin{verbatim}
116 *\cr
117 [\ifnum
118 (\ifcase
119 |\or
120 /\else
121 ]\fi
122 N\number
123 @\advance
124 X\expandafter
125 !\global
126 ?\message
127 ~\def
128 \end{verbatim}
129
130 It is time to allocate counters. Unfortunately, \cs{newcount} is
131 \cs{outer} in plain \TeX{}, so it is unpractical to use. We have
132 defined |+| to be |\count1| in plain and |\count11| in \LaTeX{}. This
133 will eventually let us access a table of $8\times 8$ counters |+11| to
134 |+88|, which are thus |\count111| to |\count188| in plain, and
135 |\count1111| to |\count1188| in \LaTeX{}. This is needed because plain
136 \TeX{} without e\TeX{} extensions only has $256$ counters, while
137 \LaTeX{} \emph{uses} some of these counters already so we must use the
138 higher counters provided by the e\TeX{} extensions, always available in
139 \LaTeX{}. The following text explains the plain \TeX{} case; in the
140 other case just replace |\count1| by |\count11|.
141
142 We have set |+1|,
143 \emph{aka.} |\count11| to $213$, and will allocate counters
144 starting from that number upwards. Repeatedly advance |+1|
145 by $1$ and define the next character to be the counter number |+1|,
146 then repeat. As always, the loop is interrupted by making it
147 redefine the looping macro |.| to be a counter. We use the trailing
148 dot to assign it the value $-1$, then assign a couple of counters:
149 starting player, other player, and the initial position:
150 the squares in rows and columns $4$ and $5$ are initially
151 filled in a cross pattern.
152 \begin{verbatim}
153 .#1{@+1 1\countdef#1+1.}.IJKLPQRSTUVWYZ.-1P1T2+44P+55P+45T+54T
154 \end{verbatim}
155 Let us summarize which counters are used where:
156 \begin{itemize}
157 \item [P] is the current player ($1$ for |-| or $2$ for |0|);
158 \item [T] is the other player;
159 \item [Q] is the row number;
160 \item [J] is the column number;
161 \item [S] is the step size in the row direction;
162 \item [K] is the step size in the column direction;
163 \item [R] is the score difference, positive when $0$ is winning;
164 \item [V] is used when computing the value of placing a piece at
165 the position (|Q|,|J|);
166 \item [W] is the value of the best possible move according to the AI,
167 also used to end the game if neither player can move;
168 \item [U] is the row number of the best move;
169 \item [L] is the column number of the best move;
170 \item [Y] is a boolean, true ($0$) most of the time,
171 it has to do with when we flip or not, but I don't
172 understand it now, help welcome;
173 \item [Z] is a temporary counter, used locally to compute
174 how much a given cell matters (\emph{i.e.} corners are important),
175 and used globally as a boolean to indicate whether to flip pieces
176 or not.
177 \end{itemize}
178
179 The board is stored in counters |1|\meta{row}\meta{column}.
180 An empty square is has the value $0$, a square for player |-|
181 has value $1$, and player |0| corresponds to the value $2$.
182 The macro |j| retrieves that value, assuming that the row and
183 column numbers are stored as |Q| and |J|, and returns |.|,
184 that is, $-1$, if outside the board. Recall that |[| is \cs{ifnum},
185 |/| is \cs{else}, and |]| is \cs{fi}. When |Q| and |J| are
186 within bounds, the value is retrieved by |^| as
187 |\count1|\meta{row}\meta{column}. Note that |j| and |^| are
188 only safe to use on the left-hand side of an \cs{ifnum} test
189 (because of expansion issues), and that |^| can be used
190 on the left-hand side of an assignment.
191 \begin{verbatim}
192 ~j{[0<Q[9>Q[0<J[9>J^/.]/.]/.]/.]}
193 ~^{+NQNJ}
194 \end{verbatim}
195
196 We often need to loop over numbers from $1$ to $8$; here is a macro.
197 \begin{verbatim}
198 ~:#1{#11#12#13#14#15#16#17#18}
199 \end{verbatim}
200
201 The macros to print the board, both to the dvi and to the console.
202 |M| spews its argument as a \cs{message} (|?|), and directly typeset.
203 This is used rather directly to print the first and last lines (|'|),
204 which are simply alignment cells containing each number from $1$ to $8$,
205 with some care given to spaces and new lines.
206 The |_| macro receives a digit and the corresponding capital letter
207 as arguments, and outputs that row of the board. First place the
208 letter on the left of the board, then loop from $1$ to $8$,
209 typesetting and \cs{message}ing a space, |-| or |0|, depending on
210 the value of the relevant count register. Note the two spaces
211 in the definition: the first ends the counter's number, the second
212 is typeset (in plain \TeX{}, active spaces expand to a normal space).
213 \begin{verbatim}
214 ~M#1{?{#1}#1}
215 ~'{M :{&M}&M{*}}
216 ~_#1#2{M#2:{\B#1}&M#2&M{*}}
217 ~\B#1#2{&M{(+#1#2 |-|0]}}
218 \end{verbatim}
219
220 The input is done by |q|, which queries the user until they give
221 a correct input, so that |Q| and |J| are in the range $[1,8]$.
222 Prompt the user with a small \cs{message}, giving an example
223 of what move he could do (only true at the start, but the hope
224 is that the player will understand what the input format is).
225 The code that follows is similar to \LaTeXe{}'s \cs{@onelevel@sanitize}.
226 We extract the two first characters from the the \cs{meaning}
227 of the user's input (remember, |X| is \cs{expandafter}),
228 as |#2| and |#3| of \cs{D}. Grab the character code of each,
229 relative to the characters |@| (row) or |0| (column).
230 The closing parenthesis is where most of the work is done.
231 It sets |V| to the value of placing a piece in the cell
232 $(|Q|,|J|)$, zero if the move does not flip any of the opponent's
233 pieces, or if the cell is outside the board. After performing
234 that calculation, if |V| is zero, the move was not valid,
235 and we query the user again.
236 \begin{verbatim}
237 ~q{?{Row and column? e.g. E6*}\read.to\EX\D\meaning\E ;}
238 ~\D#1->#2#3#4;{Q`#2@Q-`@J`#3@J-`0)(V?{Invalid move #2#3.}q]}
239 \end{verbatim}
240
241 So\ldots{} how do we compute the \enquote{value} of a move?
242 It is automatically invalid if |j| does not return $0$:
243 either the cell is occupied, or it is outside the board.
244 Then for each of the $8$ directions around the cell,
245 we count the number of pieces that are flipped in that
246 direction. The direction is stored as two counters,
247 |S| and |K|, each $\pm 1$ or $0$. We call |,| a first
248 time to test whether flipping should happen in that direction,
249 and, if it is (as indicated by the global value of |Z|),
250 call it again to actually flip. The call to |,| must happen
251 within a group, because it directly changes the row and column
252 numbers |Q| and |J|, following which cell is being queried.
253 \begin{verbatim}
254 ~){V0 (jS1z1z0z.S0z1z.S.z1z0z.]}
255 ~z#1{{K#1Z1{Y1,}(Z,]}}
256 \end{verbatim}
257
258 The macro |,| is recursive. At each step, move $(|Q|,|J|)$
259 in the direction $(|S|,|K|)$. Then, if that cell (|j|)
260 contains a piece belonging to the other player (|T|),
261 do some stuff |(Y!^P!;2]O| and repeat. What is it that
262 we do? Well, if the condition |Y| is met (I don't remember
263 how that works), we set the current cell to belong to the
264 player, globally, and change the score difference by $2$
265 (see |;|), also globally. Then, we compute with |O| the value
266 corresponding to the cell that we might be flipping (see |O|).
267
268 Otherwise (|/|), if the cell (|j|) contains a piece from the
269 current player (|P|), it means we have reached the end of a
270 run of the form \meta{initial cell} \meta{opponent's pieces}
271 \meta{own piece}, hence the \meta{opponent's pieces} should
272 count as flipped if we place our piece in the \meta{initial
273 cell}. Until there, all changes to |V| were local, returning
274 to the old value at the end of the group that |,| is contained
275 in. Since the run in that direction was successful, we escape
276 the value of |V| from the group with |\global V=V|. Under
277 some conditions, we set the boolean |Z| to true, globally (|!Z0|),
278 which triggers a second call to |,| with different setting,
279 and actually flips the opponent's pieces.
280 \begin{verbatim}
281 ~,{@QS@JK[j=T(Y!^P!;2]O,/[j=P!VV(I(Y/!Z0]]]]}
282 \end{verbatim}
283
284 I moved those |O| and |"| guys a little bit in this explanation,
285 but not in the original implemenation, because it is hard
286 to sync. We assign weights to each of the $64$ cells:
287 \begin{center}
288 \halign{&\hfil#\hfil\cr
289 9 & 1 & 6 & 6 & 6 & 6 & 1 & 9 \cr
290 1 & 1 & 2 & 2 & 2 & 2 & 1 & 1 \cr
291 6 & 2 & 4 & 4 & 4 & 4 & 2 & 6 \cr
292 6 & 2 & 4 & 4 & 4 & 4 & 2 & 6 \cr
293 6 & 2 & 4 & 4 & 4 & 4 & 2 & 6 \cr
294 6 & 2 & 4 & 4 & 4 & 4 & 2 & 6 \cr
295 1 & 1 & 2 & 2 & 2 & 2 & 1 & 1 \cr
296 9 & 1 & 6 & 6 & 6 & 6 & 1 & 9 \cr}
297 \end{center}
298 All weights are positive, so that every move which flips a piece
299 ends up with a positive overall value. The AI would be better if
300 the places next to corners had a negative weight, but I would have
301 too much code to rewrite for that to work. We really have three
302 types of rows and three types of columns. Converting from |Q|
303 or |J| is done by |"|, then we assemble the two as a number
304 in the range $[0,8]$, and use another \cs{ifcase} construction
305 to produce the weights.
306 \begin{verbatim}
307 ~O{Z"Q\multiplyZ3@Z"J@V(Z9|1|6|1|1|2|6|2|4] }
308 ~"#1{(#1|0|1|2|2|2|2|1|0]}
309 \end{verbatim}
310
311 The counter |R| keeps track of the score difference,
312 and is updated with |;2| (when flipping a piece) or |;1| (when
313 adding a piece). The counter |R| should be \cs{advance}d (|@|)
314 by a positive amount when the current player |P| is player |0|,
315 and a negative amount for player |-|.
316 \begin{verbatim}
317 ~;{@R(P|-]}
318 \end{verbatim}
319
320 After printing the board, we go through every cell and find the
321 one with the highest value. The macro \cs{A}, does one row, hence
322 |\:\A| does all the rows. Store the argument as the row number |Q|,
323 then loop over columns. After setting the column number |J| to
324 its argument, \cs{C} calls |)|, which as explained above computes
325 the value of placing a piece there, throws away that case if it flips
326 nothing, otherwise also counts the weight of the current cell. Then
327 update the best value |W| and the best row |U| and column |L| if
328 the new |V| is larger than |W|.
329 \begin{verbatim}
330 ~\A#1{Q#1:\C}
331 ~\C#1{J#1)[0<VO[V>WWVUQLJ]]}
332 \end{verbatim}
333
334 We won't need |~| as \cs{def} anymore, so we reuse it as the main command.
335 \begin{itemize}
336 \item First exchange the players: set |P| equal to |T|, but first expand
337 the value of |P| after |T| to set that as well.
338 \item Secondly, open an alignment, with a repeating preamble adding a space
339 at its end. Then message a new-line (we should be using |?| rather than
340 |M| here, I think) to keep a clean output. Afterwards, print the top line
341 with |'|, the eight lines of the bulk with |_|, and the bottom line,
342 which happens to end with |?{*}*|, \emph{i.e.}, ends with \cs{cr}:
343 we can thus close the alignment, and cause \TeX{} to output the page.
344 \item After printing, it is time to check whether there is a move or not.
345 We don't want to flip pieces at this stage, hence set the boolean |I|
346 to false ($1$). And we reset the best value to $0$, unless it was
347 already $0$ (which means that the previous player had no available
348 move), in which case we set it to $-1$. Then loop over rows, finding
349 the best value (see \cs{A}). Reset the boolean |I| to be true.
350 \item If a move was found in the previous step ($|W|>0$), either
351 use it if the player is the AI, or query the user. The various
352 booleans are set up in such a way as to do the flipping, so
353 calling |)| does it. Then also put a player's piece in the current
354 cell |^|, and increase the score difference by $1$.
355 \item Finally, if neither player could move, declare the game ended,
356 give the score, and \cs{dump} the run (not \cs{end} because we want to
357 support both plain \TeX{} and \LaTeX{}). Otherwise, repeat.
358 \end{itemize}
359 Of course, after defining |~|, we call it. Let's play!
360 \begin{verbatim}
361 ~~{
362 PXTXTNP
363 \halign{&## *M{*}'_1A_2B_3C_4D_5E_6F_7G_8H'}\vfil\break
364 I1 W(W./0] :\AI0
365 [0<W
366 [1=PQUJL/q]
367 )
368 ^P;1
369 ]
370 [.=W
371 ?{(RTie/ Player [0>R-/0] wins by N[0>R-]R].}
372 X\dump
373 ]
374 ~
375 }
376 ~
377 \end{verbatim}
378
379 \end{document}