/* main.c Copyright (C) 2026 Pierre Sarrazin This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include "graphics.h" #include "file.h" #include "dict.h" #include "GameState.h" #include "CursorBlinker.h" #include "GamePlayer.h" #include "PositionIterator.h" #include "WordSearch.h" #include "Keyboard.h" /* bcontrol library */ #include "Player.h" /* bsound library */ #define SCRIPTED_KEYS // Must be consistent with the previous enum. // static const byte colorBySquareType[] = { PAL_BOARD_BG, PAL_DOUBLE_WORD, PAL_TRIPLE_WORD, PAL_DOUBLE_WORD, PAL_TRIPLE_LETTER, PAL_DOUBLE_LETTER }; static DECBDrive drives[NUM_DISK_DRIVES]; static Keyboard keyboard; // For sounds. // static Player soundPlayer; enum { KEY_UP = '^', KEY_DOWN = 10, KEY_LEFT = 8, KEY_RIGHT = 9, KEY_ENTER = 13, KEY_CANCEL = 3, KEY_BACKSPACE = 8, KEY_PASS = 'P', KEY_QUIT = 'Q', KEY_HELP = '?', // show help from menu shown by Break key KEY_CONTINUE = 'C', KEY_MONITOR = 'M', // switches between RGB and CMP palettes }; static byte *textScrnWritePos; // current address to write to in the 32x16 screen static word timer; // 60 Hz tick counter static unsigned seed; // seed passed to srand() static byte difficultyLevel = LEVEL_EASY; // LEVEL_* value static BOOL userPlaysFirst = TRUE; // Wait a certain number of sixtieths of a second. // static void waitTicks(word numTicks) { const word start = timer; while (timer - start < numTicks) ; } #ifdef SCRIPTED_KEYS // The characters defined in the following array are typed automatically. static const char scriptedKeys[] = ""; static size_t scriptedKeyIndex = 0; // index into scriptedKeys[] byte pollKeyboard(void) { //printf("KEYS:[%s]\n", scriptedKeys); //if (scriptedKeyIndex < 5) // printf("[%u %u]", scriptedKeyIndex, scriptedKeys[scriptedKeyIndex]); if (scriptedKeys[scriptedKeyIndex]) { //printf("SCRIPTED: %u %u\n", scriptedKeyIndex, scriptedKeys[scriptedKeyIndex]); return (byte) scriptedKeys[scriptedKeyIndex++]; } return Keyboard_poll(&keyboard); } #else #define pollKeyboard() (Keyboard_poll(&keyboard)) #endif static byte pollKeyNoLowerCase(void) { byte key = pollKeyboard(); if (!key) return 0; return (byte) toupper((char) key); } // Keyboard_init() must have been called. // void pause(void) { while (pollKeyboard() == 0) ; } void clearTextScreen(void) { memset16((void *) TEXT_SCREEN, 0x6060, 512 / 2); textScrnWritePos = TEXT_SCREEN; } // vector: e.g., 0xFFF8 for IRQ. // void setISR(void *vector, ISR newRoutine) { byte *isr = * (byte **) vector; *isr = 0x7E; // JMP extended * (ISR *) (isr + 1) = newRoutine; } // N.B.: Player_init() must have been called before this ISR is allowed to be invoked. // interrupt asm void irqISR() { asm { _dskcon_irqService IMPORT ldb $FF03 bpl @done // do nothing if 63.5 us interrupt ldb $FF02 // 60 Hz interrupt. Reset PIA0, port B interrupt flag. ; lbsr Player_defaultIRQService // Player_init() must have been called ; ldd :timer addd #1 std :timer lbsr _dskcon_irqService // routine provided by decbfile library ; @done } } asm void consoleOutHook32x16(void) { asm { pshs x,b // must be preserved ldx :textScrnWritePos cmpa #13 beq @newline ; bsr @convertASCIITo6847Code sta ,x+ // no check for end of screen bra @done ; @convertASCIITo6847Code cmpa #64 blo @typo // typographical char cmpa #96 blo @conversionDone // upper-case letter cmpa #128 bhs @conversionDone // graphical char suba #96 // lower-case letter @conversionDone rts @typo adda #64 rts ; @scrollUp ldx #TEXT_SCREEN @scrollUpLoop ldd 32,x // load 2 bytes from row below std ,x++ // store in current row and advance cmpx #TEXT_SCREEN+480 blo @scrollUpLoop ldd #$6060 // 2 spaces @fillLastRow std ,x++ cmpx #TEXT_SCREEN+512 blo @fillLastRow rts ; @newline tfr x,d andb #$E0 // carriage return addd #32 // line feed tfr d,x @done cmpx #TEXT_SCREEN+512 blo @notAtEndOfScreen bsr @scrollUp ldx #TEXT_SCREEN+480 @notAtEndOfScreen stx :textScrnWritePos puls b,x } } #if 0 typedef struct WordPrinter { word numWordsInBlock; word wordIndexInBlock; } WordPrinter; // On a new block, initialize the WordPrinter at userData. // static byte printNextBlock(word numWordsInBlock, void *userData) { WordPrinter *wp = (WordPrinter *) userData; wp->numWordsInBlock = numWordsInBlock; wp->wordIndexInBlock = 0; printf("\n""BLOCK HAS %u WORDS:", numWordsInBlock); return DICT_ITER_LIST_WORDS; } // On each word of the current block. // static BOOL printWord(const char *currentWord, byte currentWordLength, void *userData) { WordPrinter *wp = (WordPrinter *) userData; // Print the last few words of the block. if (wp->wordIndexInBlock >= wp->numWordsInBlock - 5) printf(" %u=%s", wp->wordIndexInBlock, currentWord); ++wp->wordIndexInBlock; return TRUE; // continue iteration } void showDictionary(void) { printf("PRESS [ENTER] TO SEE THE WORDS:\n"); pause(); WordPrinter wordPrinter = { 0, 0 }; iterateDictionary(printNextBlock, printWord, 0, &wordPrinter); printf("\nTHE END. PRESS [ENTER] TO CONTINUE."); pause(); clearTextScreen(); } #endif // Must be as long as the width in chars of the text window where writePaddingString() writes, // i.e. TEXT_WIN_WIDTH. // static const char *spaces = " "; // str: Must not be empty. // static void writePaddingString(byte row, const char *str) { writeStringAt(TEXT_WIN_LEFT, row, str); byte len = (byte) strlen(str); writeStringAt(TEXT_WIN_LEFT + len, row, spaces + len); } static void writeInstructions(const char *line0, const char *line1, const char *line2, const char *line3, const char *line4) { // The area used here must be consistent with clearInstructions(). writePaddingString(TEXT_INSTR_ROW + 0, line0); writePaddingString(TEXT_INSTR_ROW + 1, line1); writePaddingString(TEXT_INSTR_ROW + 2, line2); writePaddingString(TEXT_INSTR_ROW + 3, line3); writePaddingString(TEXT_INSTR_ROW + 4, line4); } // Clears the window used by writeInstructions(). // static void clearInstructions(void) { byte *destPixelRow = getPixelAddr(TEXT_WIN_LEFT * (word) CHAR_WIDTH, TEXT_INSTR_ROW * (word) CHAR_HEIGHT); const byte winWidthInBytes = (SCRN_WIDTH - ((TEXT_WIN_LEFT * (word) CHAR_WIDTH) & ~7)) / 2; const byte byteToClearWith = PAL_SCREEN_BG | (PAL_SCREEN_BG << 4); for (byte row = 5 * CHAR_HEIGHT; row--; destPixelRow += BYTES_PER_ROW) memset(destPixelRow, byteToClearWith, winWidthInBytes); } static void writeResult(const char *line0, const char *line1, const char *line2, const char *line3) { writePaddingString(TEXT_RESULT_ROW + 0, line0); writePaddingString(TEXT_RESULT_ROW + 1, line1); writePaddingString(TEXT_RESULT_ROW + 2, line2); writePaddingString(TEXT_RESULT_ROW + 3, line3); } static void clearResult(void) { writeResult("", "", "", ""); } static void writeScore(const GamePlayer *currentPlayer) { byte row = TEXT_SCORE_ROW + (currentPlayer->isComputer ? 1 : 0); char str[TEXT_WIN_WIDTH + 1]; sprintf(str, "%s: %5u pts", currentPlayer->isComputer ? "Me " : "You", currentPlayer->score); writeStringAt(TEXT_WIN_LEFT, row, str); } void printRackToTextScreen(const byte rack[RACK_SIZE]) { printf("RACK: ["); for (byte i = 0; i < RACK_SIZE; ++i) { char c = GameState_getTileTypeChar(rack[i]); putchar(c == ' ' ? '.' : c); } printf("]\n"); } void showUserRack(const byte rack[RACK_SIZE]) { for (byte i = 0, col = TEXT_WIN_LEFT; i < RACK_SIZE; ++i, col += 2) writeCharAt(col, 1, GameState_getTileTypeChar(rack[i])); } static byte rackHasLetter(byte rack[RACK_SIZE], char asciiLetter) { if (asciiLetter >= 'A' && asciiLetter <= 'Z') { byte requiredTileType = (byte) (asciiLetter - '@'); // 1..26 for (byte i = 0; i < RACK_SIZE; ++i) if (rack[i] == requiredTileType) return i; } return 255; } byte rackHasBlank(byte rack[RACK_SIZE]) { for (byte i = 0; i < RACK_SIZE; ++i) if (rack[i] == TILE_TYPE_BLANK) return i; return 255; } #define copyRack(destRack, srcRack) (memcpy((destRack), (srcRack), RACK_SIZE)) static void addToRack(byte rack[RACK_SIZE], byte tileType) { for (byte i = 0; i < RACK_SIZE; ++i) if (rack[i] == TILE_TYPE_NONE) { rack[i] = tileType; break; } } #if 0 /* Debugging. */ void dumpRack(byte rack[RACK_SIZE]) { for (byte i = 0; i < RACK_SIZE; ++i) putchar(rack[i] + '@'); } #endif static word randomWord = 0; // 0..$0FFF (the 12 low bits of the word) static byte numNybblesLeft = 0; // Returns a random value between 0..15. // Optimizes the number of calls to rand(). // Depends on the seed passed to srand(). // static byte generateRandomNybble(void) { if (numNybblesLeft == 0) { randomWord = (word) rand() & 0x0FFF; // keep 12 of the 15 low bits numNybblesLeft = 3; } byte newNybble = (byte) randomWord & 0x0F; randomWord >>= 4; --numNybblesLeft; return newNybble; } typedef struct PositionedChar { byte col; // column of 51x24 screen char ch; // character to print } PositionedChar; static const PositionedChar ellipsisAnimationStates[6] = { { 2, '.' }, { 2, ' ' }, { 1, ' ' }, { 0, ' ' }, { 0, '.' }, { 1, '.' }, }; typedef struct EllipsisAnimation { byte counter; byte rate; // controls speed of animation (value to be reached by 'counter') byte state; // 0..6 re: ellipsisAnimationStates[] byte firstCol; // 1st column of the 3 dots byte row; // row of the 3 dots } EllipsisAnimation; static EllipsisAnimation ellipsisAnimation; static void EllipsisAnimation_init(byte firstCol, byte row, byte rate) { assert(firstCol < TEXT_SCREEN_WIDTH); assert(row < TEXT_SCREEN_HEIGHT); assert(rate > 0); ellipsisAnimation.counter = 0; ellipsisAnimation.rate = rate; ellipsisAnimation.state = 0; ellipsisAnimation.firstCol = firstCol; ellipsisAnimation.row = row; } // Callback invoked by some dictionary search functions to indicate progress. // static void EllipsisAnimation_update(void) { assert(ellipsisAnimation.firstCol >= TEXT_WIN_LEFT); if (++ellipsisAnimation.counter < ellipsisAnimation.rate) return; // not time yet to change state ellipsisAnimation.counter = 0; if (++ellipsisAnimation.state >= 6) ellipsisAnimation.state = 0; const PositionedChar *pc = &ellipsisAnimationStates[ellipsisAnimation.state]; writeCharAt(ellipsisAnimation.firstCol + pc->col, ellipsisAnimation.row, pc->ch); } // May be useful for debugging. // #define rejectWord(rejectedWord) (TRUE) //static word numSkippedWords; // for testing // currentWord: ASCII word to be checked. // userData: Must point to a WordSearch object. // The rack in the WordSearch may contain blank tiles. Tiles that get used are removed from it. // No tile in 'rack' is used twice. // static BOOL checkIfWordPlayableWithRack(const char *currentWord, byte currentWordLength, void *userData) { WordSearch *ws = (WordSearch *) userData; ++ws->numWordsProcessed; // If the difficulty level is easy, skip some of the dictionary's words, // to simulate a player who does not know the entire dictionary by heart. // if (ws->difficultyLevel == LEVEL_EASY && generateRandomNybble() < 14) { //++numSkippedWords; return rejectWord(currentWord); // let iterateDictionary() continue to next word } // Show a progress indicator. // static byte timeToAnimate = 0; if (++timeToAnimate == 0) EllipsisAnimation_update(); // Make a copy of the rack so that we can take tiles out of it during the test. // byte workRack[RACK_SIZE]; copyRack(workRack, ws->rack); // For each letter of 'currentWord', look up this letter in the rack. // byte firstLetterIndexNotInRack = 255; BOOL fail = FALSE; char letter; byte letterIndex; for (letterIndex = 0; (letter = currentWord[letterIndex]) != '\0'; ++letterIndex) { byte letterTileTypeBehindBlank = TILE_TYPE_NONE; byte rackIndex = rackHasLetter(workRack, letter); if (rackIndex == 255) // if rack does not have 'letter' nor a blank tile for it { rackIndex = rackHasBlank(workRack); if (rackIndex == 255) // if no blank { if (firstLetterIndexNotInRack != 255) // if already seen non-playable letter fail = TRUE; // program not strong enough to try to play this word firstLetterIndexNotInRack = letterIndex; // one letter not in rack is OK: continue } else letterTileTypeBehindBlank = letter - '@'; } if (rackIndex != 255) // rack has 'letter' or blank tile for it: workRack[rackIndex] = TILE_TYPE_NONE; // don't use this tile again in current test ws->letterTileTypeBehindBlank[letterIndex] = letterTileTypeBehindBlank; } if (fail) { //printf("WORD '%s' NOT PLAYABLE.\n", currentWord); return rejectWord(currentWord); // let iterateDictionary() continue to next word } // Here, all letters in 'currentWord' have been found in rack, with the possible // exception of one, which would be currentWord[firstLetterIndexNotInRack]. // if (firstLetterIndexNotInRack != 255 && ws->allInRack) return rejectWord(currentWord); // currentWord requires tile not in rack, and we want rack-only word #if 0 printf("%s PLAYABLE", currentWord); if (firstLetterIndexNotInRack != 255) printf(" IF FREE %c", currentWord[firstLetterIndexNotInRack]); else printf(" ALL FROM RACK"); printf("\n"); #endif if (firstLetterIndexNotInRack != 255) { // currentWord is playable if the letter in currentWord[firstLetterIndexNotInRack] // can be found on the board AND if there is room around that letter to the rest // of 'currentWord'. // if (!GameState_tryHangWord(ws->gameState, currentWord, currentWordLength, currentWord[firstLetterIndexNotInRack], firstLetterIndexNotInRack, currentWordLength - firstLetterIndexNotInRack - 1, &ws->foundWordHorizontal, &ws->foundWordRow, &ws->foundWordCol)) return rejectWord(currentWord); // failed to hang currentWord to existing board letter, keep searching //printf("PUT %s AT %u,%u %s\n", // currentWord, ws->foundWordRow, ws->foundWordCol, ws->foundWordHorizontal ? "HORIZ" : "VERT"); } else if (!ws->allInRack) { // The current word can be formed from the rack, but we want to be able to // hang it to an existing tile on the board. Try to hang the word by each of // its letters. // byte i; for (i = 0; currentWord[i] != '\0'; ++i) if (GameState_tryHangWord(ws->gameState, currentWord, currentWordLength, currentWord[i], i, currentWordLength - i - 1, &ws->foundWordHorizontal, &ws->foundWordRow, &ws->foundWordCol)) { /*printf("PUT %s AT %u,%u %s (I=%u)\n", currentWord, ws->foundWordRow, ws->foundWordCol, ws->foundWordHorizontal ? "HORIZ" : "VERT", i);*/ break; // success: can hang from currentWord[i] } if (currentWord[i] == '\0') return rejectWord(currentWord); // failed to hang currentWord to existing board letter, keep searching } /*else printf("PUT %s ALL FROM RACK\n", currentWord);*/ strcpy(ws->foundWord, currentWord); copyRack(ws->rack, workRack); return FALSE; // stop at first found, because no following word is longer } // Put the word on the board, assuming the board is empty. // void chooseWordPositionOnEmptyBoard(const GameState *gs, const char *wordToPlace, byte *outRow, byte *outCol, BOOL *outHorizontally) { byte wordLen = (byte) strlen(wordToPlace); // Try to reach the right edge, where there is a triple word score. // *outCol = (wordLen <= (BOARD_SIZE / 2 + 1) ? (byte) BOARD_SIZE / 2 : BOARD_SIZE - (byte) wordLen); *outRow = BOARD_SIZE / 2; *outHorizontally = TRUE; // this function could one day also try vertical placement } // Computer search for a playable word. // ws: Initialized WordSearch object. // A search is successful if ws->foundWord is not an empty string. // static void searchPlayableWord(byte rack[RACK_SIZE], const GameState *gs, BOOL allInRack, WordSearch *ws) { //numSkippedWords = 0; iterateDictionary(NULL, checkIfWordPlayableWithRack, 0, ws); //printf("Processed %u, skipped %u.\n", ws->numWordsProcessed, numSkippedWords); if (allInRack && *ws->foundWord) chooseWordPositionOnEmptyBoard(gs, ws->foundWord, &ws->foundWordRow, &ws->foundWordCol, &ws->foundWordHorizontal); } static byte setRightAndBottomColor(byte row, byte col, byte colorIndex, BOOL addingPerimeter) { assert(row < BOARD_SIZE); assert(col < BOARD_SIZE); byte leftX = col * TILE_WIDTH; byte rightX = leftX + TILE_WIDTH; byte topY = row * TILE_WIDTH; byte bottomY = topY + TILE_WIDTH; // Box on the grid. byte c = addingPerimeter ? colorIndex : PAL_BOARD_GRID; vline(topY, bottomY, rightX, c); hline(leftX, rightX, bottomY, c); // Box one pixel inside the grid. byte origColorIndex = getPixel(leftX + 1, topY + 1); vline(topY + 1, bottomY - 1, rightX - 1, colorIndex); hline(leftX + 1, rightX - 1, bottomY - 1, colorIndex); return origColorIndex; } static byte setSquarePerimeterColor(byte row, byte col, byte colorIndex, BOOL addingPerimeter) { assert(row <= BOARD_SIZE); assert(col <= BOARD_SIZE); byte leftX = col * TILE_WIDTH; byte rightX = (col == BOARD_SIZE ? leftX + 1 : leftX + TILE_WIDTH); byte topY = row * TILE_WIDTH; byte bottomY = (row == BOARD_SIZE ? topY + 1 : topY + TILE_WIDTH); if (row == BOARD_SIZE || col == BOARD_SIZE) // if last row or last column { byte c0 = addingPerimeter ? colorIndex : PAL_BOARD_GRID; byte c1 = addingPerimeter ? colorIndex : PAL_SCREEN_BG; if (col == BOARD_SIZE) // if at right of board { vline(topY, bottomY, leftX, c0); vline(topY, bottomY, rightX, c1); } else // at bottom of board { hline(leftX, rightX, topY, c0); hline(leftX, rightX, bottomY, c1); } return 0xFF; // does not matter } // Box on the grid. drawBox(leftX, topY, rightX, bottomY, addingPerimeter ? colorIndex : PAL_BOARD_GRID); // Box one pixel inside the grid. byte origColorIndex = getPixel(leftX + 1, topY + 1); drawBox(leftX + 1, topY + 1, rightX - 1, bottomY - 1, colorIndex); return origColorIndex; } // tileType: A letter is drawn on the tile only if this is in 1..26, for A..Z. // row, col: Board coordinates. // void drawTileOnBoard(byte tileType, byte row, byte col, byte foreColorIndex, byte backColorIndex) { assert(row < BOARD_SIZE); assert(col < BOARD_SIZE); byte squareX = col * TILE_WIDTH; byte squareY = row * TILE_WIDTH; // Draw tile background. drawRect(squareX + 2, squareY + 2, TILE_WIDTH - 3, TILE_WIDTH - 3, backColorIndex); // Draw tile letter. (No foreground to draw if blank tile.) if (tileType >= 1 && tileType <= 26) writeTileCharAtPixelPosWithColors(squareX + 4, squareY + 3, tileType, foreColorIndex, backColorIndex); } static byte waitForKey(void) { byte key; while ((key = pollKeyNoLowerCase()) == 0) ; return key; } // Uses the global 'timer' variable. // static byte readKeyFromBoardCursor(byte row, byte col) { byte key; CursorBlinker cursorBlinker; CursorBlinker_init(&cursorBlinker, &timer); for (;;) { if (CursorBlinker_updateFromTimer(&cursorBlinker, PAL_POS_CURSOR)) { byte prev = setSquarePerimeterColor(row, col, cursorBlinker.newColorIndex, !cursorBlinker.isDisplayed); CursorBlinker_updateAfterChange(&cursorBlinker, prev); } key = pollKeyNoLowerCase(); if (key != 0) { // Remove the cursor if it is currently displayed. if (cursorBlinker.isDisplayed) setSquarePerimeterColor(row, col, cursorBlinker.origColorIndex, FALSE); break; } } return key; } static byte getGameActionFromUser(void) { for (;;) { byte key = waitForKey(); switch (key) { case BREAK_KEY: return KEY_CONTINUE; case KEY_PASS: case KEY_QUIT: case KEY_HELP: case KEY_CONTINUE: case KEY_MONITOR: return key; } } } static void playSoundAtNormalSpeed(byte tone, byte duration) { poke(65496, 0); // normal speed Player_sound(tone, duration); poke(65497, 0); // high speed } static void playErrorSound(void) { playSoundAtNormalSpeed(204, 1); // G4 } static void playUserTurnSound(void) { playSoundAtNormalSpeed(50, 1); } static void showHelp(const GameState *gs); static BOOL getPositionOnBoardFromUser(const GameState *gs, byte *inOutRow, byte *inOutCol, BOOL mustUseCentralSquare) { assert(*inOutRow < BOARD_SIZE); assert(*inOutCol < BOARD_SIZE); byte row = *inOutRow, col = *inOutCol; for (;;) { byte key = readKeyFromBoardCursor(row, col); switch (key) { case KEY_HELP: showHelp(gs); break; case KEY_UP: row = (row + (BOARD_SIZE - 1)) % BOARD_SIZE; break; case KEY_DOWN: row = (row + 1) % BOARD_SIZE; break; case KEY_LEFT: col = (col + (BOARD_SIZE - 1)) % BOARD_SIZE; break; case KEY_RIGHT: col = (col + 1) % BOARD_SIZE; break; case KEY_ENTER: if (mustUseCentralSquare && ( (row != BOARD_SIZE / 2 && col != BOARD_SIZE / 2) || (row == BOARD_SIZE / 2 && col > BOARD_SIZE / 2) || (col == BOARD_SIZE / 2 && row > BOARD_SIZE / 2))) { playErrorSound(); writeResult("The first word", "must use", "the central", "square."); break; } assert(row < BOARD_SIZE); assert(col < BOARD_SIZE); *inOutRow = row; *inOutCol = col; return TRUE; case '\\': // Shift-Clear prints the seed. Useful for debugging. printf("%c%c%u\n", difficultyLevel == LEVEL_EASY ? 'E' : 'H', userPlaysFirst ? 'U' : 'C', seed); break; case KEY_CANCEL: return FALSE; } } } // Draws the tiles in prevBoardTile[] in the reverse order in which // the letters of the entered word were typed in. // // *row: One row past the last row occupied by the entered word, // if across is FALSE, otherwise, the row of that word. // *col: One column past the last column occupied by the entered word, // if across is TRUE, otherwise, the column of that word. // redrawEmptyTiles: The empty tiles in prevBoardTile[] are only redrawn // if this is TRUE, otherwise they are left as they are. // static void eraseEnteredWord(const GameState *gs, byte wordLength, BOOL across, byte *row, byte *col, const byte prevBoardTile[], BOOL redrawEmptyTiles) { assert(wordLength <= MAX_WORD_LEN); assert(*row <= BOARD_SIZE); PositionIterator posIter; PositionIterator_init(&posIter, across, row, col); // Redraw the tiles of the word that were already on the board. // The other tiles will be overwritten in the right color after the end // of this function. for (byte i = wordLength; i--; ) { PositionIterator_decrement(&posIter); // decrement *row or *col assert(*row <= BOARD_SIZE); byte prevTileType = prevBoardTile[i]; if (prevTileType != TILE_TYPE_NONE) { byte tileTypeToDraw, fore; if (prevTileType == TILE_TYPE_BLANK) { tileTypeToDraw = GameState_getBlankTileLetter(gs, *row, *col); fore = PAL_BLANK_TILE_FORE; } else { tileTypeToDraw = prevTileType; fore = PAL_BOARD_WRITING; } drawTileOnBoard(tileTypeToDraw, *row, *col, fore, PAL_TILE_BG); } else if (redrawEmptyTiles) { byte squareType = GameState_boardSquareTypes[*row][*col]; drawTileOnBoard(TILE_TYPE_NONE, *row, *col, PAL_BOARD_WRITING, colorBySquareType[squareType]); } } } static BOOL usesCentralSquare(const WordSearch *ws, byte wordLength) { const byte row = ws->foundWordRow, col = ws->foundWordCol; if (ws->foundWordHorizontal) { if (row != BOARD_SIZE / 2 || col > BOARD_SIZE / 2 // start at right of center || col + wordLength <= BOARD_SIZE / 2) return FALSE; } else { if (col != BOARD_SIZE / 2 || row > BOARD_SIZE / 2 // start below center row || row + wordLength <= BOARD_SIZE / 2) return FALSE; } return TRUE; } typedef struct Displacement { signed char dx, dy; } Displacement; static const Displacement displacements[5] = { { 0, 0 }, { +1, 0 }, // right { 0, -1 }, // up { -1, 0 }, // left { 0, +1 }, // down }; // gs: Represents the board without the candidate word. // static BOOL isCandidateWordPosValid(const GameState *gs, byte wordLength, BOOL across, byte row, byte col) { // Check if one of the letters is adjacent to a letter // already on the board. // PositionIterator posIter; PositionIterator_init(&posIter, across, &row, &col); for (byte i = wordLength; i--; ) { // Point (row, col) the next tile of the candidate word, // from the last tile to the first one. // PositionIterator_decrement(&posIter); // Try to find a board tile that is at or beside (row, col). // for (byte j = 0; j < ARRAY_SIZE(displacements); ++j) { const Displacement *d = &displacements[j]; const byte tileType = GameState_getTileWithBoundsChecking( gs, row + d->dy, col + d->dx); if (tileType != TILE_TYPE_NONE) return TRUE; // found tile at or beside (row, col) } } // No candidate tile is overlapping or adjacent to an existing tile. return FALSE; // reject } // row, col: In/out. Position PAST the last entered letter in the candidate word. // static BOOL rejectOverlongWord(const GameState *gs, BOOL across, byte row, byte col, byte wordLength) { //printf("rejectOverlongWord(%u, %u, %u, %u)\n", across, row, col, wordLength); byte prefixLen, suffixLen, dummy; if (across) { prefixLen = GameState_detectHorizontalPrefix(gs, row, col - wordLength); suffixLen = GameState_detectHorizontalSuffix(gs, row, col - 1); } else // candidate word is vertical: { prefixLen = GameState_detectVerticalPrefix(gs, row - wordLength, col); suffixLen = GameState_detectVerticalSuffix(gs, row - 1, col); } byte extendedLen = prefixLen + wordLength + suffixLen; //printf("rejectOverlongWord: %u + %u + %u = %u\n", // prefixLen, wordLength, suffixLen, extendedLen); assert(extendedLen <= BOARD_SIZE); if (extendedLen > MAX_WORD_LEN) { playErrorSound(); writeResult("This would", "create a word", "of more than", STRINGIFY_VALUE(MAX_WORD_LEN) " letter(s)."); return FALSE; } return TRUE; } // User has pressed Enter while entering a word. // Checks if the word is in the dictionary. // Also checks adjacent words. // If the word is rejected, writeResult() is called with an error message // and FALSE is returned. // Otherwise workRack[] is copied to ws->rack[], the result field is cleared // and TRUE is returned. // row, col: In/out. Position PAST the last entered letter in ws->foundWord[]. // static BOOL handleEnterKey(WordSearch *ws, BOOL allInRack, const GameState *gs, byte wordLength, byte prevBoardTile[MAX_WORD_LEN + 1], byte workRack[RACK_SIZE], BOOL across, byte *row, byte *col) { if (allInRack) { // Check that word uses central square. if (!usesCentralSquare(ws, wordLength)) { playErrorSound(); writeResult("The first word", "must use", "the central", "square."); return FALSE; } } else { if (!isCandidateWordPosValid(gs, wordLength, across, *row, *col)) { playErrorSound(); writeResult("Your word must", "overlap a tile", "or be adjacent", "to one."); return FALSE; } } writeResult("Checking your", "word...", "", ""); assert(wordLength <= MAX_WORD_LEN); // Reject the word if it extends an existing word beyond MAX_WORD_LEN. if (!rejectOverlongWord(gs, across, *row, *col, wordLength)) return FALSE; ws->foundWord[wordLength] = '\0'; // Check if the word is in the dictionary. // Set up a callback that animates the "..." in the text of the last call // to writeResult(). // EllipsisAnimation_init() is given the position of that "...". // EllipsisAnimation_init(TEXT_WIN_LEFT + 4, TEXT_RESULT_ROW + 1, 7); dict_setSearchProgressCallback(EllipsisAnimation_update); BOOL found = isWordInDictionary(ws->foundWord); dict_setSearchProgressCallback(NULL); // Reject the word if it is not in the dictionary. if (!found) { playErrorSound(); writeResult("Not in the", "dictionary.", "", ""); //printf("ws->foundWord='%s'.\n", ws->foundWord); return FALSE; } // Reject the word if it extends an existing word in a way that // is not in the dictionary. BOOL accepted = GameState_checkAdjacentWords( gs, ws->foundWordHorizontal, ws->foundWordRow, ws->foundWordCol, 255, ws->foundWord, wordLength); if (!accepted) { playErrorSound(); writeResult("Your word", "creates an", "illegal", "adjacent word."); return FALSE; } // Accept the word. Update the player's rack. eraseEnteredWord(gs, wordLength, across, row, col, prevBoardTile, FALSE); copyRack(ws->rack, workRack); ws->foundWordHorizontal = across; clearResult(); return TRUE; } static void handleBackspaceKey(WordSearch *ws, byte *wordLength, byte prevBoardTile[MAX_WORD_LEN + 1], byte workRack[RACK_SIZE], BOOL across, byte *row, byte *col) { if (*wordLength == 0) return; --*wordLength; if (across) --*col; else --*row; assert(*row < BOARD_SIZE); byte prevTileType = prevBoardTile[*wordLength]; if (prevTileType == TILE_TYPE_NONE) { // Letter being erased came from workRack[]. byte origKey = ws->foundWord[*wordLength]; if (ws->letterTileTypeBehindBlank[*wordLength] != TILE_TYPE_NONE) addToRack(workRack, TILE_TYPE_BLANK); else addToRack(workRack, origKey - '@'); } byte squareType = GameState_boardSquareTypes[*row][*col]; drawTileOnBoard(prevTileType, *row, *col, PAL_BOARD_WRITING, prevTileType == TILE_TYPE_NONE ? colorBySquareType[squareType] : PAL_TILE_BG); showUserRack(workRack); } // ws->foundWordHorizontal must be set on entry. // Updates the displayed rack as the user types or backspaces. // static BOOL letUserTypeWord(WordSearch *ws, BOOL allInRack, const GameState *gs) { assert(ws->foundWordRow < BOARD_SIZE); byte row = ws->foundWordRow, col = ws->foundWordCol; byte wordLength = 0; // index into ws->foundWord[] and ws->letterTileTypeBehindBlank[] byte prevBoardTile[MAX_WORD_LEN + 1]; // tile types // Make a copy of the rack so that we can take tiles out of it during the test. byte workRack[RACK_SIZE]; copyRack(workRack, ws->rack); const BOOL across = ws->foundWordHorizontal; CursorBlinker cursorBlinker; CursorBlinker_init(&cursorBlinker, &timer); for (;;) { // Animate cursor. if (CursorBlinker_updateFromTimer(&cursorBlinker, PAL_WORD_ENTRY_CURSOR)) { byte prev = setSquarePerimeterColor(row, col, cursorBlinker.newColorIndex, !cursorBlinker.isDisplayed); CursorBlinker_updateAfterChange(&cursorBlinker, prev); } // Read keyboard. byte key = pollKeyNoLowerCase(); if (!key) continue; if (key == KEY_HELP) { showHelp(gs); continue; } // Remove the cursor and reinitialize it so that it properly registers // the underlying color of the next square it will blink on. if (cursorBlinker.isDisplayed) setSquarePerimeterColor(row, col, cursorBlinker.origColorIndex, FALSE); CursorBlinker_init(&cursorBlinker, &timer); // Interpret key. if (key == KEY_CANCEL) { eraseEnteredWord(gs, wordLength, across, &row, &col, prevBoardTile, TRUE); ws->foundWord[0] = '\0'; showUserRack(ws->rack); clearResult(); return FALSE; } if (key == KEY_ENTER) { if (!handleEnterKey(ws, allInRack, gs, wordLength, prevBoardTile, workRack, across, &row, &col)) continue; // Here, ws->rack[] has been updated. return TRUE; } if (key == KEY_BACKSPACE) { // Puts the tile back in workRack[]. handleBackspaceKey(ws, &wordLength, prevBoardTile, workRack, across, &row, &col); continue; } if (key < 'A' || key > 'Z' || wordLength == MAX_WORD_LEN || row == BOARD_SIZE || col == BOARD_SIZE) { if (key) playErrorSound(); continue; } byte currentTileType = GameState_getTile(gs, row, col); BOOL keyUsesBlank = FALSE; // If there is at tile at [row][col], then 'key' must correspond to it. if (currentTileType >= 1 && currentTileType <= 26) // if non-blank tile { if (key - '@' != currentTileType) { playErrorSound(); continue; } } else if (currentTileType == TILE_TYPE_BLANK) { // The board at (row, col) has a blank tile, so this blank tile // must have been used to represent the same letter as 'key', // otherwise the key is rejected. // if (GameState_getBlankTileLetter(gs, row, col) != key - '@') { playErrorSound(); continue; } } else { // No tile at [row][col], so check that 'key' is in rack. byte rackIndex = rackHasLetter(workRack, (char) key); if (rackIndex == 255) // if key not in rack { // Check if rack has unused blank. rackIndex = rackHasBlank(workRack); if (rackIndex == 255) { playErrorSound(); continue; } keyUsesBlank = TRUE; } workRack[rackIndex] = TILE_TYPE_NONE; // don't use this tile again showUserRack(workRack); } assert(wordLength < MAX_WORD_LEN); // assert still room for one more char ws->foundWord[wordLength] = (char) key; ws->letterTileTypeBehindBlank[wordLength] = (keyUsesBlank ? key - '@' : TILE_TYPE_NONE); // Print the letter. Remember what tile was under it, if any. prevBoardTile[wordLength] = currentTileType; drawTileOnBoard(key - '@', row, col, PAL_PROMPTS, PAL_SCREEN_BG); ++wordLength; if (across) ++col; else ++row; } } // Returns TRUE if the user wants to continue to the next page, // or FALSE if the user wants to stop reading. // static BOOL pressSpaceOrBreak(BOOL lastPageShown) { printf("\n" "Press [Space] "); if (!lastPageShown) printf("to continue,\n"); printf("or [Break] to return to%cthe game.", !lastPageShown ? ' ' : '\n'); byte key; while ((key = pollKeyboard()) != ' ' && key != BREAK_KEY) ; if (!lastPageShown) clearHardwareTextScreen(); return key == ' '; } typedef byte (*GridFuncPtr)(const GameState *gs, byte tileType); static void printGrid(const GameState *gs, GridFuncPtr gridFuncPtr) { const byte numRows = 6, numCols = 5; for (byte row = 0; row < numRows; ++row) { for (byte col = 0; col < numCols; ++col) { byte tileNo = col * numRows + row + 1; if (tileNo > 26) putchar('\n'); else { byte points = (*gridFuncPtr)(gs, tileNo); printf(" %c %2u ", (char) (tileNo + '@'), points); } } } } // Switches to the 40x24 screen, prints help pages, waits for the user // to press a key, then switches back to the graphics screen. // static void showHelp(const GameState *gs) { clearHardwareTextScreen(); asm { sync } // switch screen mode during v-sync: showHardwareTextScreen(); printf("Tile values\n\n"); printGrid(gs, GameState_getTileValue); printf("\n""Tile distribution\n\n"); printGrid(gs, GameState_getNumTilesOfType); printf("\n""There are %u blank tiles.\n", GameState_getNumTilesOfType(gs, TILE_TYPE_BLANK)); if (pressSpaceOrBreak(FALSE)) { word totalNumWords; getDictionaryStats(&totalNumWords); printf("This game's dictionary contains %u\n" "words, each one of " STRINGIFY_VALUE(MIN_WORD_LEN) " to " STRINGIFY_VALUE(MAX_WORD_LEN) " letters.\n" "\n" "The game forbids entering a word of more" "than " STRINGIFY_VALUE(MAX_WORD_LEN) " letters, or a word that would\n" "create an adjacent word of more than " STRINGIFY_VALUE(MAX_WORD_LEN) "\n" "letters.\n" "\n" "The premium squares have the same effect" "on scoring than in the traditional game." "\n" "The game is over when both players have\n" "passed twice, all in a row. A player\n" "passes automatically when that player's\n" "rack is empty and the bag is also empty.", totalNumWords); (void) pressSpaceOrBreak(TRUE); } asm { sync } // switch screen mode during v-sync: showGraphicsMode(); } enum { USER_PLAYS, USER_PASSES, USER_QUITS, }; enum { USER_PROMPT_SET_START, USER_PROMPT_SET_DIRECTION, USER_PROMPT_MENU, }; // Fills *ws with the word composed by the user. // allInRack: TRUE if the word must be composed entirely of letters found in rack[]; // FALSE if the word can use letters that are already on the board. // ws: Initialized WordSearch object. // Returns USER_*. // static byte askUserForWord(byte rack[RACK_SIZE], const GameState *gs, BOOL allInRack, WordSearch *ws, byte initRow, byte initCol) { assert(initRow < BOARD_SIZE); assert(initCol < BOARD_SIZE); ws->foundWordRow = initRow; ws->foundWordCol = initCol; byte state = USER_PROMPT_SET_START; byte key; CursorBlinker cursorBlinker; for (;;) { switch (state) { case USER_PROMPT_SET_START: writeInstructions("Choose where", "to start your", "word with the", "arrows, then", "press Enter."); if (!getPositionOnBoardFromUser(gs, &ws->foundWordRow, &ws->foundWordCol, allInRack)) { state = USER_PROMPT_MENU; break; } /* FALLTHROUGH */ case USER_PROMPT_SET_DIRECTION: writeInstructions("Across (right", "arrow), down", "(down arrow),", "or go back", "(Break)?"); CursorBlinker_init(&cursorBlinker, &timer); do { if (CursorBlinker_updateFromTimer(&cursorBlinker, PAL_BOARD_WRITING)) { byte prev = setRightAndBottomColor(ws->foundWordRow, ws->foundWordCol, cursorBlinker.newColorIndex, !cursorBlinker.isDisplayed); CursorBlinker_updateAfterChange(&cursorBlinker, prev); } key = pollKeyNoLowerCase(); if (key == KEY_HELP) showHelp(gs); } while (key != KEY_RIGHT && key != KEY_DOWN && key != KEY_CANCEL); // Remove the cursor if it is currently displayed. if (cursorBlinker.isDisplayed) setRightAndBottomColor(ws->foundWordRow, ws->foundWordCol, cursorBlinker.origColorIndex, FALSE); if (key == KEY_CANCEL) { state = USER_PROMPT_SET_START; break; } writeInstructions("Type your word", "then Enter.", "(Backspace and", "Break can be", "used too.)"); ws->foundWordHorizontal = (key == KEY_RIGHT); if (!letUserTypeWord(ws, allInRack, gs)) { state = USER_PROMPT_SET_DIRECTION; // user cancelled break; } return USER_PLAYS; case USER_PROMPT_MENU: // user may want to pass, quit, save or try again writeInstructions("Pass (P),", "continue (C),", "quit (Q),", "monitor (M) or", "help (?)?"); key = getGameActionFromUser(); switch (key) { case KEY_CONTINUE: state = USER_PROMPT_SET_START; break; case KEY_QUIT: writeInstructions("Really quit?", "Yes (Y) or", "No (N).", "", ""); while ((key = pollKeyNoLowerCase()) != 'Y' && key != 'N') ; if (key == 'N') { // Try again. state = USER_PROMPT_SET_START; break; } return USER_QUITS; case KEY_PASS: return USER_PASSES; case KEY_MONITOR: alternatePalettes(); state = USER_PROMPT_SET_START; // automatically continue break; case KEY_HELP: showHelp(gs); state = USER_PROMPT_SET_START; // automatically continue break; } } // switch } // for assert(FALSE); // for() should have done a return } // Places and draws the word in ws->foundWord[] on the board. // Places and draws a blank where indicated by ws->letterTileTypeBehindBlank[]. // static void placeWord(const WordSearch *ws, GameState *gs) { byte row, col, rowInc, colInc, wordLen; const char *wordToPlace; WordSearch_initWordWalk(ws, &row, &col, &rowInc, &colInc, &wordToPlace, &wordLen); for (byte i = 0; i < wordLen; ++i, row += rowInc, col += colInc) { byte tile = GameState_getTile(gs, row, col); if (tile == TILE_TYPE_NONE) // don't overwrite existing tile, which may be a blank { // Put the tile on the board. byte letterTileTypeBehindBlank = ws->letterTileTypeBehindBlank[i]; tile = (letterTileTypeBehindBlank == TILE_TYPE_NONE ? wordToPlace[i] - '@' : TILE_TYPE_BLANK); GameState_setTile(gs, row, col, tile, letterTileTypeBehindBlank); // Draw the tile on the board. // If the tile is a blank, draw its letter value in a different color. byte fore; byte tileTypeBehindBlankAtPos = GameState_getBlankTileLetter(gs, row, col); if (tileTypeBehindBlankAtPos != TILE_TYPE_NONE) // if blank at (row, col) { tile = tileTypeBehindBlankAtPos; fore = PAL_BLANK_TILE_FORE; } else fore = PAL_BOARD_WRITING; drawTileOnBoard(tile, row, col, fore, PAL_TILE_BG); } } } // Assumes the board's top left corner is at (0, 0). // void drawBoard() { // Draw the squares. for (byte row = 0; row < BOARD_SIZE; ++row) { for (byte col = 0; col < BOARD_SIZE; ++col) { byte colorIndex = colorBySquareType[GameState_boardSquareTypes[row][col]]; draw6ByteWideRectangle(col * 6, row * TILE_HEIGHT, TILE_HEIGHT, colorIndex); } } // Draw the grid around the squares. for (byte row = 0; row < BOARD_SIZE + 1; ++row) hline(0, BOARD_SIZE * TILE_WIDTH, row * TILE_HEIGHT, PAL_BOARD_GRID); for (byte col = 0; col < BOARD_SIZE + 1; ++col) vline(0, BOARD_SIZE * TILE_HEIGHT, col * TILE_WIDTH, PAL_BOARD_GRID); // Misc. writeStringAt(TEXT_WIN_LEFT, 0, "Your rack:"); } // Assumes the board's top left corner is at (0, 0). // void drawTilesOnBoard(GameState *gs) { for (byte row = 0; row < BOARD_SIZE; ++row) { for (byte col = 0; col < BOARD_SIZE; ++col) { byte tileType = GameState_getTile(gs, row, col); if (tileType == TILE_TYPE_NONE) continue; // empty drawTileOnBoard(tileType, row, col, PAL_BOARD_WRITING, PAL_TILE_BG); } } } #ifndef NDEBUG void assertHandler(const char *file, int lineno, const char *condition) { printf("!!!%s:%d (%u)\n" /*": %s"*/, file, lineno, seed); for (byte tone = 255; tone >= 1; tone >>= 1) Player_sound(tone, 1); for (;;) ; } #endif // Returns TRUE if the user says that the monitor is RGB. // static BOOL showPresentation(void) { //0----+----1----+----2----+----3----+---- printf("\n" " " DISPLAY_NAME "\n" "\n" "\n" " Version " VERSION "\n" "\n" " Copyright (C) 2026 Pierre Sarrazin\n" "\n" " Distribution: GNU GPL v3 or later\n" "\n" "\n" " This is a Scrabble-like board game,\n" " but only words of 2 to 5 letters are\n" " allowed.\n" "\n" " This game's dictionary may contain\n" " words that may be offensive to some\n" " players. Player discretion is advised.\n" "\n" " Press the [Break] or [?] key during\n" " your turn to get help pages.\n" "\n" " To start, press [R] now if you have an\n" " RGB monitor, or [C] for composite.\n"); //" Press [Space] to continue."); byte key; while ((key = pollKeyNoLowerCase()) != 'R' && key != 'C') ; return key == 'R'; } // Assumes that the graphics screen is shown and empty. // Clears it before returning. // Fills globals difficultyLevel and userPlaysFirst. // static void askForGameConfig(void) { byte diffLevelKey, firstPlayerKey; for (;;) { writeStringAt(6, 10, "Difficulty level? (E = easy, H = hard)"); do diffLevelKey = waitForKey(); while (diffLevelKey != 'E' && diffLevelKey != 'H'); writeStringAt(3, 14, "Which player starts? (U = user, C = computer)"); do firstPlayerKey = waitForKey(); while (firstPlayerKey != 'U' && firstPlayerKey != 'C' && firstPlayerKey != BREAK_KEY); hcls(PAL_SCREEN_BG); if (firstPlayerKey != BREAK_KEY) break; } difficultyLevel = (diffLevelKey == 'E' ? LEVEL_EASY : LEVEL_HARD); userPlaysFirst = (firstPlayerKey == 'U'); } // Uses globals difficultyLevel and userPlaysFirst. // static void playGame(void) { drawBoard(); GameState gameState; GameState_init(&gameState); // Create the two players and print their initial scores. // GamePlayer players[NUM_PLAYERS]; // [0] is computer, [1] is user for (byte i = 0; i < NUM_PLAYERS; ++i) { GamePlayer *player = &players[i]; BOOL isComputer = (i == 0); GamePlayer_init(player, isComputer); GameState_fillRackEmptySlots(&gameState, player->rack); if (!isComputer) showUserRack(player->rack); writeScore(player); } byte turn = userPlaysFirst ? 1 : 0; BOOL firstUserTurn = TRUE; byte numNoPlays = 0; // number of consecutives times that players have passed byte initRow = BOARD_SIZE / 2, initCol = BOARD_SIZE / 2; for ( ; ; turn = (turn + 1) % NUM_PLAYERS) { writeStringAt(TEXT_WIN_LEFT, TEXT_TURN_ROW, turn ? "Your" : "My"); writeStringAt(TEXT_WIN_LEFT + (turn ? 4 : 2), TEXT_TURN_ROW, " turn. "); GamePlayer *currentPlayer = &players[turn]; if (!currentPlayer->isComputer) { if (firstUserTurn) { writeResult("Press [Break]", "for options,", "[?] for help.", ""); firstUserTurn = FALSE; } playUserTurnSound(); } BOOL allInRack = GameState_isBoardEmpty(&gameState); WordSearch wordSearch; WordSearch_init(&wordSearch, currentPlayer->rack, allInRack, difficultyLevel, &gameState); // If the player's rack is empty, the player passes automatically. // BOOL passBecauseEmptyRack = FALSE; if (GamePlayer_isRackEmpty(currentPlayer)) { passBecauseEmptyRack = TRUE; assert(*wordSearch.foundWord == '\0'); } else if (currentPlayer->isComputer) // if non empty rack, computer's turn { writeInstructions("Thinking...", "", "", "", ""); // Initialize the progress indicator. // The coordinates must be consistent with the text just written. // The 8 is the length of "Thinking", i.e., the offset of "..." from // the start of the written line. // EllipsisAnimation_init(TEXT_WIN_LEFT + 8, TEXT_INSTR_ROW, 1); const word startTime = timer; // measure time taken by search searchPlayableWord(currentPlayer->rack, &gameState, allInRack, &wordSearch); while (timer - startTime < 2 * 60) // minimum wait time ; } else // non empty rack, user's turn: { byte userAction = askUserForWord(currentPlayer->rack, &gameState, allInRack, &wordSearch, initRow, initCol); clearInstructions(); if (userAction == USER_QUITS) break; if (userAction == USER_PASSES) *wordSearch.foundWord = '\0'; else assert(userAction == USER_PLAYS); } if (*wordSearch.foundWord) // if the player has a word to play { word wordValue = WordSearch_countPointsFromWordsPlayed(&wordSearch, &gameState); currentPlayer->score += wordValue; // Print points just scored. { char nPoints[TEXT_WIN_WIDTH + 1]; utoa10(wordValue, nPoints); strcat(nPoints, " point"); strcat(nPoints, wordValue == 1 ? "." : "s."); writeResult(currentPlayer->isComputer ? "I score" : "You score", nPoints, "", ""); } writeScore(currentPlayer); // Put the word on the board. placeWord(&wordSearch, &gameState); numNoPlays = 0; if (currentPlayer->isComputer) { // Put user's cursor at start of computer's last word. initRow = wordSearch.foundWordRow; initCol = wordSearch.foundWordCol; } else // Update user's rack to remove the tiles just used. { showUserRack(currentPlayer->rack); } } else { writeResult(currentPlayer->isComputer ? "I pass." : "You pass.", passBecauseEmptyRack ? "(Empty rack.)" : "", "", ""); // Give user time to see. waitTicks(2 * 60); ++numNoPlays; if (numNoPlays == NUM_PLAYERS * 2) break; // no player can play: game over } // Refill the current player's rack before starting the next player's turn, // so that the user can immediately start thinking of words to be made with // the refilled rack. // GameState_fillRackEmptySlots(&gameState, currentPlayer->rack); if (!currentPlayer->isComputer) showUserRack(currentPlayer->rack); } // for } // Main game loop. // This function does not return. // static void onStackRegisterMoved(void) { // Tell the GIME that the 32x16 screen is at TEXT_SCREEN. setSAMRegisters((byte *) 0xFFC6, TEXT_SCREEN >> 9, 7); clearTextScreen(); setConsoleOutHook(consoleOutHook32x16); // redirect printf() to 32x16 driver #if !defined(NDEBUG) && defined(_ASSERT_IMPL_H) /* If CMOC's was included. */ _SetFailedAssertHandler(assertHandler); #endif //printf("%s\n", __TIME__); // debugging: print build time byte driveNo = 0; //timer = 0; // start timing the load operation BOOL success = loadDataFile(driveNo, &textScrnWritePos); //word timeToLoadDict = timer; poke(0xFF40, 0); // stop disk motor if (success) { //showDictionary(); } else // load failed: freeze on error message { printf("[]"); for (;;) ; } //printf("TIME TO LOAD: %u TICKS\n", timeToLoadDict); //pause(); // Use high-speed poke now that the disk files have been loaded. poke(65497, 0); Keyboard_init(&keyboard); setupGraphicsMode(); clearHardwareTextScreen(); asm { sync } // switch screen mode during v-sync: showHardwareTextScreen(); BOOL monitorIsRGB = showPresentation(); asm { sync } // switch screen mode during v-sync: setPalette(monitorIsRGB); showGraphicsMode(); // Set the rand() seed after waiting for the user to pass // the presentation screen. The timer should now have a // hard to predict value. // #ifdef FIXED_SEED /* for debugging */ seed = FIXED_SEED; #else seed = timer; #endif srand(seed); for (;;) { askForGameConfig(); //printf("\n""Seed: %u\n", seed); playGame(); writePaddingString(TEXT_TURN_ROW, ""); // nobody's turn clearResult(); writeInstructions("Game over.", "", "Press N for", "a new game.", ""); playSoundAtNormalSpeed(1, 1); while (waitForKey() != 'N') ; asm { sync } // clear screen during v-sync hcls(PAL_SCREEN_BG); } } // main() must have no local variables because we move the S register. // int main() { static_assert(GRAPHICS_START < GRAPHICS_END); if (* (word *) 0xFFF8 != 0xFEF7) { printf("COCO 3 REQUIRED\n"); return 1; } // Initialize the sector file I/O library. // if (!initDiskSystem(drives)) return 1; // Have the decb_*() functions use dskcon() from dskcon.h // and the DC* variables also in that file. Those variables // must be in the same order as in Disk Basic. // decb_setDskConAddresses(dskcon_processSector, (DECBDskConVariables *) &DCOPC); disableInterrupts(); // Go to all-RAM mode. asm("CLR", "$FFDF"); // This initializes global pointer Player_instance, which is called by irqISR(). Player_init(&soundPlayer, FALSE, NULL); // Set the IRQ and NMI services. setISR(IRQ_VECTOR, irqISR); dskcon_init(dskcon_nmiService); // Move the stack register to the new stack space. asm { lds #STACK_BOTTOM } enableInterrupts(); // Call a function that does the actual work. // That function will initialize U to its stack frame, which will sit in // the new stack space. // onStackRegisterMoved(); // never returns return 0; }