-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathundo.c
executable file
·559 lines (485 loc) · 16.8 KB
/
undo.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
/* undo.c */
#include <stdio.h>
#include <string.h>
#include "array.h"
#include "baize.h"
#include "scrunch.h"
#include "stock.h"
#include "trace.h"
#include "undo.h"
#include "util.h"
#include "ui.h"
/*
BaizeResetState() creates a new, empty undo stack, then does an undo push, to save the starting state.
The number of user moves is the length of the undo stack minus one.
After a user move, there is a new undo push, to push the current state on the undo stack.
So the top of the undo stack is always the "pre move" state shown on the baize.
An undo command means popping the state from the top of the stack, and throwing it away.
A second state is popped, and the baize restored from that. Finally, the current state is pushed back onto the stack.
Restarting a deal works by popping all the items off the undo stack, restoring the baize from the last-popped state,
then pushing a new state onto the stack.
Bookmarking a position means remembering the current length of the undo stack.
Going back to a bookmark makes means popping saved states off the undo stack until it's length == the saved length,
restoring the baize from the last-popped state, and then pushing a new state onto the stack.
*/
#define EMPTY_LABEL ("*")
static void encodeLabel(char *dst, char *src)
{
if (*src == '\0') {
strcpy(dst, EMPTY_LABEL);
return;
}
while (*src) {
if (*src == ' ' || *src == '\t')
*dst++ = '_';
else
*dst++ = *src;
src++;
}
*dst = '\0';
}
static void decodeLabel(char *dst, char *src)
{
if (strcmp(src, EMPTY_LABEL) == 0) {
*dst = '\0';
return;
}
while (*src) {
if (*src == '_')
*dst++ = ' ';
else
*dst++ = *src;
src++;
}
*dst = '\0';
}
// We need to save the Card's prone flag as well as a reference (index) to the card in the card library
struct SavedCard {
unsigned int index:15;
unsigned int prone:1;
};
// Array functions store arrays of void* pointers, but we need to store arrays of indexes into the card library,
// so we have to make a new struct to avoid upsetting the compiler
struct SavedCardArray {
char label[MAX_PILE_LABEL+1];
size_t len;
struct SavedCard sav[];
};
static struct SavedCardArray* SavedCardArrayNew(struct Card* cardLibrary, struct Pile *const pile)
{
struct SavedCardArray* self = calloc(1, sizeof(struct SavedCardArray) + ArrayLen(pile->cards) * sizeof(struct SavedCard));
if (self) {
encodeLabel(self->label, pile->label);
self->len = 0;
size_t index;
for ( struct Card *c = ArrayFirst(pile->cards, &index); c; c = ArrayNext(pile->cards, &index) ) {
self->sav[self->len++] = (struct SavedCard){.index = c - cardLibrary, .prone = CardProne(c)};
}
}
return self;
}
static void SavedCardArrayCopyToPile(struct SavedCardArray *const sca, struct Card *const cardLibrary, struct Pile *const pile)
{
char label[MAX_PILE_LABEL+1];
decodeLabel(label, sca->label);
PileSetLabel(pile, label);
for ( size_t i=0; i<sca->len; i++ ) {
struct SavedCard sc = sca->sav[i];
struct Card* c = &cardLibrary[sc.index];
// PilePushCard does a Scrunch, so do a simplified copy of PilePushCard()
CardSetOwner(c, pile);
Vector2 fannedPos = PilePosAfter(pile, ArrayPeek(pile->cards)); // get this *before* pushing card to pile
CardTransitionTo(c, fannedPos);
pile->cards = ArrayPush(pile->cards, c);
sc.prone ? CardFlipDown(c) : CardFlipUp(c);
}
}
#if 0
static void SavedCardArrayWriteToFile(FILE* f, struct SavedCardArray *const sca)
{
// sca->label will not be empty
if (sca->label[0]=='\0') CSOL_ERROR("%s", "label is empty");
fprintf(f, "%s %lu:", sca->label, sca->len);
for ( size_t i=0; i<sca->len; i++ ) {
unsigned int number = sca->sav[i].index;
number <<= 1;
number |= sca->sav[i].prone;
fprintf(f, " %u", number);
// fprintf(f, " %d/%d", sca->sav[i].index, sca->sav[i].prone);
}
fprintf(f, "\n");
}
#endif
static void SavedCardArrayFree(struct SavedCardArray *const sca)
{
if (sca) {
free(sca);
}
}
/*
A snapshot of the baize is an object that contains
(1) the stock recycles count and
(b) an array (that mimics the baize piles array) of pointers to arrays (of SavedCardArray) of SavedCard objects
*/
static struct Snapshot* SnapshotNew(struct Baize *const self)
{
struct Snapshot *s = calloc(1, sizeof(struct Snapshot));
if (s) {
s->bookmark = self->bookmark;
s->recycles = ((struct Stock*)self->stock)->recycles;
s->savedPiles = ArrayNew(ArrayLen(self->piles));
if (s->savedPiles) {
size_t pindex;
for ( struct Pile *p = (struct Pile*)ArrayFirst(self->piles, &pindex); p; p = (struct Pile*)ArrayNext(self->piles, &pindex) ) {
struct SavedCardArray* sca = SavedCardArrayNew(self->cardLibrary, p);
s->savedPiles = ArrayPush(s->savedPiles, sca);
}
}
}
return s;
}
static void SnapshotFree(struct Snapshot *s)
{
size_t pindex;
for ( struct SavedCardArray *sca = ArrayFirst(s->savedPiles, &pindex); sca; sca = ArrayNext(s->savedPiles, &pindex) ) {
SavedCardArrayFree(sca);
}
ArrayFree(s->savedPiles);
free(s);
}
#if 0
static void SnapshotWriteToFile(FILE* f, size_t index, struct Snapshot *s)
{
fprintf(f, "#%lu %lu %d\n", index, s->bookmark, s->recycles);
size_t pindex;
for ( struct SavedCardArray *sca = ArrayFirst(s->savedPiles, &pindex); sca; sca = ArrayNext(s->savedPiles, &pindex) ) {
SavedCardArrayWriteToFile(f, sca);
}
}
#endif
static void BaizeUpdateStatusBar(struct Baize *const self)
{
char zLeft[64], zCenter[64], zRight[64];
zLeft[0] = '\0';
// Baize->stock may not be set yet if variant.lua/Build has not been run
if (self->stock && !PileHidden(self->stock)) {
if (self->waste) {
sprintf(zLeft, "STOCK: %lu WASTE: %lu", PileLen(self->stock), PileLen(self->waste));
} else {
sprintf(zLeft, "STOCK: %lu", PileLen(self->stock));
}
}
zCenter[0] = '\0';
if (BaizeComplete(self)) {
strcpy(zRight, "COMPLETE");
} else {
sprintf(zRight, "PROGRESS: %d%%", self->script->PercentComplete(self));
}
UiUpdateStatusBar(self->ui, zLeft, zCenter, zRight);
}
struct Array* UndoStackNew(void)
{
return ArrayNew(32);
}
void UndoStackFree(struct Array *stack)
{
ArrayForeach(stack, (ArrayIterFunc)SnapshotFree);
ArrayFree(stack);
}
void BaizeUndoPush(struct Baize *const self)
{
struct Snapshot* s = SnapshotNew(self);
self->undoStack = ArrayPush(self->undoStack, s);
BaizeUpdateStatusBar(self);
}
void BaizeUpdateFromSnapshot(struct Baize *const self, struct Snapshot *snap)
{
if ( ArrayLen(self->piles) != ArrayLen(snap->savedPiles) ) {
CSOL_ERROR("%s", "Bad snapshot");
return;
}
for ( size_t i=0; i<ArrayLen(self->piles); i++ ) {
struct SavedCardArray *sca = ArrayGet(snap->savedPiles, i);
struct Pile* dstPile = ArrayGet(self->piles, i);
ArrayReset(dstPile->cards);
SavedCardArrayCopyToPile(sca, self->cardLibrary, dstPile);
ScrunchPile(dstPile);
}
self->bookmark = snap->bookmark;
if (snap->recycles != ((struct Stock*)self->stock)->recycles) {
((struct Stock*)self->stock)->recycles = snap->recycles;
}
}
void BaizeSavePositionCommand(struct Baize *const self, void* param)
{
(void)param;
if ( BaizeComplete(self) ) {
UiToast(self->ui, "Cannot bookmark a completed game");
return;
}
self->bookmark = ArrayLen(self->undoStack);
UiToast(self->ui, "Position bookmarked");
// fprintf(stdout, "undoStack %lu bookmark %lu\n", ArrayLen(self->undoStack), self->bookmark);
}
void BaizeLoadPositionCommand(struct Baize *const self, void* param)
{
(void)param;
// fprintf(stderr, "undoStack 1 %lu\n", ArrayLen(self->undoStack));
if ( self->bookmark == 0 || self->bookmark > ArrayLen(self->undoStack) ) {
UiToast(self->ui, "No bookmark");
return;
}
// WHY can't you undo a completed game? Because undoing and then making a move counts as another win?
// if ( BaizeComplete(self) ) {
// UiToast(self->ui, "Cannot undo a completed game");
// return;
// }
struct Snapshot *snapshot = NULL;
while ( ArrayLen(self->undoStack) + 1 > self->bookmark ) {
if ( snapshot ) {
SnapshotFree(snapshot);
}
snapshot = ArrayPop(self->undoStack);
}
if (snapshot) {
BaizeUpdateFromSnapshot(self, snapshot);
SnapshotFree(snapshot);
}
BaizeUndoPush(self); // replace current state
// fprintf(stderr, "undoStack 2 %lu\n", ArrayLen(self->undoStack));
}
void BaizeRestartDealCommand(struct Baize *const self, void* param)
{
(void)param;
struct Snapshot *snapshot = NULL;
while ( ArrayLen(self->undoStack) > 0 ) {
if (snapshot) {
SnapshotFree(snapshot);
}
snapshot = ArrayPop(self->undoStack);
}
if (snapshot) {
BaizeUpdateFromSnapshot(self, snapshot);
SnapshotFree(snapshot);
}
self->bookmark = 0;
// do not run BaizeStartGame(self);!
BaizeUndoPush(self);
}
void BaizeUndo0(struct Baize *const self)
{
struct Snapshot *snap = ArrayPop(self->undoStack); // removes current state
if (!snap) {
CSOL_ERROR("no snap when popping from undo stack of length %lu", ArrayLen(self->undoStack));
return;
}
BaizeUpdateFromSnapshot(self, snap);
SnapshotFree(snap);
}
void BaizeUndoCommand(struct Baize *const self, void* param)
{
(void)param;
if ( ArrayLen(self->undoStack) < 2 ) {
UiToast(self->ui, "Nothing to undo");
return;
}
// WHY can't you undo a completed game? Because undoing and then making a move counts as another win?
// if ( BaizeComplete(self) ) {
// UiToast(self->ui, "Cannot undo a completed game");
// return;
// }
struct Snapshot* snap = ArrayPop(self->undoStack); // removes current state
if (!snap) {
CSOL_ERROR("%s", "popping from undo stack");
return;
}
SnapshotFree(snap); // discard this one, it's the same as the current baize
snap = ArrayPeek(self->undoStack);
if (!snap) {
CSOL_ERROR("%s", "peeking from undo stack");
return;
}
BaizeUpdateFromSnapshot(self, snap); // this was Peeked, so don't you go trying to free it
BaizeUpdateStatusBar(self);
}
#if 0
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
static _Bool createDirectories(char *src)
{
if (!src || *src != '/') {
CSOL_ERROR("%s", "bad input");
return 0;
}
struct stat st = {0};
char dirName[256];
char *dst = dirName;
while (*src) {
do {
// copy the first / and all chars up to but not including the next / or end of string
*dst++ = *src++;
} while (*src && *src != '/');
*dst = '\0';
if (stat(dirName, &st) == -1) {
CSOL_INFO("%s does not exist", dirName);
if (mkdir(dirName, 0700) == -1) {
CSOL_ERROR("cannot create %s", dirName);
return 0;
} else {
CSOL_INFO("%s created", dirName);
}
} else {
// fprintf(stdout, "INFO: %s: %s exists\n", __func__, dirName);
}
}
return 1;
}
#endif
#if 0
void BaizeSaveUndoToFile(struct Baize *const self)
{
extern int flag_nosave; if (flag_nosave) return;
char *homeDir;
if ((homeDir = getenv("HOME")) == NULL) {
CSOL_ERROR("%s", "HOME not set");
return;
}
/*
if ((homedir = getenv("HOME")) == NULL) {
homedir = getpwuid(getuid())->pw_dir;
}
*/
// fprintf(stdout, "INFO: %s: HOME is %s\n", __func__, homeDir);
char fname[256];
strcpy(fname, homeDir);
strcat(fname, "/.config/oddstream.games/csol");
if (!createDirectories(fname)) {
return;
}
strcat(fname, "/saved.txt");
FILE* f = fopen(fname, "w");
if (f) {
fprintf(f, "VARIANT=%s\n", self->variantName);
fprintf(f, "PILES=%lu\n", ArrayLen(self->piles));
fprintf(f, "UNDOSTACK=%lu\n", ArrayLen(self->undoStack));
{
size_t index;
for ( struct Snapshot *s = ArrayFirst(self->undoStack, &index); s; s = ArrayNext(self->undoStack, &index) ) {
SnapshotWriteToFile(f, index, s);
}
}
fclose(f);
} else {
CSOL_WARNING("could not create %s", fname);
}
// fprintf(stdout, "GetWorkingDirectory is %s\n", GetWorkingDirectory());
}
#endif
#if 0
struct Array* LoadUndoFromFile(char *variantName /* out */)
{
extern int flag_noload; if (flag_noload) return NULL;
char *homeDir;
if ((homeDir = getenv("HOME")) == NULL) {
CSOL_ERROR("%s", "HOME not set");
return NULL;
}
// fprintf(stdout, "INFO: %s: HOME is %s\n", __func__, homeDir);
char fname[256];
strcpy(fname, homeDir);
strcat(fname, "/.config/oddstream.games/csol/saved.txt");
struct Array *undoStack = NULL;
FILE* f = fopen(fname, "r");
if (f) {
size_t pileCount, stackDepth;
/*
"This implies that scanf will read across line boundaries to find its input, since newlines are white space.
(White space characters are blank, tab, newline, carriage return, vertical tab, and formfeed.)" -- K&R p157
*/
if (fscanf(f, "VARIANT=%[^\n]s", variantName) != 1) {
CSOL_ERROR("%s", "cannot read VARIANT=");
return NULL;
}
// prepend a space to 'PILES=' to consume \n
if (fscanf(f, " PILES=%lu", &pileCount) != 1) {
CSOL_ERROR("%s", "cannot read PILES=");
return NULL;
}
// prepend a space to 'UNDOSTACK=' to consume \n
if (fscanf(f, " UNDOSTACK=%lu", &stackDepth) != 1) {
CSOL_ERROR("%s", "cannot read UNDOSTACK=");
return NULL;
}
undoStack = ArrayNew(stackDepth + 16);
for ( size_t n=0; n<stackDepth; n++) {
size_t ncheck = 0xdeadbeef;
size_t bookmark;
int recycles;
// prepend a space to '#' to consume \n
if (fscanf(f, " #%lu %lu %d", &ncheck, &bookmark, &recycles) != 3) {
CSOL_ERROR("%s", "incorrect read of saved pile, expecting #number bookmark recycles");
goto fclose_label;
}
if (n != ncheck) {
CSOL_ERROR("saved pile miscount %lu != %lu", n, ncheck);
goto fclose_label;
}
struct Snapshot *snap = calloc(1, sizeof(struct Snapshot));
if (!snap) {
goto fclose_label;
}
snap->bookmark = bookmark;
snap->recycles = recycles;
snap->savedPiles = ArrayNew(pileCount);
if (!snap->savedPiles) {
free(snap);
goto fclose_label;
}
for ( size_t m=0; m<pileCount; m++ ) {
/*
<label> <count>: <cards>
*/
char label[256];
size_t cards;
if (fscanf(f, "%s %lu:", label, &cards) != 2) {
CSOL_ERROR("%s", "expecting <label> <cards>:");
goto fclose_label;
}
struct SavedCardArray *sca = calloc(1, sizeof(struct SavedCardArray) + cards * sizeof(struct SavedCard));
if (!sca) {
goto fclose_label;
}
if (strlen(label)>MAX_PILE_LABEL) {
sca->label[0] = '\0';
} else {
strcpy(sca->label, label);
}
for (size_t card=0; card<cards; card++) {
int index, prone;
unsigned int number;
if (fscanf(f, " %u", &number) != 1) {
CSOL_ERROR("%s", "expecting card index<<1|prone");
goto fclose_label;
}
index = number >> 1;
prone = number & 1;
sca->sav[sca->len++] = (struct SavedCard){.index=index, .prone=prone};
}
snap->savedPiles = ArrayPush(snap->savedPiles, sca);
}
undoStack = ArrayPush(undoStack, snap);
}
fclose_label: fclose(f);
remove(fname);
}
#ifdef _DEBUG
CSOL_INFO("state loaded from %s for '%s'", fname, variantName);
if (undoStack)
CSOL_INFO("returning undo stack of length %lu", ArrayLen(undoStack));
else
CSOL_INFO("%s", "returning null undo stack");
#endif
return undoStack;
}
#endif