/* color8.c - COLOR EIGHTS - A game of Eights for the Color Computer (1, 2 and 3). Copyright (C) 2003-2024 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 . */ /* To compile into color8.bin (for Disk Basic), see the Makefile. To test in the XRoar emulator: xroar -machine cocous -cart-autorun -cart color8.rom */ #include "cardgame.h" /////////////////////////////////////////////////////////////////////////////// #ifdef OS9 #include "Keyboard.h" /* bcontrol */ // bcontrol keyboard support. // Keyboard keyboard; #define inkey() (Keyboard_poll(&keyboard)) // blinkCursor: TRUE is not supported. // byte waitkey(byte blinkCursor) { for (;;) { byte key = inkey(); if (key) return key; } } void pcls(byte byteToClearWith) { memset(scrnBuffer, byteToClearWith, BYTES_PER_SCREEN); } // OS9Timer_init() must have been called successfully. // #define getTimer() (OS9Timer_getTimer()) // OS9Timer_init() must have been called successfully. // #define setTimer(newValue) (OS9Timer_setTimer(newValue)) #endif /* OS9 */ /////////////////////////////////////////////////////////////////////////////// #define PROGRAM_FULL_NAME "Color Eights" #define BY_LINE "By Pierre Sarrazin" #define COLOR_EIGHTS_URL "sarrazip.com/dev/color8.html" #define USER_HAND_ROW 149 #define DISPLAYED_CARD_COL 14 #define DISPLAYED_CARD_ROW 48 #define CARDS_PER_ROW 15 #define OVERLAY_HEIGHT 30 /* A card on top of another one must be drawn this many pixels lower, so enough of the bottom card shows. */ #define STATUS_COL 6 #define STATUS_ROW 1 // in characters #define DECK_COL 21 // in bytes of pixels #define DECK_ROW 8 // in pixels #define EVENT_ROW 13 #define REQUESTED_SUIT_COL 19 // in characters #define REQUESTED_SUIT_ROW 9 // in characters #define QUIT_GAME 0 #define NEXT_PLAYER_PLAYS 1 #define NEXT_PLAYER_PASSES 2 #define PLAY_NEW_GAME 3 /////////////////////////////////////////////////////////////////////////////// byte mainDeck[NUMCARDS]; byte numCardsMainDeck; byte discardDeck[NUMCARDS]; byte numDiscardedCards; byte displayedCard; byte requestedSuit; byte userHand[NUMCARDS]; byte numUserCards; byte computerHand[NUMCARDS]; byte numComputerCards; void initDecks() { numCardsMainDeck = NUMCARDS; for (byte i = 0; i < numCardsMainDeck; ++i) mainDeck[i] = i + 1; numDiscardedCards = 0; displayedCard = 0; numUserCards = 0; numComputerCards = 0; } void shuffleMainDeck() { shuffleDeck(mainDeck, numCardsMainDeck); } // Transfers all cards from the discarded deck into the main deck, // then calls shuffleMainDeck(). // void reshuffle() { assertf(numCardsMainDeck + numDiscardedCards <= NUMCARDS, "%u, %u", numCardsMainDeck, numDiscardedCards); for (byte i = 0; i < numDiscardedCards; i++) mainDeck[numCardsMainDeck++] = discardDeck[i]; numCardsMainDeck = numDiscardedCards; numDiscardedCards = 0; shuffleMainDeck(); } // Determines if 'card' is a card that does not make the other player // pick cards, pass a turn or change the requested suit. // byte isOrdinaryCard(byte card) { if (getCardType(card) == SUIT_JOKER) return FALSE; switch (getCardValue(card)) { case 2: case 8: case 11: // jack return FALSE; default: return TRUE; } } void putOrdinaryCardOnTopOfDeck() { if (numCardsMainDeck == 0) return; // Find the topmost (highest index) powerless card in the main deck. // byte i; for (i = numCardsMainDeck; i--; ) if (isOrdinaryCard(mainDeck[i])) break; if (i == 0xFF) // if no ordinary card return; // do nothing byte topIndex = numCardsMainDeck - 1; if (i == topIndex) // if topmost ordinary card is already on top return; // nothing to do // Swap found card with top card. // byte found = mainDeck[i]; mainDeck[i] = mainDeck[topIndex]; mainDeck[topIndex] = found; } byte pickCardFromMainDeck() { return pickCardFromDeck(mainDeck, &numCardsMainDeck); } byte isPlayableCard(byte card) { byte type = getCardType(card); if (type == SUIT_JOKER) return TRUE; byte val = getCardValue(card); if (val == 8) return TRUE; if (type == requestedSuit) return TRUE; return getCardType(displayedCard) != SUIT_JOKER && val == getCardValue(displayedCard); } byte atLeastOnePlayable(byte *hand, byte numCards) { byte i; for (i = 0; i < numCards; i++) if (isPlayableCard(hand[i])) return TRUE; return FALSE; } // Ordering of cards that puts the 8s at the end. // Jokers go after the 8s because they are cards #53 and #54 // (see getCardType() in cardgame.h). // byte cardComesAfter(byte card0, byte card1) { assertf(card0 != card1, "%u", card0); if (getCardValue(card0) == 8) if (getCardValue(card1) == 8) return card0 > card1; else return TRUE; // card0, being an 8, comes after card1, which is not an 8 else if (getCardValue(card1) == 8) return FALSE; else return card0 > card1; } // Returns the index in hand[] where newCard was inserted. // byte insertCardInDisplayOrder(byte *hand, byte initNumCards, byte newCard) { assertf(initNumCards <= NUMCARDS, "%u", initNumCards); assertf(newCard >= 1 && newCard <= NUMCARDS, "%u", newCard); // Find the first card in hand[] that comes after 'newCard'. // byte i = 0; for ( ; i < initNumCards; ++i) if (cardComesAfter(hand[i], newCard)) break; // Insert newCard at i (which may be initNumCards). // if (initNumCards > 0) for (byte j = initNumCards; j > i; --j) hand[j] = hand[j - 1]; hand[i] = newCard; return i; #if 0 // Debugging. printf("Inserted %2u at %2u (init # %2u):", newCard, i, initNumCards); for (byte j = 0; j < initNumCards + 1; ++j) printf(" %3u", hand[j]); printf("\n"); debugBufIndex = 0; printf("[%3u] [%3u]\n", 7, 0); byte debugBufIndex_ = debugBufIndex; restoreOriginalTextMode(); printf("debugBufIndex=%u\n", debugBufIndex_); for (byte j = 0; j < debugBufIndex_; ++j) printf(" %02x", debugBuf[j]); printf(".\n"); exit(0); #endif } // Evaluates hand[], of length 'numCards' and returns a score for each suit // in suitScores[4], the number of 8-cards in *nbEights and the number of // jokers in *nbJokers. // The score of a suit is higher if the player would be more advantaged // if that suit were the required one. // If 'playableCardsOnly' is true, then the score of a suit is zero if // that suit is currently not playable. Passing FALSE is useful when // playing an 8 or joker and any suit becomes admissible. // Returns the suit (suit_{HEARTS,SPADES,DIAMONDS,CLUBS} with the // highest score (as returned in suitScores[]). // byte evaluateHand(byte *suitScores, byte *nbEights, byte *nbJokers, byte *hand, byte numCards, byte playableCardsOnly) { suitScores[0] = 0; suitScores[1] = 0; suitScores[2] = 0; suitScores[3] = 0; *nbEights = 0; *nbJokers = 0; byte playableSuit[4]; playableSuit[0] = FALSE; playableSuit[1] = FALSE; playableSuit[2] = FALSE; playableSuit[3] = FALSE; byte i; for (i = 0; i < numCards; i++) { byte card = hand[i]; byte suit = getCardType(card); byte val; if (suit == SUIT_JOKER) (*nbJokers)++; else if ((val = getCardValue(card)) == 8) (*nbEights)++; else { if (isPlayableCard(card)) playableSuit[suit] = TRUE; byte s = 2; if (val == 11) // if jack s += 2; if (val == 2) // 2 forces 2- or 4-card pick { s += 8; if (suit == SUIT_SPADES) // 2 of spades forces 4-card pick s += 6; } suitScores[suit] += s; } } if (playableCardsOnly) for (byte suit = 0; suit < 4; suit++) if (!playableSuit[suit]) suitScores[suit] = 0; byte bestSuit = 0; for (byte suit = 0; suit < 4; suit++) if (suitScores[suit] > suitScores[bestSuit]) bestSuit = suit; return bestSuit; } byte eventRowUsed = FALSE; // text row where most messages appear #define autoMode FALSE // for debugging: when TRUE, user always picks void clearEventRow() { moveCursor(0, EVENT_ROW); printf(" "); eventRowUsed = FALSE; } void printEvent(const char *str) { if (eventRowUsed) { optDelay(60); clearEventRow(); } printCentered(EVENT_ROW, str); eventRowUsed = TRUE; } // Changes requestedSuit in the computer's interest. // void chooseComputerSuit() { byte suitScores[4]; byte nbEights; byte nbJokers; requestedSuit = evaluateHand(suitScores, &nbEights, &nbJokers, computerHand, numComputerCards, FALSE); char msg[33]; concat(msg, sizeof(msg), "I change the suit to ", getSuitName(requestedSuit), ".", NULL); printEvent(msg); } // Puts a card on the discarded deck and makes it the new displayed card. // This function must be the only way to make a card the displayed card. // void discardCard(byte card) { assertf(card >= 1 && card <= NUMCARDS, "%u", card); assertf(numDiscardedCards < NUMCARDS, "%u", numDiscardedCards); discardDeck[numDiscardedCards++] = card; displayedCard = card; } byte getPixelRowOfFirstCard(byte numCards, byte lastAdmissibleRow) { if (numCards > 30) numCards = 30; // fallback assertf(numCards <= NUMCARDS, "%u", numCards); assertf(lastAdmissibleRow >= OVERLAY_HEIGHT && lastAdmissibleRow < PIXEL_ROWS_PER_SCREEN, "%u", lastAdmissibleRow); byte numRowsUsed = (numCards + (CARDS_PER_ROW - 1)) / CARDS_PER_ROW; assertf(numRowsUsed > 0 && numRowsUsed <= 2, "%u, %u", numRowsUsed, numCards); byte row = lastAdmissibleRow - (numRowsUsed - 1) * OVERLAY_HEIGHT; assertf(row < PIXEL_ROWS_PER_SCREEN, "%u", row); return row; } // CARDS_PER_ROW is the max number of cards per screen row. // OVERLAY_HEIGHT is used if more than one row necessary. // Continue putting cards towards the top of the screen // if continueUpwards is true, towards the bottom otherwise. // void drawHand(byte *hand, byte numCards, byte y, byte continueUpwards) { if (numCards == 0) return; if (numCards > 30) numCards = 30; // fallback y = getPixelRowOfFirstCard(numCards, y); byte col = 0; byte x = 0; for (byte i = 0; i < numCards; ++i) { byte card = hand[i]; byte suit = getCardType(card); byte val = getCardValue(card); //printf("%2u. %2u %2u %2u ", i, card, suit, val); drawCompiledCard(val, suit, x, y); x += 2; ++col; if (col == CARDS_PER_ROW) // if next card will be on a new row: { col = 0; x = 0; y += OVERLAY_HEIGHT; } } } void drawUserHand() { // Black out card region before drawing cards. byte y = getPixelRowOfFirstCard(CARDS_PER_ROW << 1, USER_HAND_ROW); word byteOffset = (word) y * BYTES_PER_SCREEN_ROW; assertf(byteOffset < 0x1800, "%u", byteOffset); memset(scrnBuffer + byteOffset, 0, 0x1800 - byteOffset); drawHand(userHand, numUserCards, USER_HAND_ROW, TRUE); } // Show the given card sliding to the place of the displayed card. // void animatePlayedCard(byte card, byte isUsersTurn) { byte rowsPerCard = getNumPixelRowsPerCard(); byte val = getCardValue(card); byte type = getCardType(card); byte ticks = 15; // Slide the card up or down. // byte col = DISPLAYED_CARD_COL - 5; byte rowInc = (isUsersTurn ? -8 : 8); byte row = DISPLAYED_CARD_ROW + (isUsersTurn ? +24 : -24); for (byte i = 0; i < 4; ++i, row += rowInc) { drawCompiledCard(val, type, col, row); optDelay(ticks); // Blacken the bottom or top 8 pixel rows of the currently displayed card. // byte firstRowToBlacken = row; if (isUsersTurn) firstRowToBlacken += rowsPerCard - 8; word *writer = (word *) (scrnBuffer + (word) firstRowToBlacken * BYTES_PER_SCREEN_ROW + col); for (byte r = 8; r--; writer += WORDS_PER_SCREEN_ROW) *writer = writer[1] = 0x0000; } ticks = 0; // Slide to the right. // for ( ; col < DISPLAYED_CARD_COL; ++col) { drawCompiledCard(val, type, col, DISPLAYED_CARD_ROW); optDelay(ticks); ticks = 15; // Blacken the left column of the currently displayed card. // byte *writer = scrnBuffer + (word) DISPLAYED_CARD_ROW * BYTES_PER_SCREEN_ROW + col; for (byte i = rowsPerCard; i--; writer += BYTES_PER_SCREEN_ROW) *writer = 0x00; } drawCompiledCard(val, type, col, DISPLAYED_CARD_ROW); } void drawDisplayedCard() { drawCompiledCard(getCardValue(displayedCard), getCardType(displayedCard), DISPLAYED_CARD_COL, DISPLAYED_CARD_ROW); } // Blackens the area where the "which suit" menu is drawn. // void clearSuitMenu() { byte *dest = scrnBuffer + ((word) EVENT_ROW * PIXEL_ROWS_PER_TEXT_ROW - 1) * BYTES_PER_SCREEN_ROW; word numBytes = (word) BYTES_PER_SCREEN_ROW * ((word) ROWS_PER_SUIT * 2 + 2); memset(dest, 0, numBytes); } // Returns whether the next player must pass their turn. // byte playCard(byte card, byte isUsersTurn) { animatePlayedCard(card, isUsersTurn); discardCard(card); drawDisplayedCard(); byte cardType = getCardType(card); byte cardValue = getCardValue(card); byte nextPlayerPasses = FALSE; byte nextPlayerPicks = 0; // number of cards byte changesRequestedSuit = FALSE; // Determine the effects of the played card: if (cardType != SUIT_JOKER) { if (cardValue == 2) { nextPlayerPasses = TRUE; if (cardType == SUIT_SPADES) nextPlayerPicks = 4; else nextPlayerPicks = 2; } else if (cardValue == 8) changesRequestedSuit = TRUE; else if (cardValue == 11) nextPlayerPasses = TRUE; } else { nextPlayerPasses = TRUE; nextPlayerPicks = 5; changesRequestedSuit = TRUE; } // Apply the effects of the played card. if (nextPlayerPicks) { char msg[33], s[11]; // argument of dwtoa() MUST have at least 11 bytes concat(msg, sizeof(msg), isUsersTurn ? "You" : "I", " make ", isUsersTurn ? "me" : "you", " pick ", dwtoa(s, 0, nextPlayerPicks), " card", nextPlayerPicks > 1 ? "s." : ".", NULL); assertf(strlen(msg) < sizeof(msg), "%u", strlen(msg)); printEvent(msg); for ( ; nextPlayerPicks; --nextPlayerPicks) { if (numCardsMainDeck == 0) reshuffle(); if (numCardsMainDeck == 0) break; byte pickedCard = pickCardFromMainDeck(); if (isUsersTurn) computerHand[numComputerCards++] = pickedCard; else { insertCardInDisplayOrder(userHand, numUserCards, pickedCard); ++numUserCards; } } } if (nextPlayerPasses) { if (isUsersTurn) printEvent("You make me pass a turn."); else printEvent("I make you pass a turn."); } // If the card just played allows its player to change the requested suit, // but no player has won yet, then let the player choose a suit. // If a player has won, don't bother: the caller is expected to end the game. // if (changesRequestedSuit && numUserCards > 0 && numComputerCards > 0) { if (isUsersTurn) { // Redraw the user hand and the displayed card so that // the screen shows the 8 or joker has been played. // drawUserHand(); drawDisplayedCard(); // Draw a menu of suits to choose from. // printEvent("Which suit? H S D C "); for (byte suit = 0; suit < 4; ++suit) drawSuit(14 + suit * 5, EVENT_ROW * PIXEL_ROWS_PER_TEXT_ROW, suit); // Process keyboard input. // for (;;) { char c = (autoMode ? 'H' : (char) toupper(waitkey(FALSE))); if (c == 'H') requestedSuit = SUIT_HEARTS; else if (c == 'S') requestedSuit = SUIT_SPADES; else if (c == 'D') requestedSuit = SUIT_DIAMONDS; else if (c == 'C') requestedSuit = SUIT_CLUBS; else continue; break; } clearSuitMenu(); } else chooseComputerSuit(); } else requestedSuit = cardType; return nextPlayerPasses; } /* Utility function to draw a horizontal line. void drawPixelRow(byte y, byte byteToWrite) { byte *row = scrnBuffer + (word) y * BYTES_PER_SCREEN_ROW; for (int i = BYTES_PER_SCREEN_ROW; i--; ) *++row = byteToWrite; } */ void drawStatus() { byte statusRow = STATUS_ROW; moveCursor(STATUS_COL, statusRow); printf("Computer:"); moveCursor(STATUS_COL, ++statusRow); if (numComputerCards == 0) printf("no cards"); else printf("%u card%s ", numComputerCards, numComputerCards > 1 ? "s" : ""); moveCursor(DECK_COL + 1, (DECK_ROW >> 3) + 3); printf("%2u", numCardsMainDeck); } void drawAllCards() { drawUserHand(); drawDisplayedCard(); byte requestedCol = REQUESTED_SUIT_COL; byte requestedRow = REQUESTED_SUIT_ROW; moveCursor(requestedCol, requestedRow); printf("Requested:"); drawSuit(requestedCol + 3, ((requestedRow + 1) << 3) + 2, requestedSuit); drawStatus(); } #define NUM_CURSOR_ROWS 4 word savedBG[NUM_CURSOR_ROWS]; word *cursorAddr; // Changes cursorAddr and saves the new cursor background in savedBG[]. // selectedCardIndex: Must be < numUserCards. // void computeCursorAddress(byte selectedCardIndex) { byte cursorByteCol = (selectedCardIndex % CARDS_PER_ROW) << 1; byte rowOfFirstCard = getPixelRowOfFirstCard(numUserCards, USER_HAND_ROW); byte cursorPixelRow = rowOfFirstCard + selectedCardIndex / CARDS_PER_ROW * OVERLAY_HEIGHT + 1; assertf(cursorPixelRow < PIXEL_ROWS_PER_SCREEN, "%u", cursorPixelRow); cursorAddr = (word *) (scrnBuffer + (word) cursorPixelRow * BYTES_PER_SCREEN_ROW + (word) cursorByteCol); assertf(cursorAddr >= scrnBuffer && cursorAddr < scrnBuffer + BYTES_PER_SCREEN, "%p, %p", cursorAddr, scrnBuffer); for (byte i = 0; i < NUM_CURSOR_ROWS; ++i) savedBG[i] = cursorAddr[((word) i) << 4]; } // Uses cursorAddr and savedBG. // void restoreCursorBG() { assertf(cursorAddr >= scrnBuffer && cursorAddr < scrnBuffer + BYTES_PER_SCREEN, "%p, %p", cursorAddr, scrnBuffer); for (byte i = 0; i < NUM_CURSOR_ROWS; ++i) cursorAddr[((word) i) << 4] = savedBG[i]; } byte basicHelpShown; // is the H=HELP Q=QUIT prompt currently shown void showBasicHelp() { if (basicHelpShown) return; moveCursor(1, REQUESTED_SUIT_ROW); printf("H=help"); moveCursor(1, REQUESTED_SUIT_ROW + 1); printf("Q=quit"); basicHelpShown = TRUE; } void hideBasicHelp() { if (! basicHelpShown) return; moveCursor(1, REQUESTED_SUIT_ROW); putstr(" ", 6); moveCursor(1, REQUESTED_SUIT_ROW + 1); putstr(" ", 6); basicHelpShown = FALSE; } void initPlayScreen() { pcls(0); // Draw the deck as a face-down card. // moveCursor(DECK_COL, DECK_ROW >> 3); printf("Deck"); drawFaceDownCard(DECK_ROW + PIXEL_ROWS_PER_TEXT_ROW, DECK_COL); basicHelpShown = FALSE; } // Help lines must be at most 30 characters. const char *helpLines0[] = { "", "|" PROGRAM_FULL_NAME, "|" "V" VERSION, "", "|" BY_LINE, "|" COLOR_EIGHTS_URL, "", "", "Derived from Crazy Eights.", "", "Left and right arrows: move", "the cursor over your cards.", "", "SPACE: play the current card.", "P: pick a card.", "Q: quit the program.", "", "You cannot pick if one of your", "cards is playable. If the card", "picked is playable, it is", "played.", "", "|" "Press [Space] to continue.", 0 }; const char *helpLines1[] = { "", "An 8 changes the requested", "suit.", "", "So does the joker, which also", "makes the opponent pass their", "turn and makes them pick five", "cards.", "", "A 2 makes the opponent pass", "their turn and pick 2 cards", "(4 cards if it is a 2 of", "spades).", "", "A jack makes the opponent", "pass their turn.", "", "", "", "", "", "|" "Press [Space] to return", "|" "to the game.", 0 }; // A line that starts with '|' gets centered instead of // being left-justified. // void showTextLines(const char *lines[]) { for (byte i = 0; lines[i]; ++i) { byte row = i; if (row >= TEXT_ROWS_PER_SCREEN) return; const char *line = lines[i]; byte len = (byte) strlen(line); byte col; if (line[0] == '|') // if centered line { ++line; --len; col = (TEXT_COLS_PER_ROW - len) / 2; } else col = 1; moveCursor(col, row); putstr(line, len); } } void waitForSpaceKey(void) { while (waitkey(FALSE) != ' ') ; } void showHelpScreen() { pcls(0); showTextLines(helpLines0); waitForSpaceKey(); pcls(0); showTextLines(helpLines1); waitForSpaceKey(); initPlayScreen(); drawAllCards(); } void warnIfComputerLowOnCards() { byte writtenByte; if (numComputerCards >= 3) writtenByte = 0x00; else writtenByte = (getTimer() & 0x20 ? 0x00 : 0xAA); // blinking red line // Point byte *p = scrnBuffer + (STATUS_ROW + 2) * BYTES_PER_TEXT_ROW + STATUS_COL; byte numBytes = (numComputerCards > 1 ? 7 : 6); memset(p, writtenByte, numBytes); } void eraseLowCardWarning() { byte *p = scrnBuffer + (STATUS_ROW + 2) * BYTES_PER_TEXT_ROW + STATUS_COL; memset(p, 0, 7); } byte selectedCardIndex = 0; // index in userHand[], must be < numUserCards byte playUserTurn() { if (numUserCards == 0) return NEXT_PLAYER_PLAYS; // failsafe if (selectedCardIndex >= numUserCards) selectedCardIndex = numUserCards - 1; computeCursorAddress(selectedCardIndex); // init cursorAddr and resave background word prevPattern = 0; byte result = QUIT_GAME; for (;;) { byte key = autoMode ? 'P' : (char) toupper(inkey()); if (key == '?' || key == 'H') { showHelpScreen(); continue; } if (key == 'Q') { hideBasicHelp(); restoreCursorBG(); clearEventRow(); // avoid delay that would occur if printEvent() called on non-empty event row #ifdef CARTRIDGE_ROM printEvent("Start a new game? (Y/N)"); #else printEvent("Quit this program? (Y/N)"); #endif byte key = (byte) toupper(waitkey(FALSE)); if (key != 'Y') { clearEventRow(); continue; } result = QUIT_GAME; break; } if (key && eventRowUsed) { clearEventRow(); eventRowUsed = FALSE; } if (key == 'P') // if user picks { result = NEXT_PLAYER_PLAYS; #ifndef ALWAYS_ALLOW_PICKING if (atLeastOnePlayable(userHand, numUserCards)) { printEvent("You are not allowed to pick."); continue; } #endif if (numCardsMainDeck == 0) reshuffle(); if (numCardsMainDeck == 0) { hideBasicHelp(); restoreCursorBG(); printEvent("No more cards to be picked."); if (!autoMode) waitkey(FALSE); printEvent("Another game? (Y/N)"); byte key = autoMode ? 'Y' : (char) toupper(waitkey(FALSE)); return key == 'Y' ? PLAY_NEW_GAME : QUIT_GAME; } else { byte pickedCard = pickCardFromMainDeck(); selectedCardIndex = insertCardInDisplayOrder(userHand, numUserCards, pickedCard); ++numUserCards; assertf(numUserCards <= NUMCARDS, "%u", numUserCards); if (isPlayableCard(pickedCard)) { key = ' '; // simulate manual selection on picked card printEvent("You pick a card and play it."); // Wait and clear, because the animation will draw over the event row. optDelay(60); clearEventRow(); } else { printEvent("You pick a card: not playable."); break; } } } if (key == ' ') // [Space] to play current card { assertf(numUserCards <= NUMCARDS, "%u", numUserCards); assertf(selectedCardIndex < numUserCards, "%u", selectedCardIndex); if (! isPlayableCard(userHand[selectedCardIndex])) { printEvent("This card cannot be played."); continue; } hideBasicHelp(); restoreCursorBG(); // Take the card out of the user's hand: byte selectedCard = userHand[selectedCardIndex]; for (byte j = selectedCardIndex + 1; j < numUserCards; ++j) userHand[j - 1] = userHand[j]; --numUserCards; drawUserHand(); byte computerPasses = playCard(selectedCard, TRUE); if (numUserCards == 0) { #ifdef CARTRIDGE_ROM printEvent("You win."); waitkey(FALSE); return PLAY_NEW_GAME; #else printEvent("You win. Another game? (Y/N)"); byte key = (byte) toupper(waitkey(FALSE)); return key == 'Y' ? PLAY_NEW_GAME : QUIT_GAME; #endif } if (computerPasses) result = NEXT_PLAYER_PASSES; else result = NEXT_PLAYER_PLAYS; break; } if (key == 8 || key == 9) // if left or right arrow { restoreCursorBG(); if (key == 8) // if left selectedCardIndex = (selectedCardIndex == 0 ? numUserCards - 1 : selectedCardIndex - 1); else if (key == 9) selectedCardIndex = (selectedCardIndex == numUserCards - 1 ? 0 : selectedCardIndex + 1); assertf(selectedCardIndex < numUserCards, "%u, %u", selectedCardIndex, numUserCards); computeCursorAddress(selectedCardIndex); // update cursorAddr and resave background } showBasicHelp(); // if not already shown // Change cursor pattern a few times per second, using TIMER. // word curPattern = (getTimer() & 0x10) ? (word) 0x5555 : 0xAAAA; if (curPattern != prevPattern) { word *dest = cursorAddr; for (byte i = 0; i < NUM_CURSOR_ROWS; ++i) { *dest = curPattern; dest += WORDS_PER_SCREEN_ROW; } prevPattern = curPattern; } warnIfComputerLowOnCards(); } hideBasicHelp(); restoreCursorBG(); eraseLowCardWarning(); return result; } byte findSuitChangingCard(byte eightWanted) { assertf(numComputerCards < NUMCARDS, "%u", numComputerCards); for (byte i = 0; i < numComputerCards; i++) { byte card = computerHand[i]; byte suit = getCardType(card); if (eightWanted && suit != SUIT_JOKER && getCardValue(card) == 8) return i; if (!eightWanted && suit == SUIT_JOKER) return i; } return BAD_INDEX; } /** Find a card of the appropriate suit in the computer's hand. Does not choose a card whose value is 8 nor cards that are jokers. @param suit requested suit (not SUIT_JOKER) @param danger boolean that indicates that the computer should give preference to cards that can make the user pick cards and pass his turn @returns an index into computerHand[], or 0xFF on failure */ byte findComputerCard(byte suit, byte danger) { byte maxScore = 0; byte index = 0xFF; byte i; for (i = 0; i < numComputerCards; i++) { byte card = computerHand[i]; byte cardValue = getCardValue(card); byte cardType = getCardType(card); if (cardType == suit && cardValue != 8 && isPlayableCard(card)) { byte score = 6; if (cardValue == 2 || cardValue == 11) { score++; if (cardValue == 2) { score += 2; if (cardType == SUIT_SPADES) score += 2; } } // Here, score is expected to be between 6 and 11 inclusively. if (!danger) score = 12 - score; if (score > maxScore) { maxScore = score; index = i; } } } return index; } byte chooseComputerCard() { byte suitScores[4]; byte nbEights; byte nbJokers; byte bestSuit = evaluateHand(suitScores, &nbEights, &nbJokers, computerHand, numComputerCards, TRUE); assertf(bestSuit < 4, "%u", bestSuit); byte danger = (numUserCards <= 4); if (danger) { if (nbJokers > 0) return findSuitChangingCard(FALSE); if (suitScores[bestSuit] > 0) return findComputerCard(bestSuit, TRUE); if (nbEights > 0) return findSuitChangingCard(TRUE); } else { if (suitScores[bestSuit] > 0) return findComputerCard(bestSuit, FALSE); if (nbEights > 0) return findSuitChangingCard(TRUE); if (nbJokers > 0) return findSuitChangingCard(FALSE); } return 99; // pick } byte playComputerTurn() { optDelay(60); byte index = chooseComputerCard(); if (index == 99) { if (numCardsMainDeck == 0) reshuffle(); if (numCardsMainDeck == 0) printEvent("No more cards to be picked."); else { byte pickedCard = pickCardFromMainDeck(); assertf(numComputerCards < NUMCARDS, "%u", numComputerCards); computerHand[numComputerCards++] = pickedCard; if (isPlayableCard(pickedCard)) { printEvent("I pick a card and play it."); optDelay(60); index = numComputerCards - 1; } else { printEvent("I pick a card: not playable."); } } } if (index == 99) return NEXT_PLAYER_PLAYS; // Take the card out of the computer's hand: assertf(index < numComputerCards, "%u, %u", index, numComputerCards); byte chosenCard = computerHand[index]; assertf(numComputerCards > 0 && index < NUMCARDS, "%u, %u", numComputerCards, index); computerHand[index] = computerHand[--numComputerCards]; byte userPasses = playCard(chosenCard, FALSE); if (numComputerCards == 0) { drawAllCards(); #ifdef CARTRIDGE_ROM printEvent("I win."); waitkey(FALSE); return PLAY_NEW_GAME; #else printEvent("I win. Another game (Y/N)?"); byte key = autoMode ? 'Y' : (byte) toupper(waitkey(FALSE)); return key == 'Y' ? PLAY_NEW_GAME : QUIT_GAME; #endif } if (userPasses) return NEXT_PLAYER_PASSES; return NEXT_PLAYER_PLAYS; } #define assertNumCards() assertf(numUserCards + numComputerCards + numCardsMainDeck + numDiscardedCards == NUMCARDS, \ "%u %u %u %u", numUserCards, numComputerCards, numCardsMainDeck, numDiscardedCards) void eights() { for (;;) { initPlayScreen(); initDecks(); assertNumCards(); shuffleMainDeck(); assertNumCards(); // Initialize the two players' hands: byte i; for (i = 8; i > 0; i--) { insertCardInDisplayOrder(userHand, numUserCards, pickCardFromMainDeck()); ++numUserCards; computerHand[numComputerCards++] = pickCardFromMainDeck(); } assertNumCards(); putOrdinaryCardOnTopOfDeck(); discardCard(pickCardFromMainDeck()); requestedSuit = getCardType(displayedCard); if (requestedSuit == SUIT_JOKER) requestedSuit = SUIT_HEARTS; clearEventRow(); drawAllCards(); byte userPasses = FALSE; byte code = NEXT_PLAYER_PLAYS; for (;;) { assertNumCards(); if (userPasses) { code = NEXT_PLAYER_PLAYS; } else { code = playUserTurn(); if (code == QUIT_GAME || code == PLAY_NEW_GAME) break; drawAllCards(); } assertNumCards(); if (code == NEXT_PLAYER_PASSES) { code = NEXT_PLAYER_PLAYS; } else { code = playComputerTurn(); if (code == QUIT_GAME || code == PLAY_NEW_GAME) break; drawAllCards(); userPasses = (code == NEXT_PLAYER_PASSES); } } #ifndef CARTRIDGE_ROM // The cart version does not return from this function. if (code == QUIT_GAME) return; #endif } } /////////////////////////////////////////////////////////////////////////////// // Returns the key pressed by the user to start the game. // byte showPresentation() { byte row = 0; printCentered(++row, PROGRAM_FULL_NAME); ++row; ++row; printCentered(++row, BY_LINE); ++row; ++row; printCentered(++row, "Version " VERSION); // this statement defines the version number printCentered(++row, "Copyright (C) 2003-2024"); ++row; printCentered(++row, COLOR_EIGHTS_URL); printCentered(TEXT_ROWS_PER_SCREEN - 2, "Press [Space] to start."); // Wait for a key while drawing the 8 card in different suits. // word origTimer = getTimer(); setTimer(0); byte key = 0; for (byte prevSuit = SUIT_NONE; key != ' '; key = inkey()) { byte curSuit = (byte) ((getTimer() & 0x00C0) >> 6); if (curSuit != prevSuit) { drawCompiledCard(8, curSuit, 14, 108); prevSuit = curSuit; } } setTimer(getTimer() + origTimer); // allows use of original timer for srand() seed return key; } asm void printUpperCase(const char *str) { #if 0 // Original code: for ( ; *str; ++str) putchar(toupper(*str)); #else asm { ldx 2,s // str (not using U because of 'asm' on function definition) bra printUpperCase_cond printUpperCase_loop cmpa #97 // 'a' blo printUpperCase_putchar cmpa #122 // 'z' bhi printUpperCase_putchar suba #32 // to upper-case printUpperCase_putchar #ifndef CMOC_MONOLITH CHROUT IMPORT #endif jsr [CHROUT,PCR] printUpperCase_cond lda ,x+ // get char bne printUpperCase_loop // loop if not end of string printUpperCase_end } #endif } #ifdef CHECK_NULL void nullPointerHandler(char *addressOfFailedCheck) { moveCursor(0, 0); printf("*** NULL AT %p ***", addressOfFailedCheck); for (;;) ; } #endif int main() { #ifdef CARTRIDGE_ROM asm { // We come here from a JMP $C000 in Color Basic (normally at $A10A in v1.2). // At this point, the 60 Hz interrupt has not been enabled yet, so enable it. lda $ff03 // get control register of PIA0, port B ora #1 sta $ff03 // enable 60 Hz interrupt // Unmask interrupts to allow the timer IRQ to be processed. andcc #$af } #endif void *screenBuffer; #ifdef OS9 { byte err = OS9Timer_init(1); // increment a counter at every 60 Hz tick if (err != 0) { printf("FAILED TO INIT OS-9 TIMER: ERROR #%u\n", err); return 1; } } Keyboard_init(&keyboard); screenBuffer = NULL; #else screenBuffer = (void *) (((word) * (byte *) 0x00BC) << 8); #endif openCardGame(screenBuffer, TRUE); #ifdef CHECK_NULL // Install a null pointer handler. It will only be called if this program // is compiled with --check-null -DCHECK_NULL=1 // set_null_ptr_handler(nullPointerHandler); #endif byte key = showPresentation(); word seed = getTimer(); #if 0 // For debugging: pressing S uses fixed seed. if (toupper(key) == 'S') seed = 1; #endif srand(seed); pcls(0); eights(); closeCardGame(); #ifndef OS9 screen(0, 0); // text mode cls(255); printf("THANK YOU FOR PLAYING\nCOLOR EIGHTS.\n\n" "VERSION: " VERSION "\n" "COPYRIGHT 2003-23\n\n"); printUpperCase(COLOR_EIGHTS_URL); printf("\n\n"); #else putstr("\x12\x0E", 2); // End Graphics, Display Alpha (text mode) #endif //printf("SEED WAS %u.\n", seed); #ifdef OS9 Keyboard_shutdown(&keyboard); { byte err = OS9Timer_shutdown(); if (err != 0) { printf("FAILED TO CLOSE OS-9 TIMER: ERROR #%u\n", err); return 1; } } #endif return 0; }