/* coco-planes.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 "DirtyRectList.h" #include "util.h" #include "Sprite.h" #include "BiplaneMover.h" #include "PreShiftedBitmap.h" #include "ThinBitmap.h" #include "KeyState.h" #include "Score.h" #include "Controller.h" #include "pmode4game.h" /* cardgame library */ #include "Joystick.h" /* bcontrol library */ #if SEED_FROM_USER #include "Keyboard.h" /* bcontrol library */ #endif #if COMPUTE_CHECKSUM #include "crc16.h" /* decbfile library */ #endif #ifdef OS9 #define IF_OS9(os9_value, non_os9_value) os9_value #else #define IF_OS9(os9_value, non_os9_value) non_os9_value #endif typedef void (*NoiseFuncPtr)(void); static void silence(void) { } // Background noise function. // Must preserve U and Y. // NoiseFuncPtr noiseFuncPtr = silence; byte writablePageIndex; // 0..1 index of currently writable page #ifdef STATS word numFlips; word numPrematureFlips; #endif word numFrames = 0; // frame counter // Must be set to setCoCo12ColorSet or setCoCo3ColorSet according // to emulatingPMode4OnCoCo3. // __gcccall void (*setColorSet)(byte colorSet); DirtyRectList dirtyLists[2]; // [0] for page 0, [1] for page 1 // Erases the rectangles in the current dirty list and clears that list. // #define cleanWritablePage() (DirtyRectList_clean(writablePageIndex ? dirtyLists + 1 : dirtyLists)) // samPageNo: SAM address (0..127) of the graphics page to show. // The actual address will be samPageNo * 512. // Assumes that the correct PMODE has already been set up. // void showGraphicsPage(byte samPageNo) { static_assert(page0 == 7 && page1 == 19); // re: optimization in this function assert(samPageNo == page0 || samPageNo == page1); BOOL didSync = FALSE; while (numVSyncsBeforeScreenFlip > 0) // decremented by irqService() at v-sync { asm { sync } didSync = TRUE; } numVSyncsBeforeScreenFlip = VSYNCS_PER_FLIP; if (!didSync) { // We are here because numVSyncsBeforeScreenFlip was zero upon entry // to this function. This means that doMainGameLoop() worked for // too long, i.e., more than 'VSYNCS_PER_FLIP' TV frames. // We tolerate this, but we do a sync instruction here to wait for // the next v-sync, so that the buffer flip happens during the // vertical retrace. Otherwise, we would risk flipping while the // VDG is drawing a screen, which could show as tearing or flickering. // asm { sync } } // Useful to get stats on IRQs per flip. See also irqService(). //beckputchar('F'); //beckputchar('\n'); if (emulatingPMode4OnCoCo3) { // Set the CoCo 3 Vertical offset register. // It receives the absolute address of the screen buffer, divided by 8. // Here, we assume that samPageNo designates an address >= $70000. // * (word *) 0xFF9D = 0xE000 | ((word) samPageNo << 6); } else { // samPageNo is assumed to be either 7 or 19. // 7 is 0000111. // 19 is 0010011. // ^ ^ // bits: 4 2 // Only bits 2 and 4 differ, so we only need to change the words at // $FFC6+2*2 and $FFC6+2*4, i.e., $FFCA and $FFCE. // So instead of calling // setSAMRegisters((byte *) 0xFFC6, samPageNo, 7); // we change only 2 bits of the SAM F register. // if (samPageNo == 7) asm { clr $FFCB // set bit 2 to 1 (use odd adress of the SAM word) clr $FFCE // set bit 4 to 0 (use even address of the SAM word) } else asm { clr $FFCA // set bit 2 to 0 (use even adress of the SAM word) clr $FFCF // set bit 4 to 1 (use odd address of the SAM word) } } #ifdef STATS ++numFlips; if (!didSync) ++numPrematureFlips; #endif } // Sets the BYTES_PER_SCREEN bytes starting at 'screen' to zero. // __gcccall void asm clearScreen(byte *screen) { asm { tfr x,d ; X is 'screen' b/c __gcccall addd #BYTES_PER_SCREEN ; end of region to clear pshs b,a ; push end address clra clrb @loop: std ,x++ std ,x++ std ,x++ std ,x++ std ,x++ std ,x++ std ,x++ std ,x++ std ,x++ std ,x++ std ,x++ std ,x++ std ,x++ std ,x++ std ,x++ std ,x++ cmpx ,s ; reached end? bne @loop leas 2,s ; discard end address } } void showPmode4ColorSet1(void) { if (emulatingPMode4OnCoCo3) { * (byte *) 0xFF90 = 0x7E; // not CoCo compatible mode * (byte *) 0xFF98 = 0x80; // graphics mode * (byte *) 0xFF99 = 0x09; // 192 pixel rows, 32 bytes per row, 4 pixels per byte (i.e., 128x192, 4 colors) * (byte *) 0xFF9A = 0xFF; // white border setCoCo3ColorSet(1); } else { // PMODE 4: byte *pia1bData = (byte *) 0xff22; *pia1bData = *pia1bData & 7 | ((PMODE + 3) << 4); // SCREEN 1,1: setSAMRegisters((byte *) 0xFFC0, PMODE4_SAMV_VALUE, 3); *pia1bData |= 0x88; } } // Uses writablePageIndex. // __gcccall asm byte * getWritableBuffer(void) { #if 0 /* Original C code. */ return writablePageIndex ? grbuf1 : grbuf0; #else asm { tst :writablePageIndex ; 0..1 bne @writingInPage1 ldx #grbuf0 rts @writingInPage1 ldx #grbuf1 @gotBufferPtr } #endif } // Switches 'writablePageIndex' between 0 and 1. // Waits for the v-sync then shows the previously writable page. // void flipDisplayedBuffer(void) { writablePageIndex ^= 1; // If page 1 is now the writable page, then show page 0. // If page 0 is now the writable page, then show page 1. // showGraphicsPage(writablePageIndex ? page0 : page1); setScreenBuffer2(getWritableBuffer()); // for cardgame lib assert(getWritableBuffer() == scrnBuffer); } BOOL gameStarted; Sprite biplane_red; Sprite biplane_blue; byte bulletTimeToLive; // number of frames that a bullet lives for Sprite bullets_red[MAX_BULLETS_PER_PLANE]; Sprite bullets_blue[MAX_BULLETS_PER_PLANE]; Sprite explosions[MAX_EXPLOSIONS]; Sprite balloon; Sprite leftClouds[MAX_CLOUDS]; Sprite rightClouds[MAX_CLOUDS]; byte numFramesBeforeCloudMove; sbyte windDirection; // in pixels word numFramesBeforeBalloonTakeOff; word numBalloonExplosionFramesLeft; BiplaneMover redBiplaneMover; BiplaneMover blueBiplaneMover; Score redScore; Score blueScore; // Array indexed by writablePageIndex. // grPageHasStartPrompt[i] is true iff the start prompt is currently // written on graphics page i (0..1). // BOOL grPageHasStartPrompt[2]; BOOL soundAllowed = TRUE; // FALSE means game sounds muted extern const PreShiftedBitmap biplane_red_00_bm; extern const PreShiftedBitmap biplane_red_01_bm; extern const PreShiftedBitmap biplane_red_02_bm; extern const PreShiftedBitmap biplane_red_03_bm; extern const PreShiftedBitmap biplane_red_04_bm; extern const PreShiftedBitmap biplane_red_05_bm; extern const PreShiftedBitmap biplane_red_06_bm; extern const PreShiftedBitmap biplane_red_07_bm; extern const PreShiftedBitmap biplane_red_08_bm; extern const PreShiftedBitmap biplane_red_09_bm; extern const PreShiftedBitmap biplane_red_10_bm; extern const PreShiftedBitmap biplane_red_11_bm; extern const PreShiftedBitmap biplane_red_12_bm; extern const PreShiftedBitmap biplane_red_13_bm; extern const PreShiftedBitmap biplane_red_14_bm; extern const PreShiftedBitmap biplane_red_15_bm; extern const PreShiftedBitmap biplane_blue_00_bm; extern const PreShiftedBitmap biplane_blue_01_bm; extern const PreShiftedBitmap biplane_blue_02_bm; extern const PreShiftedBitmap biplane_blue_03_bm; extern const PreShiftedBitmap biplane_blue_04_bm; extern const PreShiftedBitmap biplane_blue_05_bm; extern const PreShiftedBitmap biplane_blue_06_bm; extern const PreShiftedBitmap biplane_blue_07_bm; extern const PreShiftedBitmap biplane_blue_08_bm; extern const PreShiftedBitmap biplane_blue_09_bm; extern const PreShiftedBitmap biplane_blue_10_bm; extern const PreShiftedBitmap biplane_blue_11_bm; extern const PreShiftedBitmap biplane_blue_12_bm; extern const PreShiftedBitmap biplane_blue_13_bm; extern const PreShiftedBitmap biplane_blue_14_bm; extern const PreShiftedBitmap biplane_blue_15_bm; const PreShiftedBitmap *biplane_red_bitmaps[NUM_BIPLANE_BITMAPS] = { &biplane_red_00_bm, &biplane_red_01_bm, &biplane_red_02_bm, &biplane_red_03_bm, &biplane_red_04_bm, &biplane_red_05_bm, &biplane_red_06_bm, &biplane_red_07_bm, &biplane_red_08_bm, &biplane_red_09_bm, &biplane_red_10_bm, &biplane_red_11_bm, &biplane_red_12_bm, &biplane_red_13_bm, &biplane_red_14_bm, &biplane_red_15_bm, }; const PreShiftedBitmap *biplane_blue_bitmaps[NUM_BIPLANE_BITMAPS] = { &biplane_blue_08_bm, &biplane_blue_07_bm, &biplane_blue_06_bm, &biplane_blue_05_bm, &biplane_blue_04_bm, &biplane_blue_03_bm, &biplane_blue_02_bm, &biplane_blue_01_bm, &biplane_blue_00_bm, &biplane_blue_15_bm, &biplane_blue_14_bm, &biplane_blue_13_bm, &biplane_blue_12_bm, &biplane_blue_11_bm, &biplane_blue_10_bm, &biplane_blue_09_bm, }; extern const PreShiftedBitmap bullet_bm; extern const PreShiftedBitmap explosion0_bm; extern const PreShiftedBitmap explosion1_bm; extern const PreShiftedBitmap balloon_bm; extern const PreShiftedBitmap cloud_left_bm; extern const PreShiftedBitmap cloud_right_bm; extern const ThinBitmap digit0_bm; extern const ThinBitmap digit1_bm; extern const ThinBitmap digit2_bm; extern const ThinBitmap digit3_bm; extern const ThinBitmap digit4_bm; extern const ThinBitmap digit5_bm; extern const ThinBitmap digit6_bm; extern const ThinBitmap digit7_bm; extern const ThinBitmap digit8_bm; extern const ThinBitmap digit9_bm; const ThinBitmap *digitBitmaps[10] = // each digit bitmap is 8x5 pixels, 12 bytes each { &digit0_bm, &digit1_bm, &digit2_bm, &digit3_bm, &digit4_bm, &digit5_bm, &digit6_bm, &digit7_bm, &digit8_bm, &digit9_bm, }; extern const ThinBitmap space_bm; extern const ThinBitmap minus_bm; KeyState muteKeyState = { KEY_PROBE_M, KEY_BIT_M, FALSE }; enum { JOY_RIGHT_Y_AXIS = 1, JOY_LEFT_Y_AXIS = 3 }; // 0..3 enum { JOY_AXIS_LOW_THR = 16, JOY_AXIS_HIGH_THR = 48 }; // 0..63 enum { JOY_UP = +1, JOY_DOWN = -1, JOY_MIDDLE = 0 }; enum { JOY_BUTTON_RIGHT_MASK = 1, JOY_BUTTON_LEFT_MASK = 2 }; // 1st button of each joystick sbyte rightJoystickVerticalPos = JOY_MIDDLE; sbyte leftJoystickVerticalPos = JOY_MIDDLE; byte joystickButtonPreviousStates = 0xFF; // test with JOY_BUTTON_*_MASK byte joystickButtonStates = 0xFF; // test with JOY_BUTTON_*_MASK #if SEED_FROM_USER Keyboard keyboard; #endif Controller redBiplaneController; Controller blueBiplaneController; // 16xTOWER_HEIGHT grid of pixels. // const word tower_pixels[TOWER_HEIGHT] = { 0b1111111111111111, 0b0011000000001100, 0b0011000000001100, 0b0011000000001100, 0b0011111111111100, 0b0011111111111100, 0b0000110000110000, 0b0011111111111100, 0b0011000000001100, 0b0011000000001100, 0b0011000000001100, 0b0011000000001100, 0b0011111111111100, 0b0011000000001100, 0b0011000000001100, 0b0011000000001100, 0b0011000000001100, }; void asm drawTower(void) { #if 0 /* Original C code. */ word *writer = (word *) (getWritableBuffer() + (BYTES_PER_SCREEN - TOWER_HEIGHT * BYTES_PER_ROW + BYTES_PER_ROW / 2 - 1)); for (byte i = 0; i < TOWER_HEIGHT; ++i, writer += BYTES_PER_ROW / 2) { assert((word) writer - (word) getWritableBuffer() < 6144); *writer = tower_pixels[i]; } #else asm { lbsr getWritableBuffer ; point X to start of current graphics buffer OFFSET equ BYTES_PER_SCREEN_-TOWER_HEIGHT*BYTES_PER_ROW+BYTES_PER_ROW/2-1 leax OFFSET,x ; X is 'writer' IF_OS9(pshs y, ;) leay :tower_pixels ; under OS-9, cannot refer to global C vars after this ldb #TOWER_HEIGHT ; number of words to copy pshs b ; word counter in stack @loop ldd ,y++ ; load a word of pixels std ,x ; write to graphics buffer leax BYTES_PER_ROW,x ; point to next pixel row dec ,s ; dec word counter bne @loop ; loop if more words to copy ; leas 1,s ; discard word counter IF_OS9(puls y, ;) } #endif } // Returns the address of a Sprite in the given array whose 'active' field is FALSE. // If none is found, returns NULL. // Sprite * findInactiveSprite(Sprite sprites[], byte numSprites) { for (byte i = 0; i < numSprites; ++i) { Sprite *s = &sprites[i]; assert(s); if (!s->active) return s; } return NULL; } void initBiplaneSprite(Sprite *biplane, const PreShiftedBitmap *bitmapArray[], byte initBitmapIndex, byte initX) { assert(biplane); assert(bitmapArray); assert(initBitmapIndex < NUM_BIPLANE_BITMAPS); assert(initX >= 2 && initX + SPRITE_WIDTH + 2 <= COLS_PER_SCREEN); const PreShiftedBitmap *bm = bitmapArray[initBitmapIndex]; assert(bm->height == BIPLANE_HEIGHT); Sprite_init(biplane, bm); biplane->x = initX; biplane->y = ROWS_PER_SCREEN - bm->height / 2 - bm->height; biplane->bitmapIndex = initBitmapIndex; } // Draws to the buffer given by getWritableBuffer(). // Does nothing if s->active is FALSE. // Calls noiseFuncPtr while drawing (if soundAllowed is non-zero): // That function can be used for background noise. // __gcccall void drawSprite(const Sprite *s) { if (!s->active) return; assert(s->x >= 2 && s->x <= COLS_PER_SCREEN - 2 - SPRITE_WIDTH); assert(s->bm); assert(s->h > 0); byte spriteY = s->y; byte spriteHeight = s->h; byte numSkippedRows = 0; if (spriteY >= ROWS_PER_SCREEN) { // spriteY considered negative (-64..-1). if (- (sbyte) spriteY >= (sbyte) spriteHeight) return; // nothing to do: sprite completely above screen spriteHeight += spriteY; // decrease spriteHeight, to only draw rows that are on screen numSkippedRows = - spriteY; // skip the first rows of the bitmap spriteY = 0; // start writing at row 0 of screen } // y is in 0..191. // Compute the byte offset of the first affected screen byte. // Assumes PMODE 4. // byte *firstChangedAddr = getWritableBuffer() + ((word) spriteY << 5) + (word) (s->x >> 3); assert(((word) firstChangedAddr & 0x001F) <= 29); // check not too far at right byte shiftIndex = (byte) (s->x & 0b110u) >> 1; // 0..3 word preShiftOffset = s->bm->preShiftOffsets[shiftIndex]; const byte *preShiftedBytes = s->bm->bytes + preShiftOffset + numSkippedRows * BYTES_PER_BITMAP_ROW; byte *dest = firstChangedAddr; byte i = 0; // row index (0 .. spriteHeight - 1). #define drawSprite_asm #ifndef drawSprite_asm /* Original C code. (Very slow.) */ for (;;) { word screenWord = * (word *) dest; screenWord &= * (word *) preShiftedBytes; // AND with high word of mask screenWord |= * (word *) (preShiftedBytes + 3); // OR with high word of image * (word *) dest = screenWord; byte screenByte = dest[2]; screenByte &= preShiftedBytes[2]; screenByte |= preShiftedBytes[5]; dest[2] = screenByte; if (++i >= spriteHeight) break; dest += BYTES_PER_ROW, preShiftedBytes += BYTES_PER_BITMAP_ROW; } #else /* Inline asssembly language version. */ asm { IF_OS9(pshs y, ;) ldy :preShiftedBytes ldx :dest @loop ldd ,x ; screenWord anda ,y andb 1,y ora 3,y orb 4,y std ,x ; lda 2,x ; screenByte anda 2,y ora 5,y sta 2,x ; inc :i ldb :i cmpb :spriteHeight bhs @done ; leax BYTES_PER_ROW,x ; advance dest leay BYTES_PER_BITMAP_ROW,y ; advance preShiftedBytes ; tst :soundAllowed beq @skipNoise pshs x jsr [:noiseFuncPtr] ; trashes D, X; preserves U, Y puls x @skipNoise bra @loop @done IF_OS9(puls y, ;) } #endif if (!DirtyRectList_add(&dirtyLists[writablePageIndex], firstChangedAddr, spriteHeight)) assert(!"TOO MANY DIRTY RECTS"); } __gcccall void drawSpriteList(const Sprite spriteList[], byte numSprites) { for (byte i = 0; i < numSprites; ++i, ++spriteList) drawSprite(spriteList); } // x: Digit position (one digit per byte). // Writes at row THIN_BITMAP_Y_POS. // __gcccall void drawThinBitmap(byte x, const ThinBitmap *bitmap) { #if 0 /* Original C code. */ byte *p = getWritableBuffer() + ((word) THIN_BITMAP_Y_POS << 5) + x; const byte *src = bitmap->bytes; for (byte row = 0; row < bitmap->height; ++row) { *p = *src; ++src; p += BYTES_PER_ROW; } #else asm { IF_OS9(pshs y, ;) lbsr getWritableBuffer ; address received in X leax THIN_BITMAP_Y_POS*BYTES_PER_ROW,x ; point to left of top pixel row of score ldb :x abx ; ldy :bitmap ; must not refer to C globals while Y is modified ldb ,y ; counter init w/ bitmap->height leay 1,y ; src = bitmap->bytes @loop lda ,y+ ; load from src sta ,x ; write at p leax BYTES_PER_ROW,x ; point to row below decb ; another row to do? bne @loop ; branch if yes IF_OS9(puls y, ;) } #endif } // horizPos: 0..31. // __gcccall void drawScore(const Score *score, byte horizPos, BOOL leftJustified) { byte tens = score->digits[0]; byte units = score->digits[1]; if (tens == 0) { if (leftJustified) { drawThinBitmap(horizPos, digitBitmaps[units]); drawThinBitmap(horizPos + 1, &space_bm); } else { drawThinBitmap(horizPos, &space_bm); drawThinBitmap(horizPos + 1, digitBitmaps[units]); } } else { drawThinBitmap(horizPos, digitBitmaps[tens]); drawThinBitmap(horizPos + 1, digitBitmaps[units]); } } __gcccall void drawChars(const char *str) { for ( ; *str; ++str) drawChar((unsigned char) *str); } void drawStartPrompt(const char *line0, const char *line1) { makeSpacesTransparent(FALSE); moveCursor(START_PROMPT_COL, START_PROMPT_ROW); drawChars(line0); moveCursor(START_PROMPT_COL, START_PROMPT_ROW + 1); drawChars(line1); makeSpacesTransparent(TRUE); } void showStartPrompt(void) { drawStartPrompt("PRESS A PLANE'S FIRE", "BUTTON TO START IT. "); } void eraseStartPrompt(void) { drawStartPrompt(" ", " "); } void drawInWritablePage(void) { drawTower(); // TODO (if needed for perf): Only call this when tower region is dirty. drawSprite(&balloon); drawSprite(&biplane_red); drawSprite(&biplane_blue); drawSpriteList(bullets_red, ARRAY_SIZE(bullets_red)); drawSpriteList(bullets_blue, ARRAY_SIZE(bullets_blue)); drawSpriteList(explosions, ARRAY_SIZE(explosions)); drawSpriteList(leftClouds, ARRAY_SIZE(leftClouds)); drawSpriteList(rightClouds, ARRAY_SIZE(rightClouds)); // Show the start prompt if needed. // assert(getWritableBuffer() == scrnBuffer); if (!gameStarted && !grPageHasStartPrompt[writablePageIndex]) { showStartPrompt(); grPageHasStartPrompt[writablePageIndex] = TRUE; } else if (gameStarted && grPageHasStartPrompt[writablePageIndex]) { eraseStartPrompt(); grPageHasStartPrompt[writablePageIndex] = FALSE; } drawScore(&redScore, 1, TRUE); drawScore(&blueScore, 29, FALSE); } // Returns TRUE if the x field was changed, or FALSE if it remains unchanged // because the move would have taken the sprite out of bounds. // __gcccall BOOL addXSpeedToSpritePos(Sprite *sprite) { sword newValue = (sword) sprite->x + (sword) sprite->dx; if (newValue < 0) return FALSE; if (newValue + SPRITE_WIDTH > COLS_PER_SCREEN - 2) // - 2 to avoid rightmost pos return FALSE; sprite->x = (byte) newValue; return TRUE; } // Random values that approximate white noise. // Bits 0 and 1 are zero in each byte. // const byte randomSoundSamples[256] = { 0x94, 0x9c, 0x74, 0x70, 0x80, 0x7c, 0x68, 0x6c, 0x80, 0x88, 0x68, 0x58, 0xa0, 0x8c, 0x5c, 0xa0, 0x5c, 0x80, 0xa8, 0x6c, 0xa4, 0x7c, 0xa0, 0xa4, 0x8c, 0x60, 0xa4, 0x80, 0x88, 0x68, 0x6c, 0x98, 0x74, 0x94, 0x68, 0x94, 0x70, 0xa4, 0x64, 0x88, 0x6c, 0x94, 0x60, 0x94, 0x74, 0x84, 0x60, 0xa0, 0x84, 0x80, 0x80, 0x88, 0x74, 0x6c, 0x64, 0x74, 0x84, 0x88, 0x8c, 0x80, 0x8c, 0x8c, 0x7c, 0x88, 0x74, 0x78, 0x68, 0x68, 0x84, 0x6c, 0x88, 0x6c, 0x84, 0x80, 0x6c, 0x80, 0x94, 0x80, 0x64, 0x98, 0x9c, 0x70, 0x60, 0x70, 0x7c, 0x98, 0x8c, 0x5c, 0xa4, 0x70, 0x8c, 0xa0, 0x70, 0x98, 0x88, 0x8c, 0x74, 0x88, 0x9c, 0x88, 0x68, 0x78, 0x70, 0x98, 0x74, 0x6c, 0x84, 0x88, 0x88, 0x64, 0x74, 0x64, 0xa0, 0x84, 0x80, 0x84, 0x64, 0xa0, 0x5c, 0x84, 0xa8, 0x84, 0x98, 0xa4, 0x7c, 0x60, 0x58, 0xa4, 0xa4, 0x90, 0x88, 0x5c, 0x60, 0x64, 0x64, 0x60, 0x80, 0x60, 0x84, 0x80, 0x88, 0xa8, 0x90, 0x7c, 0x94, 0x60, 0x74, 0x9c, 0xa0, 0xa0, 0x9c, 0x84, 0x74, 0x80, 0x58, 0x84, 0x60, 0x90, 0x60, 0x7c, 0x5c, 0xa4, 0x88, 0x84, 0x74, 0xa0, 0x64, 0x78, 0xa0, 0x7c, 0x80, 0x7c, 0x6c, 0x70, 0x94, 0x88, 0x6c, 0x60, 0xa0, 0xa0, 0x84, 0x80, 0x90, 0xa0, 0x6c, 0x7c, 0x64, 0x88, 0x5c, 0x68, 0x7c, 0x88, 0x68, 0x64, 0x9c, 0x88, 0x80, 0x70, 0x78, 0x78, 0xa0, 0x98, 0x5c, 0xa0, 0x80, 0x90, 0x90, 0x80, 0x7c, 0xa4, 0x84, 0x68, 0x84, 0x90, 0x68, 0x68, 0xa0, 0x8c, 0x64, 0x88, 0x90, 0x80, 0x5c, 0x5c, 0x94, 0x80, 0x60, 0x5c, 0x64, 0x90, 0x70, 0xa0, 0x7c, 0x98, 0x6c, 0x64, 0x80, 0x70, 0x7c, 0x88, 0x88, 0x84, 0x70, 0x9c, 0x88, 0x68, 0xa4, 0x70, 0x74, 0x8c, 0x94, 0xa8, 0x6c, 0x64, 0x74, 0x8c, }; sbyte randomSoundSampleIndex = 0; // signed index into randomSoundSamples[] (-128..127) // Plays the byte designated by randomSoundSamples[randomSoundSampleIndex]. // Increments randomSoundSampleIndex for the next call. // Preserves U and Y. // Assumes that randomSoundSamples[] has 256 elements. // void asm playExplosionSoundSample(void) { asm { leax :randomSoundSamples[128] ; middle of table ldb :randomSoundSampleIndex ; signed index lda b,x sta $FF20 ; write to PIA1 incb ; rolls over after 127, so stays in -128..127 stb :randomSoundSampleIndex } } // Starts an explosion in the middle of 'destroyedSprite'. // Returns the explosion that got started, if there is room for an additional explosion. // Returns NULL if no explosion could be started. // __gcccall Sprite * startExplosion(const Sprite *destroyedSprite) { Sprite *explosion = findInactiveSprite(explosions, MAX_EXPLOSIONS); if (!explosion) { assert(!"TOO MANY EXPL"); return NULL; } Sprite_init(explosion, &explosion0_bm); explosion->x = destroyedSprite->x; // Position explosion center at center of destroyedSprite. explosion->y = destroyedSprite->y + (destroyedSprite->h - explosion->h) / 2; explosion->timeToLive = FRAMES_PER_EXPLOSION; // explosion will live for this many frames noiseFuncPtr = playExplosionSoundSample; return explosion; } // (x1, y1, height1) is the bounding rectangle of the first sprite. // (x2, y2, height2) is the bounding rectangle of the second sprite. // The width of the 2nd sprite is given by width2. // All arguments are signed. // BOOL areSpriteRectanglesColliding(sword x1, sword y1, sword height1, sword x2, sword y2, sword height2, byte width2) { if (x1 + SPRITE_WIDTH <= x2) // if sprite 1 at left of sprite 2 return FALSE; if (y1 + height1 <= y2) // if sprite 1 above sprite 2 return FALSE; if (x2 + width2 <= x1) // if sprite 1 at right of sprite 2 return FALSE; if (y2 + height2 <= y1) // if sprite 1 below sprite 2 return FALSE; return TRUE; } #if 0 // Not used. // Upon a collision, an explosion is started at the position of sprite 'a', // and both sprites are marked as inactive. // Does not check if 'a' or 'b' are currently active. // Returns TRUE iff a collision was detected. // BOOL detectCollision2Sprites(Sprite *a, Sprite *b) { if (!areSpriteRectanglesColliding(a->x, signExtendYPos(a->y), a->h, b->x, signExtendYPos(b->y), b->h, SPRITE_WIDTH)) return FALSE; //startExplosion(a); a->active = FALSE; b->active = FALSE; return TRUE; } // Adds (hundreds, tens, units) to the score for each detected collision. // bcdValue: Binary-coded decimal value between 0x000 and 0x999. // 'other' is passed to detectCollision2Sprites() as the 2nd argument. // BOOL detectCollisionWithSpriteList(Sprite sprites[], byte numSprites, Sprite *other, byte scoreIndex) { BOOL collisionDetected = FALSE; for (byte i = 0; i < numSprites; ++i) { Sprite *s = &sprites[i]; if (s->active) { if (detectCollision2Sprites(s, other)) { collisionDetected = TRUE; } } } return collisionDetected; } #endif void detectBulletOnPlane(Controller *controller, Sprite *bullet, Score *shooterScore) { if (!bullet->active) return; BiplaneMover *mover = controller->mover; if (!mover->hasStarted) return; Sprite *biplane = mover->biplane; if (!biplane->active) return; if (!areSpriteRectanglesColliding(biplane->x, biplane->y, biplane->h, bullet->x + BULLET_MARGIN, bullet->y, bullet->h, BULLET_WIDTH)) // re: bullet.bm return; startExplosion(biplane); biplane->active = FALSE; Controller_onBiplaneExplosion(controller); // Wait until after explosion finished to respawn the plane. // mover->numFramesBeforeSpawn = FRAMES_PER_EXPLOSION; bullet->active = FALSE; Score_addPoint(shooterScore); } void detectBulletOnBalloon(Sprite *bullet, Score *shooterScore) { if (!bullet->active || !balloon.active || numFramesBeforeBalloonTakeOff > 0) return; if (!areSpriteRectanglesColliding(balloon.x, balloon.y, balloon.h, bullet->x + BULLET_MARGIN, bullet->y, bullet->h, BULLET_WIDTH)) // re: bullet.bm return; startExplosion(&balloon); balloon.active = FALSE; // Wait until after explosion finished to respawn the balloon. // numBalloonExplosionFramesLeft = FRAMES_PER_EXPLOSION; bullet->active = FALSE; Score_addPoint(shooterScore); } void detectPlaneOnTower(Controller *controller, Score *otherPlayerScore) { BiplaneMover *mover = controller->mover; if (!mover->hasStarted) return; Sprite *biplane = mover->biplane; if (!biplane->active) return; if (!areSpriteRectanglesColliding(biplane->x, biplane->y, biplane->h, TOWER_LEFT_X, TOWER_TOP_Y, TOWER_HEIGHT, TOWER_WIDTH)) // re: tower_pixels[] return; startExplosion(biplane); biplane->active = FALSE; Controller_onBiplaneExplosion(controller); // Wait until after explosion finished to respawn the plane. // mover->numFramesBeforeSpawn = FRAMES_PER_EXPLOSION; Score_addPoint(otherPlayerScore); } void detectBulletOnTower(Sprite *bullet) { if (!bullet->active) return; if (!areSpriteRectanglesColliding(TOWER_LEFT_X, TOWER_TOP_Y, TOWER_HEIGHT, bullet->x + BULLET_MARGIN, bullet->y, bullet->h, BULLET_WIDTH)) // re: bullet.bm return; bullet->active = FALSE; } void detectCollisions(void) { Sprite *blueBullet = bullets_blue; Sprite * const bullets_blue_end = bullets_blue + MAX_BULLETS_PER_PLANE; Sprite *redBullet = bullets_red; for ( ; blueBullet < bullets_blue_end; ++blueBullet, ++redBullet) { detectBulletOnPlane(&redBiplaneController, blueBullet, &blueScore); detectBulletOnPlane(&blueBiplaneController, redBullet, &redScore); detectBulletOnBalloon(blueBullet, &blueScore); detectBulletOnBalloon(redBullet, &redScore); detectBulletOnTower(blueBullet); detectBulletOnTower(redBullet); } detectPlaneOnTower(&redBiplaneController, &blueScore); detectPlaneOnTower(&blueBiplaneController, &redScore); } BOOL isExplosionActive(void) { for (byte i = 0; i < MAX_EXPLOSIONS; ++i) if (explosions[i].active) return TRUE; return FALSE; } __gcccall void animateBullet(Sprite *bullet) { if (!bullet->active) return; if (bullet->timeToLive == 0) { bullet->active = FALSE; // time to live over return; } --bullet->timeToLive; sword newX = (sword) bullet->x + bullet->dx; if (newX > COLS_PER_SCREEN - 2 - SPRITE_WIDTH) // if past rightmost allowed pos newX = 2; // reposition at leftmost allowed pos else if (newX < 2) newX = COLS_PER_SCREEN - 2 - SPRITE_WIDTH; sword newY = (sword) bullet->y + bullet->dy; if (newY < 0 || newY + bullet_bm.height > ROWS_PER_SCREEN) { bullet->active = FALSE; // went out at top/bottom of screen return; } bullet->x = (byte) newX; bullet->y = (byte) newY; } void animateBullets(void) { Sprite *redBullet = bullets_red; Sprite *bullets_red_end = bullets_red + ARRAY_SIZE(bullets_red); Sprite *blueBullet = bullets_blue; for ( ; redBullet < bullets_red_end; ++redBullet, ++blueBullet) { animateBullet(redBullet); animateBullet(blueBullet); } } void animateExplosions(void) { byte bitmapIndex = (byte) numFrames & 1; BOOL atLeastOneExplosion = FALSE; for (byte i = 0; i < MAX_EXPLOSIONS; ++i) { Sprite *e = &explosions[i]; if (!e->active) continue; if (--e->timeToLive == 0) // if time to live goes to 0 { e->active = FALSE; continue; } e->bm = (bitmapIndex ? &explosion1_bm : &explosion0_bm); if (e->dx != 0 && !addXSpeedToSpritePos(e)) // if going off screen { e->active = FALSE; continue; } atLeastOneExplosion = TRUE; if (e->dy < 0) // if explosion moving up e->y = (byte) (e->dy + signExtendYPos(e->y)); } if (!atLeastOneExplosion) noiseFuncPtr = silence; // stop playing explosion sound } void initBalloon(void) { Sprite_init(&balloon, &balloon_bm); balloon.x = (COLS_PER_SCREEN - SPRITE_WIDTH) / 2; balloon.y = TOWER_TOP_Y - 1 - balloon_bm.height; numFramesBeforeBalloonTakeOff = rnd(MIN_BALLOON_TAKE_OFF_TIME, MAX_BALLOON_TAKE_OFF_TIME); numBalloonExplosionFramesLeft = 0; } enum { BALLOON_UP_AND_LEFT, BALLOON_UP_AND_RIGHT, BALLOON_UP }; byte prevBalloonDirection = BALLOON_UP; byte numFramesBeforeBallonDirChange = FRAMES_PER_BALLON_DIR_CHANGE; void animateBalloon(void) { if (!balloon.active) { if (numBalloonExplosionFramesLeft > 0) // if balloon exploding { --numBalloonExplosionFramesLeft; return; // left explosion continue } // Balloon explosion has finished, so create new one. initBalloon(); return; } if (!gameStarted) return; if (numFramesBeforeBalloonTakeOff > 0) { --numFramesBeforeBalloonTakeOff; return; // not time to take off yet } if ((byte) numFrames & 1) return; // only move balloon every 2 frames, to make it slow // Balloon is in flight. Move it up. // balloon.y is allowed to go below 0, in signed terms, because // drawSprite() will do the needed clipping. // --balloon.y; if (balloon.y >= ROWS_PER_SCREEN && balloon.y <= (byte) -BALLOON_HEIGHT) // if entirely above screen { initBalloon(); // put balloon back on tower; reinit numFramesBeforeBalloonTakeOff return; } byte direction; // BALLOON_* if (numFramesBeforeBallonDirChange > 0) // if not time to change direction { --numFramesBeforeBallonDirChange; direction = prevBalloonDirection; // reuse previous direction } else { direction = generateRandomTayste(); // get new direction randomly if (direction == BALLOON_UP_AND_LEFT && prevBalloonDirection == BALLOON_UP_AND_RIGHT) direction = BALLOON_UP; // avoid going right just after going left else if (direction == BALLOON_UP_AND_RIGHT && prevBalloonDirection == BALLOON_UP_AND_LEFT) direction = BALLOON_UP; // avoid going left just after going right else if (direction == 3) // 4th value is also "up" direction = BALLOON_UP; numFramesBeforeBallonDirChange = FRAMES_PER_BALLON_DIR_CHANGE; } switch (direction) { case BALLOON_UP_AND_LEFT: if (balloon.x > 2) balloon.x -= 2; break; case BALLOON_UP_AND_RIGHT: if (balloon.x < COLS_PER_SCREEN - 2 - SPRITE_WIDTH) balloon.x += 2; break; } prevBalloonDirection = direction; } void initNumFramesBeforeCloudMove(void) { numFramesBeforeCloudMove = (byte) rnd(50, 100); } void animateClouds(void) { if (numFramesBeforeCloudMove > 0) { --numFramesBeforeCloudMove; return; } initNumFramesBeforeCloudMove(); for (byte i = 0; i < MAX_CLOUDS; ++i) { Sprite *lc = &leftClouds[i]; sword newX = (sword) lc->x + windDirection; if (newX < 2) newX = COLS_PER_SCREEN - 2 - SPRITE_WIDTH * 2; else if (newX > COLS_PER_SCREEN - 2 - SPRITE_WIDTH * 2) newX = 2; assert(newX >= 2 && newX <= COLS_PER_SCREEN - 2 - SPRITE_WIDTH * 2); lc->x = (byte) newX; rightClouds[i].x = (byte) newX + SPRITE_WIDTH; } } // Returns the index in bulletArray[] of the first inactive Sprite. // Returns MAX_BULLETS_PER_PLANE if none is found. // byte getFreeBulletSpotIndex(const Sprite bulletArray[MAX_BULLETS_PER_PLANE]) { byte i; for (i = 0; i < MAX_BULLETS_PER_PLANE; ++i) if (!bulletArray[i].active) break; return i; } typedef struct SpeedVector { sbyte dx, dy; } SpeedVector; // Couples of the form 4 * cos(angle), 4 * -sin(angle). // (Y axis points down.) // The angle is the bitmap index (0..15) times 22.5 degrees (0, 22.5, 45, ..., 337.5). // The horizontal speeds are rounded to the nearest even number. // Allowing odd speeds would allow the sprite to be displayed starting at // an odd horizontal position, which in PMODE 4 may change the sprite's colors // because of that graphics mode's NTSC artifact colors. // const SpeedVector bulletSpeedVectors[NUM_BIPLANE_BITMAPS] = { { 9, 0 }, // 0.0 degrees { 8, 3 }, // 22.5 degrees { 6, 6 }, // 45.0 degrees { 3, 8 }, // 67.5 degrees { -0, 9 }, // 90.0 degrees { -3, 8 }, // 112.5 degrees { -6, 6 }, // 135.0 degrees { -8, 3 }, // 157.5 degrees { -9, -0 }, // 180.0 degrees { -8, -3 }, // 202.5 degrees { -6, -6 }, // 225.0 degrees { -3, -8 }, // 247.5 degrees { 0, -9 }, // 270.0 degrees { 3, -8 }, // 292.5 degrees { 6, -6 }, // 315.0 degrees { 8, -3 }, // 337.5 degrees }; static const byte bulletSound[] = { 0xFC, 0x04, 0xFC, 0x04 }; // Does nothing if 'biplane' is inactive or if no room in bulletArray[]. // void fireBullet(const Sprite *biplane, Sprite bulletArray[MAX_BULLETS_PER_PLANE]) { assert(biplane); if (!biplane->active) return; // Search for a free spot in the bullet array. // byte i = getFreeBulletSpotIndex(bulletArray); if (i == MAX_BULLETS_PER_PLANE) return; // no room Sprite *bullet = &bulletArray[i]; const SpeedVector *speed = &bulletSpeedVectors[biplane->bitmapIndex]; Sprite_init(bullet, &bullet_bm); // Put the bullet at the nose of the plane. // The position of the nose depends on the 'speed' vector. // The (x, y) position of the plane is the top-left pixel of // the rectangle that encloses the plane bitmap. // The minus 6 is because the bullet sprite is 16x2 but that // bullet is a 4x2 subrectangle in the middle, and (16 - 4) / 2 = 6. // bullet->x = biplane->x + SPRITE_WIDTH / 2 + speed->dx - 6; bullet->y = biplane->y + BIPLANE_HEIGHT / 2 - speed->dy; bullet->dx = speed->dx; bullet->dy = - speed->dy; bullet->timeToLive = bulletTimeToLive; if (soundAllowed) playSoundSample(bulletSound, ARRAY_END(bulletSound), 20); } BOOL checkForKey(byte probe, byte testBit) { if (!isKeyPressed(probe, testBit)) return FALSE; while (isKeyPressed(probe, testBit)) ; return TRUE; } void checkForMute(void) { if (KeyState_update(&muteKeyState)) soundAllowed = !soundAllowed; } #ifndef NDEBUG enum { DEBUG_BUFFER_SIZE = 1024 }; char debugBuffer[DEBUG_BUFFER_SIZE]; size_t debugBufferIndex = 0; void printDebugChar(void) { asm { pshs u,y,x,b,a ldd :debugBufferIndex cmpd #DEBUG_BUFFER_SIZE-1 ; reserve last byte of buffer for terminating NUL bhs @done leax :debugBuffer leax d,x addd #1 std :debugBufferIndex ; for next call lda ,s ; char to write sta ,x @done puls a,b,x,y,u } } #endif BOOL inFailedAssert = FALSE; void onFailedAssert(const char *file, int lineno, const char *condition) { if (inFailedAssert) return; // in case the following code asserts, avoid infinite loop inFailedAssert = TRUE; (*setColorSet)(0); // switch to green/black in case error msg not visible moveCursor(0, 0); // cardgame library function makeSpacesTransparent(FALSE); printf("*** FAILED ASSERT: %s:%d: %s\n", file, lineno, condition); flipDisplayedBuffer(); for (;;) ; } void waitForKeyRelease(byte probe, byte testBit) { while (isKeyPressed(probe, testBit)) ; } #if 0 void waitForKeyPressAndRelease(byte probe, byte testBit) { while (! isKeyPressed(probe, testBit)) ; waitForKeyRelease(probe, testBit); } #endif BOOL isKeyPressedAndReleased(byte probe, byte testBit) { if (isKeyPressed(probe, testBit)) { waitForKeyRelease(probe, testBit); return TRUE; } return FALSE; } void updateJoystickButtons(void); // Waits for a key that corresponds to the commands offered by the pause screen. // // allowResume: Allow resuming the game. Should be FALSE at first, and when // a game has just finished. // // The next parameters are only used when allowResume is FALSE. // // (colNumPlayers, rowNumPlayers): Position on the text screen where '1' or '2' // is displayed to indicate the number of players // in the next game. // (colNumPlayers, rowControlType): Position where 'K' or 'J' is displayed to indicate // keyboard or joystick control. // (colNumPlayers, rowBulletRange): Position where 'S' or 'L' is displayed to indicate // short-range or long-range bullet. // numPlayers: Must point to a byte that receives 1 or 2 (value, not character) // when key 1 or 2 is pressed. // controlType: Must point to a byte that receives JOYSTICK_CONTROLLER or // KEYBOARD_CONTROLLER when key J or K is pressed. // // Modifies bulletTimeToLive if a bullet range key (S or L) is pressed. // // Returns ' ', 'R' or 'I'. // byte waitForGamePauseKey(BOOL allowResume, byte colNumPlayers, byte rowNumPlayers, byte rowControlType, byte rowBulletRange, byte *numPlayers, byte *controlType) { for (;;) { updateJoystickButtons(); if (allowResume && isKeyPressedAndReleased(KEY_PROBE_R, KEY_BIT_R)) { return 'R'; } if (isKeyPressedAndReleased(KEY_PROBE_SPACE, KEY_BIT_SPACE) || (~joystickButtonPreviousStates & joystickButtonStates)) // if space bar or joystick button clicked { return ' '; } if (!allowResume) // if presentation screen, or game over: { if (isKeyPressedAndReleased(KEY_PROBE_1, KEY_BIT_1)) { moveCursor(colNumPlayers, rowNumPlayers); drawChar('1'); *numPlayers = 1; continue; } if (isKeyPressedAndReleased(KEY_PROBE_2, KEY_BIT_2)) { moveCursor(colNumPlayers, rowNumPlayers); drawChar('2'); *numPlayers = 2; continue; } if (isKeyPressedAndReleased(KEY_PROBE_J, KEY_BIT_J)) { moveCursor(colNumPlayers, rowControlType); drawChar('J'); *controlType = JOYSTICK_CONTROLLER; continue; } if (isKeyPressedAndReleased(KEY_PROBE_K, KEY_BIT_K)) { moveCursor(colNumPlayers, rowControlType); drawChar('K'); *controlType = KEYBOARD_CONTROLLER; continue; } if (isKeyPressedAndReleased(KEY_PROBE_S, KEY_BIT_S)) { moveCursor(colNumPlayers, rowBulletRange); drawChar('S'); bulletTimeToLive = FRAMES_PER_SHORT_RANGE_BULLET; continue; } if (isKeyPressedAndReleased(KEY_PROBE_L, KEY_BIT_L)) { moveCursor(colNumPlayers, rowBulletRange); drawChar('L'); bulletTimeToLive = FRAMES_PER_LONG_RANGE_BULLET; continue; } } if (isKeyPressedAndReleased(KEY_PROBE_I, KEY_BIT_I)) // show instructions { return 'I'; } if (isKeyPressed(KEY_PROBE_CLEAR, KEY_BIT_CLEAR) // cold boot && isKeyPressed(KEY_PROBE_BREAK, KEY_BIT_BREAK)) { waitForKeyRelease(KEY_PROBE_CLEAR, KEY_BIT_CLEAR); waitForKeyRelease(KEY_PROBE_BREAK, KEY_BIT_BREAK); coldBoot(); } } } // Prints to the graphics page designated by writablePageIndex, at the current // text row (textPosY). // Clears the dirty rectangle list. // x: Even pixel position on the text row given by textPosY. Must be in 0..238. // newline: If non-zero, advances textPosY after drawing the bitmap. // void printBitmap(byte x, BOOL newline, const PreShiftedBitmap *bm) { assert(textPosY * PIXEL_ROWS_PER_TEXT_ROW + bm->height <= ROWS_PER_SCREEN); Sprite sprite; Sprite_init(&sprite, bm); sprite.x = x; sprite.y = textPosY * PIXEL_ROWS_PER_TEXT_ROW; drawSprite(&sprite); if (newline) textPosY += (bm->height + PIXEL_ROWS_PER_TEXT_ROW - 1) / PIXEL_ROWS_PER_TEXT_ROW; DirtyRectList_init(&dirtyLists[writablePageIndex]); } // Returns TRUE if the user wants to see the next page, // or FALSE if the user wants to stop reading. // BOOL pressSpaceToContinue(void) { printWrapped( "\n" "PRESS ^SPACE^ TO CONTINUE...\n"); BOOL cont = TRUE; for (;;) { if (checkForKey(KEY_PROBE_SPACE, KEY_BIT_SPACE)) break; if (checkForKey(KEY_PROBE_BREAK, KEY_BIT_BREAK)) { cont = FALSE; break; } } clearScreen(scrnBuffer); moveCursor(0, 1); return cont; } // Clears the screen first, and also clears it before returning. // void showInstructionsScreen(void) { clearScreen(scrnBuffer); printCentered(1, "INSTRUCTIONS"); moveCursor(0, 3); printWrapped("The object is to score 15 points first by shooting down " "your opponent's plane or the ascending balloon, " "and by not crashing your own plane.\n" "\n" "Take off by pressing the joystick fire button, " "then climb by pulling back the joystick.\n" "\n" "Get back to a horizontal position by pushing up the joystick.\n"); if (!pressSpaceToContinue()) return; printWrapped("Don't make your plane climb too fast or it will stall and crash. " "If it starts to lose altitude, pull back the joystick, " "so the plain gains speed and stability.\n" "\n" "To fire at the ascending balloon or your opponent's plane, " "aim at the target and press the fire button.\n" "\n" "A plane can do loops, dive and fly upside down.\n" "\n" "When a plane, a bullet or a cloud reaches a side of the screen, " "it teleports to the other side instantly.\n"); if (!pressSpaceToContinue()) return; printWrapped("The presentation screen allows choosing a 1 or 2 player game. " "In a single-player game, the red plane is controlled by the computer, " "and you control the blue plane.\n" "\n" "When playing with the keyboard, the red plane climbs with ^Z^, " "dives with ^A^ and fires with ^S^, while the blue plane climbs " "with ^.^, dives with ^;^ and fires with ^L^.\n" "\n" "A choice is also offered between short-range and long-range bullets.\n"); if (!pressSpaceToContinue()) return; printWrapped("Pressing the Reset button quits the game and shows the " "presentation screen again.\n" "\n" "This game is based on the biplanes game of the 1981 " "Intellivision Triple Action cartridge.\n"); pressSpaceToContinue(); } #if COMPUTE_CHECKSUM void computeAndShowCodeCheckSum(void) { void *program_start, *s_rwdata; asm { program_start IMPORT s_rwdata IMPORT ldx #program_start stx :program_start ldx #s_rwdata stx :s_rwdata } moveCursor(0, 0); printf("program_start=%p\n""s_rwdata=%p.\n", program_start, s_rwdata); uint16_t crc = crc16_block(CRC16_RESET, program_start, s_rwdata - program_start); printf("crc=$%04x\n", crc); } #endif // Made with Verdana Bold 18 font in GIMP 2.10. // extern const uint32_t titleBitmap[14][8]; // Returns ' ' or 'R'. // byte showPresentationScreen(byte *numPlayers, byte *controlType) { // Show empty screen while drawing presentation, which takes about a full second. // showGraphicsPage(writablePageIndex ? page0 : page1); #if COMPUTE_CHECKSUM computeAndShowCodeCheckSum(); #endif for (;;) { // TODO: Draw some sprites above the title. // Display the large, garish game title. // const byte numTitleRows = ARRAY_SIZE(titleBitmap); // in pixel rows byte *screenPtr = getWritableBuffer() + (word) 1 * PIXEL_ROWS_PER_TEXT_ROW * BYTES_PER_ROW; copyDoubleRowBitmap(screenPtr, titleBitmap, numTitleRows); byte titleVertMargin = 4; // in pixel rows byte *xoredRegion = screenPtr - titleVertMargin * BYTES_PER_ROW; byte numXoredRows = numTitleRows * 2 + titleVertMargin * 2; xorRegion(xoredRegion, numXoredRows, 0x55); // N.B.: printWrapped() must be used if color inversion (^) is needed. byte textRow = 6; printCentered(textRow++, "VERSION " VERSION); textRow++; enableInvertedColorText(TRUE); printCentered(textRow++, "UNFINISHED PROTOTYPE"); enableInvertedColorText(FALSE); textRow++; printCentered(textRow++, "(C) " COPYRIGHT_YEARS " PIERRE SARRAZIN"); printCentered(textRow++, "DISTRIBUTED UNDER"); printCentered(textRow++, "THE GNU GPL V3 OR LATER"); textRow++; moveCursor(WRAPPED_TEXT_LEFT_MARGIN, textRow++); printWrapped("PRESS ^I^ FOR INSTRUCTIONS.\n\n"); printWrapped("NUMBER OF PLAYERS (^1^ OR ^2^):"); drawChar(' '); drawChar('0' + *numPlayers); printWrapped("\n\nUSE ^J^OYSTICK OR ^K^EYBOARD:"); drawChars(" "); // printWrapped() would merge these 3 spaces into a single one drawChar(*controlType == JOYSTICK_CONTROLLER ? 'J' : 'K'); printWrapped("\n\n^S^HORT/^L^ONG-RANGE BULLETS:"); drawChars(" "); drawChar(bulletTimeToLive == FRAMES_PER_SHORT_RANGE_BULLET ? 'S' : 'L'); printWrapped("\n\nPRESS ^SPACE^ TO START THE GAME."); // Show the screen that has just been drawn. // showGraphicsPage(writablePageIndex ? page1 : page0); byte cursorX, cursorY; getCursor(&cursorX, &cursorY); byte key = waitForGamePauseKey(FALSE, cursorX - 2, cursorY - 6, cursorY - 4, cursorY - 2, numPlayers, controlType); assert(key == 'I' || key == ' ' || key == 'R'); if (key == 'I') { showInstructionsScreen(); showGraphicsPage(writablePageIndex ? page0 : page1); // show empty screen continue; } return key; } } byte showGamePauseScreen(BOOL gameOver, byte *numPlayers, byte *controlType) { byte leftMargin = 1, indent = 6, row = 9; moveCursor(leftMargin, 6); if (gameOver) { putstr("GAME OVER", 9); moveCursor(leftMargin, row); putstr("PRESS ", 6); } else { putstr("GAME PAUSED", 11); moveCursor(leftMargin, row); ++row; ++row; printWrapped("PRESS ^R^ TO RESUME,"); moveCursor(leftMargin + indent, row); } printWrapped("^SPACE^ TO START"); ++row; moveCursor(leftMargin + indent + 6, row); printWrapped("A NEW GAME,"); ++row; ++row; moveCursor(leftMargin + indent, row); printWrapped("^I^ FOR INSTRUCTIONS."); byte cursorX = 0, cursorY = 0; if (gameOver) { ++row; ++row; moveCursor(leftMargin, row); printWrapped("NUMBER OF PLAYERS (^1^ OR ^2^):"); drawChar(' '); drawChar('0' + *numPlayers); printWrapped("\n\nUSE ^J^OYSTICK OR ^K^EYBOARD:"); drawChars(" "); drawChar(*controlType == JOYSTICK_CONTROLLER ? 'J' : 'K'); printWrapped("\n\n^S^HORT/^L^ONG-RANGE BULLETS:"); drawChars(" "); drawChar(bulletTimeToLive == FRAMES_PER_SHORT_RANGE_BULLET ? 'S' : 'L'); getCursor(&cursorX, &cursorY); } return waitForGamePauseKey(!gameOver, cursorX - 1, cursorY - 4, cursorY - 2, cursorY, numPlayers, controlType); } // Clears screen, show dialog, then clears screen again. // BOOL showNewGameConfirmDialog(void) { byte *writableBuffer = getWritableBuffer(); assert(writableBuffer == scrnBuffer); clearScreen(writableBuffer); printCentered(9, "START A NEW GAME:"); printCentered(11, "ARE YOU SURE?"); moveCursor((32 - 10) / 2, 13); printWrapped("^Y^ES or ^N^O?"); BOOL response = FALSE; for (;;) { if (isKeyPressedAndReleased(KEY_PROBE_Y, KEY_BIT_Y)) { response = TRUE; break; } if (isKeyPressedAndReleased(KEY_PROBE_N, KEY_BIT_N)) break; } clearScreen(writableBuffer); return response; } // redPlaneControlType: *_CONTROLLER value. // void initRedBiplane(byte redPlaneControlType) { initBiplaneSprite(&biplane_red, biplane_red_bitmaps, 0 /* point right */, SPRITE_WIDTH / 2); BiplaneDirectionFunctor dirFunctor; switch (redPlaneControlType) { case KEYBOARD_CONTROLLER: dirFunctor = getRedKeyboardDirection; break; case JOYSTICK_CONTROLLER: dirFunctor = getRedJoystickDirection; break; case AUTOMATIC_CONTROLLER: dirFunctor = getRedAutomaticDirection; break; default: assert(FALSE); } BiplaneMover_init(&redBiplaneMover, &biplane_red, biplane_red_bitmaps, 1, NUM_BIPLANE_BITMAPS - 1, dirFunctor); Controller_init(&redBiplaneController, redPlaneControlType, &redBiplaneMover, KEY_PROBE_S, KEY_BIT_S, JOY_BUTTON_LEFT_MASK); } void initBlueBiplane(BOOL bluePlaneUsesJoystick) { initBiplaneSprite(&biplane_blue, biplane_blue_bitmaps, 8 /* point left */, (byte) (COLS_PER_SCREEN - SPRITE_WIDTH / 2 - SPRITE_WIDTH)); BiplaneMover_init(&blueBiplaneMover, &biplane_blue, biplane_blue_bitmaps, NUM_BIPLANE_BITMAPS - 1, 1, bluePlaneUsesJoystick ? getBlueJoystickDirection : getBlueKeyboardDirection); Controller_init(&blueBiplaneController, bluePlaneUsesJoystick ? JOYSTICK_CONTROLLER : KEYBOARD_CONTROLLER, &blueBiplaneMover, KEY_PROBE_L, KEY_BIT_L, JOY_BUTTON_RIGHT_MASK); } // A cloud is made of two sprites displayed side by side. // void initCloud(Sprite *leftCloud, Sprite *rightCloud, BOOL onLeftHalfOfScreen) { // Choose a position that is above the 2 text lines where // the start game prompt appears. Sprite_init(leftCloud, &cloud_left_bm); leftCloud->x = (byte) (onLeftHalfOfScreen ? rnd(2, COLS_PER_SCREEN / 2 - 2 - SPRITE_WIDTH * 2) : rnd(COLS_PER_SCREEN / 2 + 2, COLS_PER_SCREEN - 2 - SPRITE_WIDTH * 2)); leftCloud->y = (byte) rnd(2, START_PROMPT_ROW * 8 - cloud_left_bm.height - 2); assert(leftCloud->x >= 2 && leftCloud->x <= COLS_PER_SCREEN - 2 - SPRITE_WIDTH); Sprite_init(rightCloud, &cloud_right_bm); rightCloud->x = leftCloud->x + SPRITE_WIDTH; rightCloud->y = leftCloud->y; assert(rightCloud->x >= 2 && rightCloud->x <= COLS_PER_SCREEN - 2 - SPRITE_WIDTH); } void initClouds(void) { for (byte i = 0; i < MAX_CLOUDS; ++i) initCloud(&leftClouds[i], &rightClouds[i], i & 1); switch (rand() % 7) { case 0: case 1: case 2: windDirection = -2; break; case 3: case 4: case 5: windDirection = +2; break; default: windDirection = 0; } initNumFramesBeforeCloudMove(); } // redPlaneControlType: *_CONTROLLER value. // bluePlaneUsesJoystick: FALSE means keyboard control. // void initNewGame(byte redPlaneControlType, BOOL bluePlaneUsesJoystick) { (*setColorSet)(1); for (byte i = 0; i < MAX_EXPLOSIONS; ++i) explosions[i].active = FALSE; initBalloon(); initRedBiplane(redPlaneControlType); initBlueBiplane(bluePlaneUsesJoystick); initClouds(); grPageHasStartPrompt[0] = grPageHasStartPrompt[1] = FALSE; Score_init(&redScore); Score_init(&blueScore); numVSyncsBeforeScreenFlip = 1; numFrames = 0; // init frame counter gameStarted = FALSE; } byte getRedKeyboardDirection(void) { if (isKeyPressed(KEY_PROBE_Z, KEY_BIT_Z)) return DIR_CLIMB; if (isKeyPressed(KEY_PROBE_A, KEY_BIT_A)) return DIR_DIVE; return DIR_FORWARD; } byte getBlueKeyboardDirection(void) { if (isKeyPressed(KEY_PROBE_PERIOD, KEY_BIT_PERIOD)) return DIR_CLIMB; if (isKeyPressed(KEY_PROBE_SEMICOLON, KEY_BIT_SEMICOLON)) return DIR_DIVE; return DIR_FORWARD; } __gcccall void updateJoystickAxisPos(byte axis, sbyte *joystickVerticalPos) { Joystick_selectAnalogMuxInputs(axis); // vertical axis of the right joystick BOOL atOrAboveLowThreshold = Joystick_compareAxis(JOY_AXIS_LOW_THR); //printf("[L=%u]", atOrAboveLowThreshold); if (!atOrAboveLowThreshold) // if axis value close to zero { *joystickVerticalPos = JOY_UP; //printf("[...]"); } else { BOOL atOrAboveHighThreshold = Joystick_compareAxis(JOY_AXIS_HIGH_THR); //printf("[H=%u]", atOrAboveHighThreshold); if (atOrAboveHighThreshold) // if close to max value *joystickVerticalPos = JOY_DOWN; else *joystickVerticalPos = JOY_MIDDLE; } } void updateJoystickButtons(void) { joystickButtonPreviousStates = joystickButtonStates; joystickButtonStates = Joystick_getButtonStates2(); } // Must be called periodically. // Uses useRightJoystick and useLeftJoystick. // void updateJoysticks(void) { disableInterrupts(); // Save the current state of the DAC, to restore it after reading // the joystick, to avoid hearing clicks. // byte savedDACState = * (byte *) 0xFF20; Joystick_disableSound(); // needed to avoid disrupting sound effects if (blueBiplaneController.controlType == JOYSTICK_CONTROLLER) updateJoystickAxisPos(JOY_RIGHT_Y_AXIS, &rightJoystickVerticalPos); if (redBiplaneController.controlType == JOYSTICK_CONTROLLER) updateJoystickAxisPos(JOY_LEFT_Y_AXIS, &leftJoystickVerticalPos); updateJoystickButtons(); // Reconnect digitial-to-analog sound input to output of sound multiplexer. // Basic's SOUND command does this at $A960, just before setting bit 3 of $FF23, // which we do by calling Joystick_enableSound(). // Joystick_selectAnalogMuxInputs(0); * (byte *) 0xFF20 = savedDACState; Joystick_enableSound(); enableInterrupts(); } byte getRedJoystickDirection(void) { if (leftJoystickVerticalPos == JOY_DOWN) return DIR_CLIMB; if (leftJoystickVerticalPos == JOY_UP) return DIR_DIVE; return DIR_FORWARD; } byte getBlueJoystickDirection(void) { if (rightJoystickVerticalPos == JOY_DOWN) return DIR_CLIMB; if (rightJoystickVerticalPos == JOY_UP) return DIR_DIVE; return DIR_FORWARD; } BOOL isSpriteNearInFront(const Sprite *shooter, const Sprite *target) { int8_t angleInBrads; if (!computeAngleIfNotTooFar(shooter->x, shooter->y, shooter->bitmapIndex, target->x, target->y, 128, 128 * 128, &angleInBrads)) return FALSE; return angleInBrads > -16 && angleInBrads < 16; } // Uses redBiplaneController. // byte getRedAutomaticDirection(void) { assert(gameStarted); int8_t bradsBetweenPlanes; switch (redBiplaneController.state) { case STATE_READY_FOR_TAKE_OFF: return DIR_FORWARD; case STATE_ON_RUNWAY: { if (redBiplaneController.numFramesBeforeStateChange > 0) { --redBiplaneController.numFramesBeforeStateChange; return DIR_FORWARD; } redBiplaneController.state = STATE_FIRST_CLIMB; // Choose the duration of the first climb. redBiplaneController.numFramesBeforeStateChange = rnd(1 * 20, 3 * 20); return DIR_CLIMB; } case STATE_FIRST_CLIMB: if (redBiplaneController.numFramesBeforeStateChange == 0) // if finished climbing { redBiplaneController.state = STATE_IN_FLIGHT; return DIR_DIVE; } --redBiplaneController.numFramesBeforeStateChange; /* FALLTHROUGH */ case STATE_IN_FLIGHT: if (!biplane_blue.active // attacking plane currently exploding || !blueBiplaneController.mover->hasStarted) // has not taken off return DIR_FORWARD; // Check if Red should change orientation to point towards Blue. // if ((biplane_red.bitmapIndex == 0 || biplane_red.bitmapIndex == 8) // pointing right or left && computeAngleIfNotTooFar(biplane_red.x, biplane_red.y, biplane_red.bitmapIndex, biplane_blue.x, biplane_blue.y, 128, 128 * 128, &bradsBetweenPlanes) && bradsBetweenPlanes != 0 // not already pointing towards Blue && abs(bradsBetweenPlanes) <= 16) { byte newDir; if (biplane_red.bitmapIndex == 0) // if Red is upright newDir = bradsBetweenPlanes > 0 ? DIR_CLIMB : DIR_DIVE; else newDir = bradsBetweenPlanes > 0 ? DIR_DIVE : DIR_CLIMB; // b/c Red is upside down redBiplaneController.state = (newDir == DIR_CLIMB ? STATE_ATTACK_CLIMB : STATE_ATTACK_DIVE); redBiplaneController.numFramesBeforeStateChange = rnd(5, 10); return newDir; } // Check if time for a defensive looping. // else if (isSpriteNearInFront(&biplane_blue, &biplane_red)) // red in danger { // Choose betweem climbing and diving. // byte dir; if (biplane_red.bitmapIndex <= 4 || biplane_red.bitmapIndex >= 13) // if pointing right or up { if (biplane_red.y < ROWS_PER_SCREEN / 2) // if plane in upper half of screen dir = DIR_DIVE; // dive toward ground else dir = DIR_CLIMB; // climb toward sky } else // pointing left (upside down) or down: { if (biplane_red.y < ROWS_PER_SCREEN / 2) // if plane in upper half of screen dir = DIR_CLIMB; // "climb" toward ground else dir = DIR_DIVE; // "dive" toward sky } redBiplaneController.state = (dir == DIR_CLIMB ? STATE_LOOPING_CLIMB : STATE_LOOPING_DIVE); return dir; } return DIR_FORWARD; case STATE_LOOPING_CLIMB: case STATE_LOOPING_DIVE: if ( biplane_red.bitmapIndex == 0 || biplane_red.bitmapIndex == 8) // if back to horizontal { redBiplaneController.state = STATE_IN_FLIGHT; // stop looping return DIR_FORWARD; } // Keep looping. return redBiplaneController.state == STATE_LOOPING_CLIMB ? DIR_CLIMB : DIR_DIVE; case STATE_ATTACK_CLIMB: case STATE_ATTACK_DIVE: { if (redBiplaneController.numFramesBeforeStateChange > 0) { --redBiplaneController.numFramesBeforeStateChange; return DIR_FORWARD; } // Return to horizontal. byte newDir = redBiplaneController.state == STATE_ATTACK_CLIMB ? DIR_DIVE : DIR_CLIMB; redBiplaneController.state = STATE_IN_FLIGHT; return newDir; } default: assert(!"Unsupported state"); } return DIR_FORWARD; } BOOL tryToShootAtSprite(Sprite *target) { byte bulletIndex = getFreeBulletSpotIndex(bullets_red); if (bulletIndex != MAX_BULLETS_PER_PLANE) // if free spot found { // If Red is attacking, shoot automatically. if (redBiplaneController.state == STATE_ATTACK_CLIMB || redBiplaneController.state == STATE_ATTACK_DIVE) return TRUE; // If Blue appears in front of Red, shoot. if (isSpriteNearInFront(&biplane_red, target)) return TRUE; } return FALSE; } // Uses bullets_red[]. // BOOL isPlaneFiringAuto(Controller *controller) { if (controller->state == STATE_READY_FOR_TAKE_OFF) { // Here, "firing" is used to launch the plane. // if (controller->numFramesBeforeStateChange > 0) { --controller->numFramesBeforeStateChange; return FALSE; } return TRUE; } if (controller->state == STATE_ON_RUNWAY) { // Never fire while on runway. // return FALSE; } // Here, the function is for actually firing a bullet. byte bits = (byte) numFrames & 15; if (bits == 0 // once in a while && biplane_blue.active // target plane not currently exploding && blueBiplaneController.mover->hasStarted) // has taken off return tryToShootAtSprite(&biplane_blue); if (bits == 14 // once in a while && balloon.active // balloon not currently exploding && numFramesBeforeBalloonTakeOff == 0) // balloon is in flight return tryToShootAtSprite(&balloon); return FALSE; } __gcccall void spawnPlaneIfInactive(BiplaneMover *mover, BOOL isRed) { if (mover->biplane->active) return; // nothing to do if (mover->numFramesBeforeSpawn > 0) // if still exploding { --mover->numFramesBeforeSpawn; return; // keep waiting } // Reinitiaze the plane with the control type that it already has. // (It was initialized by initNewGame().) // if (isRed) initRedBiplane(redBiplaneController.controlType); else initBlueBiplane(blueBiplaneController.controlType); } typedef BOOL (*FireButtonPressedFuncPtr)(Controller *controller); BOOL isPlaneFiring(Controller *controller) { if (controller->controlType == AUTOMATIC_CONTROLLER) return isPlaneFiringAuto(controller); if (controller->controlType == JOYSTICK_CONTROLLER) return (joystickButtonPreviousStates & controller->joyButtonMask) != 0 && (joystickButtonStates & controller->joyButtonMask) == 0; return KeyState_update(&controller->fireKeyState); } // Returns true if the plane has just been started. // BOOL checkIfStartingPlane(BiplaneMover *mover, Controller *controller) { if (!mover->hasStarted && isPlaneFiring(controller)) { mover->speed = MAX_SPEED_256THS; mover->hasStarted = TRUE; gameStarted = TRUE; return TRUE; } return FALSE; } void movePlane(Controller *controller, Score *otherPlane) { BiplaneMover *mover = controller->mover; if (BiplaneMover_move(mover)) { Controller_onBiplaneExplosion(controller); startExplosion(mover->biplane); mover->numFramesBeforeSpawn = FRAMES_PER_EXPLOSION; Score_addPoint(otherPlane); } } // Returns when the player has just lost the last life, or when // the quit key has been pressed. // Returns TRUE if the game is over, FALSE if the player requests a pause. // BOOL doMainGameLoop(void) { for (;;) // main game loop { ++numFrames; cleanWritablePage(); drawInWritablePage(); flipDisplayedBuffer(); // waits for v-sync then changes visible graphics page // Quit the game loop if a player has won the game, and the last explosion has finished. // if (!isExplosionActive() && (Score_isWinningScore(&redScore) || Score_isWinningScore(&blueScore))) return TRUE; if (blueBiplaneController.controlType == JOYSTICK_CONTROLLER || redBiplaneController.controlType == JOYSTICK_CONTROLLER) updateJoysticks(); checkForMute(); // If a plane is inactive, its explosion is still going on. // When that explosion has finished, i.e., when the numFramesBeforeSpawn field // has gone to 0, respawn the plane. // spawnPlaneIfInactive(&redBiplaneMover, TRUE); spawnPlaneIfInactive(&blueBiplaneMover, FALSE); // Check if a plane has not started yet but its player wants to start it now. // BOOL redJustStarted = checkIfStartingPlane(&redBiplaneMover, &redBiplaneController); BOOL blueJustStarted = checkIfStartingPlane(&blueBiplaneMover, &blueBiplaneController); if (redJustStarted) { redBiplaneController.state = STATE_ON_RUNWAY; redBiplaneController.numFramesBeforeStateChange = rnd(1, 10); // duration before first climb } if (redBiplaneMover.hasStarted || blueBiplaneMover.hasStarted) { assert(gameStarted); detectCollisions(); if ((byte) numFrames & 1) // each plane is allowed to move every 2 frames movePlane(&redBiplaneController, &blueScore); else movePlane(&blueBiplaneController, &redScore); // Check if planes want to fire. // Do not allow a plane to fire if it has just started. // (Otherwise, plane would fire immediately as it starts.) // if (!redJustStarted && isPlaneFiring(&redBiplaneController)) fireBullet(&biplane_red, bullets_red); if (!blueJustStarted && isPlaneFiring(&blueBiplaneController)) fireBullet(&biplane_blue, bullets_blue); } animateBullets(); animateExplosions(); animateBalloon(); animateClouds(); if (checkForKey(KEY_PROBE_BREAK, KEY_BIT_BREAK)) // if player requests pause return FALSE; // pause now } } #if SEED_FROM_USER byte pollKeyboard(void *) { return Keyboard_poll(&keyboard); } word getTimerWord(void *) { return timer; } void askForRNGSeed(void) { Keyboard_init(&keyboard); moveCursor(0, 0); printf("SEED? "); char response[6]; readLineFromKeyboard(pollKeyboard, NULL, 30, getTimerWord, response, sizeof(response)); srand(response[0] == '\0' ? timer : (word) atoul(response)); } #endif /* def SEED_FROM_USER */ enum { BLK = COCO3_FIRST_CODE_MMU_BLOCK, // abbreviation }; // Routine that restore all-RAM mode, then reexecutes the program. // This is to be run upon a Reset. // See the code at $A017 in Color Basic. // Will be copied to address WARM_START_ENTRY_POINT. // Must end before address COCO12_INTR_VECTORS. // // The writes to $FFAx are for a CoCo 3 (see loader.c). // They do nothing on a CoCo 1 and 2. // static byte warmStartRoutine[] = { 0x12, // NOP: required for this to be a warm start routine 0x7F, 0xFF, 0xDF, // CLR >$FFDF (put CoCo in all-RAM mode) 0xCC, BLK+0, BLK+1, // LDD #$3031 (tune in the 6 MMU blocks that contain the code) 0xFD, 0xFF, 0xA2, // STD $FFA2 0xCC, BLK+2, BLK+3, // LDD #$3233 0xFD, 0xFF, 0xA4, // STD $FFA4 0xCC, BLK+4, BLK+5, // LDD #$3435 0xFD, 0xFF, 0xA6, // STD $FFA6 0x10, 0xCE, STACK_BOTTOM/256, STACK_BOTTOM%256, // LDS #STACK_BOTTOM 0x7E, 0x00, 0x00, // JMP >mainWithNewStackSpace (address to be determined at run time) }; // Write a warm start routine in the first half of the 64k addressable space, // since this half is always RAM. // The second half gets reverted to ROM by the Reset button. // See the code at $A017 in Color Basic. // void prepareWarmStartRoutine(void) { // Don't override CoCo 1/2 interrupt vectors. assert(WARM_START_ENTRY_POINT + ARRAY_SIZE(warmStartRoutine) <= COCO12_INTR_VECTORS); * (byte *) RSTFLG = 0x55; // make Reset button do warm start instead of cold * (void **) RSTVEC = (void *) WARM_START_ENTRY_POINT; * (void **) (warmStartRoutine + (ARRAY_SIZE(warmStartRoutine) - 2)) = (void *) APP_ENTRY; // replace 0x00, 0x00 memcpy(WARM_START_ENTRY_POINT, warmStartRoutine, ARRAY_SIZE(warmStartRoutine)); } // Interrupts must be masked upon entry to this function. // void mainWithNewStackSpace(void) { // Turn the disk motors off. * (byte *) 0xFF40 = 0; prepareWarmStartRoutine(); // Make 32x16 screen black in case of Reset. // This avoids showing the screen that was left by the loader. memset16(VIDRAM, 0x8080, 512 / 2); // Initializations that depend on the type of CoCo (1/2 vs 3). emulatingPMode4OnCoCo3 = (* (word *) 0xFFF8 == 0xFEF7); // using global from cardgame library if (emulatingPMode4OnCoCo3) { rgb(); // Assume RGB monitor on a CoCo 3. setColorSet = setCoCo3ColorSet; } else { setColorSet = setCoCo12ColorSet; } setupIRQService(); // Enable the V-Sync IRQ interrupt. // This is not necessary on the first execution of this program, // but it is necessary after a Reset. // * (byte *) 0xFF03 |= 1; enableInterrupts(); _SetFailedAssertHandler(onFailedAssert); enableSound(); clearScreen(grbuf1); clearScreen(grbuf0); // Initialize both dirty lists. DirtyRectList_init(&dirtyLists[0]); DirtyRectList_init(&dirtyLists[1]); asm { sync } // wait for v-sync to change screen mode if (emulatingPMode4OnCoCo3) * (word *) 0xFF9D = 0xE000 | ((word) page1 << 6); // assumes buffer in $7xxxx range else setSAMRegisters((byte *) 0xFFC6, page1, 7); // show page 1 (empty screen) showPmode4ColorSet1(); // Cardgame library: setScreenBuffer2((void *) grbuf1); // must be consistent w/ preceding setSAMRegisters() call textScreenWidth = TEXT_COLS_PER_ROW; textScreenHeight = TEXT_ROWS_PER_SCREEN; setConsoleOutHook(hiResTextConsoleOutHook); // make printf() et al. write to screen at scrnBuffer setInvertedColorsParameters(TRUE, TRUE); makeSpacesTransparent(TRUE); setWrappedPrinting(WRAPPED_TEXT_LEFT_MARGIN, BYTES_PER_SCREEN_ROW - 2); // required to use printWrapped() #if SEED_FROM_USER askForRNGSeed(); clearScreen(grbuf1); #endif writablePageIndex = 1; // for printBitmap() calls in showPresentationScreen() byte numPlayers = 1; byte controlType = JOYSTICK_CONTROLLER; // Restore default value of some globals. (Needed in case of a Reset.) gameStarted = FALSE; bulletTimeToLive = FRAMES_PER_SHORT_RANGE_BULLET; grPageHasStartPrompt[0] = grPageHasStartPrompt[1] = FALSE; byte startKey = showPresentationScreen(&numPlayers, &controlType); #if !SEED_FROM_USER srand(timer); #endif writablePageIndex = 0; setScreenBuffer2(getWritableBuffer()); // for drawChar(), printf() et al. assert(getWritableBuffer() == scrnBuffer); //setConsoleOutHook(beckerPortConsoleOutHook); // to debug after presentation screen clearScreen(grbuf1); for (;;) { if (startKey == ' ') // if starting game initNewGame(numPlayers == 1 ? AUTOMATIC_CONTROLLER : controlType, controlType); else assert(startKey == 'R'); // resume paused game // Useful to get stats on IRQs per flip. See also irqService(). //extern BOOL enableTraces; //enableTraces = TRUE; BOOL gameOver = doMainGameLoop(); // Temporarily switch writablePageIndex so that the drawSprite() call // in printBitmap(), printf(), etc., will write to the displayed page. // writablePageIndex ^= 1; setScreenBuffer2(getWritableBuffer()); // for cardgame lib // Erase the start prompt, if any, during the pause. // assert(getWritableBuffer() == scrnBuffer); if (!gameStarted && grPageHasStartPrompt[writablePageIndex]) { eraseStartPrompt(); // grPageHasStartPrompt[writablePageIndex] is not set to FALSE here // because both entries of that array will be set to FALSE below, // after clearing both screens. } for (;;) { startKey = showGamePauseScreen(gameOver, &numPlayers, &controlType); assert(startKey == 'I' || startKey == ' ' || startKey == 'R'); if (startKey == ' ') { if (gameOver || showNewGameConfirmDialog()) break; // confirmed continue; // cancelled, so show pause screen again } if (startKey != 'I') break; showInstructionsScreen(); } assert(getWritableBuffer() == scrnBuffer); writablePageIndex ^= 1; // switch back to original page setScreenBuffer2(getWritableBuffer()); // for cardgame lib assert(getWritableBuffer() == scrnBuffer); clearScreen(grbuf0); clearScreen(grbuf1); // Set both entries of grPageHasStartPrompt[] to FALSE // to reflect that both screens have just been cleared. // grPageHasStartPrompt[0] = grPageHasStartPrompt[1] = FALSE; } } // Interrupts are masked upon entry to main(), because // of decbfile_runDOSLoader(), the function called by loader.c // to load an execute this program. // The CoCo is assumed to have been put in all-RAM mode by that loader. // The Basic interpreter must be assumed to be totally absent. // int main() { asm { lds #STACK_BOTTOM ; put stack space below 1st graphics buffer lbra mainWithNewStackSpace } }