summaryrefslogtreecommitdiff
path: root/chapter31/docs/examples
diff options
context:
space:
mode:
Diffstat (limited to 'chapter31/docs/examples')
-rw-r--r--chapter31/docs/examples/Breakout.smp386
-rw-r--r--chapter31/docs/examples/Clock.smp68
-rw-r--r--chapter31/docs/examples/Graphics.smp19
-rw-r--r--chapter31/docs/examples/README.md35
-rw-r--r--chapter31/docs/examples/TicTacToeGraphical.smp15
5 files changed, 310 insertions, 213 deletions
diff --git a/chapter31/docs/examples/Breakout.smp b/chapter31/docs/examples/Breakout.smp
index e5757b45..d60894ac 100644
--- a/chapter31/docs/examples/Breakout.smp
+++ b/chapter31/docs/examples/Breakout.smp
@@ -1,6 +1,6 @@
// Clear 24 x 8 bricks. Arrows or mouse move; Space/click serves; P pauses;
// R restarts; Q/Escape exits. Any argument runs ten frames as a smoke test.
-int WIDTH = 1008, HEIGHT = 760, COLS = 24, ROWS = 8;
+u32 WIDTH = 1008, HEIGHT = 760, COLS = 24, ROWS = 8;
int LEFT = 24, RIGHT = 984, TOP = 84, BOTTOM = 718;
int BRICK_TOP = 152, BRICK_DX = 40, BRICK_DY = 22, BRICK_W = 36, BRICK_H = 18;
int RADIUS = 5, PADDLE_HALF = 56, PADDLE_Y = 674;
@@ -17,18 +17,76 @@ struct Game {
int score = 0, remaining = COLS*ROWS, lives = 3, depth = 1, phase = READY;
bool boosted = false, backWall = false, paused = false;
f64 x = 504.0, y = 663.0, dx = 0.4, dy = -0.916515138991168;
- int soundDepth = 1;
- // Serve the ball; give it a nominal direction and speed
- val _serve = { ->
- if( phase == READY && !paused ) {
- phase = PLAY;
- dx = 0.4;
- dy = -_sqrt(1.0-dx*dx);
+ // Fixed 8 ms simulation, split further to travel at most two pixels per step.
+ // Even at maximum boosted speed a ball cannot tunnel through an 18 px brick.
+ val _tick = { int direction ->
+ if( paused || phase == WON || phase == LOST ) return 0;
+ _paddle(paddle+direction*6.4);
+ if( phase == READY ) { x = paddle; y = PADDLE_Y-RADIUS-6; return 0; }
+ f64 seconds = 0.008; // 8ms
+ while( seconds > 0.000000001 && phase == PLAY ) {
+ f64 dt = 2.0/speed;
+ if( dt > seconds ) dt = seconds;
+ seconds -= dt;
+ f64 oldX = x, oldY = y;
+ x += dx*speed*dt;
+ y += dy*speed*dt;
+ if( x < LEFT+RADIUS && dx < 0.0 ) {
+ x = 2.0*(LEFT+RADIUS)-x; dx = -dx; _cue(1);
+ }
+ if( x > RIGHT-RADIUS && dx > 0.0 ) {
+ x = 2.0*(RIGHT-RADIUS)-x; dx = -dx; _cue(1);
+ }
+ if( y < TOP+RADIUS && dy < 0.0 ) {
+ y = 2.0*(TOP+RADIUS)-y; dy = -dy;
+ backWall = true; _cue(1);
+ }
+ if( dy > 0.0 && oldY <= PADDLE_Y-RADIUS && y >= PADDLE_Y-RADIUS &&
+ paddle-PADDLE_HALF-RADIUS <= x <= paddle+PADDLE_HALF+RADIUS ) _rebound();
+ if( y > BOTTOM+RADIUS ) {
+ _lostBall();
+ break;
+ }
+ // Map the center into the grid of radius-expanded brick boxes.
+ // Their overlap is smaller than one cell: at most 2 x 2 candidates.
+ if( x <= LEFT+2 -RADIUS || x >= LEFT+2 +(COLS-1)*BRICK_DX+BRICK_W+RADIUS ||
+ y <= BRICK_TOP-RADIUS || y >= BRICK_TOP+(ROWS-1)*BRICK_DY+BRICK_H+RADIUS )
+ continue;
+ int col = (x-(LEFT+2 -RADIUS))/BRICK_DX;
+ int row = (y-(BRICK_TOP-RADIUS))/BRICK_DY;
+ bool hit = false;
+ for( int r = row > 0 ? row-1 : 0; r <= row && r < ROWS && !hit; r++ )
+ for( int c = col > 0 ? col-1 : 0; c <= col && c < COLS; c++ ) {
+ int i = r*COLS+c;
+ if( bricks[i] == 0 ) continue;
+ f64 left = LEFT+2 +c*BRICK_DX-RADIUS;
+ f64 top = BRICK_TOP+r*BRICK_DY-RADIUS;
+ f64 right = left+BRICK_W+2*RADIUS;
+ f64 bottom= top +BRICK_H+2*RADIUS;
+ if( left < x < right && top < y < bottom ) {
+ bool back = false;
+ // Resolve the face crossed this step, using the previous center.
+ // Vertical faces win a simultaneous corner contact.
+ if( oldY <= top && dy > 0.0 ) {
+ y = top; dy = -dy; back = true;
+ } else if( oldY >= bottom && dy < 0.0 ) {
+ y = bottom; dy = -dy;
+ } else if( oldX <= left && dx > 0.0 ) {
+ x = left; dx = -dx;
+ } else if( oldX >= right && dx < 0.0 ) {
+ x = right; dx = -dx;
+ } else continue; // Missed all bricks
+ _brick(i,back);
+ hit = true;
+ break;
+ }
+ }
}
return 0;
};
+
// Several sound things might happen in this event, pick one
int sound = 0; // Increasing priority: wall, paddle, brick, boost, miss, win.
val _cue = { int snd -> if( snd > sound ) sound = snd; };
@@ -41,11 +99,10 @@ struct Game {
f64 paddle;
val _paddle = { f64 x ->
paddle = x < LEFT +PADDLE_HALF ? LEFT +PADDLE_HALF :
- x > RIGHT-PADDLE_HALF ? RIGHT+PADDLE_HALF :
+ x > RIGHT-PADDLE_HALF ? RIGHT-PADDLE_HALF :
x;
};
-
// Hit the paddle
val _rebound = { ->
// Where along the paddle did you hit?
@@ -62,6 +119,7 @@ struct Game {
};
// Hit a brick?
+ int soundDepth; // Which brick depth for the boop
val _brick = { int index, bool back ->
if( bricks[index] == 0 ) return 0; // No brick to hit!
bricks[index] = 0; // Clear brick
@@ -70,13 +128,25 @@ struct Game {
remaining--; // Fewer bricks to iwn
if( row > depth ) depth = row; // Max depth seen
// Brick-hit sound
- if( sound <= 3 ) { soundDepth = row; _cue(3); }
- if( back && backWall && !boosted ) { boosted = true; _cue(4); }
- if( remaining == 0 ) { phase = WON; _cue(6); }
+ if( sound <= 3 ) { _cue(3); soundDepth = row; }
+ if( back && backWall && !boosted ) { _cue(3); boosted = true; }
+ if( remaining == 0 ) { _cue(6); phase = WON; }
_speed();
return 0;
};
+ // Missed ball with paddle
+ val _lostBall = { ->
+ lives--;
+ phase = lives == 0 ? LOST : READY;
+ backWall = false;
+ depth = 1;
+ boosted = false;
+ _speed();
+ x = paddle; y = PADDLE_Y-RADIUS-6;
+ _cue(5);
+ };
+
// Reset for another round
val _reset = { ->
for( int i = 0; i < bricks#; i++ ) bricks[i] = 1;
@@ -89,164 +159,154 @@ struct Game {
backWall = false;
paused = false;
sound = 0;
+ soundDepth = 1;
paddle = 504.0;
x = paddle;
y = PADDLE_Y-RADIUS-6;
_speed();
};
-};
-// Fixed 8 ms simulation, split further to travel at most two pixels per step.
-// Even at maximum boosted speed a ball cannot tunnel through an 18 px brick.
-val _tick = { !Game g, int direction ->
- if( g.paused || g.phase == WON || g.phase == LOST ) return 0;
- g._paddle(g.paddle+direction*6.4);
- if( g.phase == READY ) { g.x = g.paddle; g.y = PADDLE_Y-RADIUS-6; return 0; }
- f64 seconds = 0.008;
- while( seconds > 0.000000001 && g.phase == PLAY ) {
- f64 dt = 2.0/g.speed;
- if( dt > seconds ) dt = seconds;
- seconds -= dt;
- f64 oldX = g.x, oldY = g.y;
- g.x += g.dx*g.speed*dt;
- g.y += g.dy*g.speed*dt;
- if( g.x < LEFT+RADIUS && g.dx < 0.0 ) {
- g.x = 2.0*(LEFT+RADIUS)-g.x; g.dx = -g.dx; g._cue(1);
- }
- if( g.x > RIGHT-RADIUS && g.dx > 0.0 ) {
- g.x = 2.0*(RIGHT-RADIUS)-g.x; g.dx = -g.dx; g._cue(1);
- }
- if( g.y < TOP+RADIUS && g.dy < 0.0 ) {
- g.y = 2.0*(TOP+RADIUS)-g.y; g.dy = -g.dy;
- g.backWall = true; g._cue(1);
+ // --------------------------------
+ // Drawing code
+ val _hud = { !sys.draw.Canvas c ->
+ c.text(24,22,"BREAKOUT",5,WHITE);
+ c.text(264,20,"SCORE",2,MUTED);
+ _number(c,264,40,score,3,4,WHITE);
+ c.text(424,20,"BRICKS",2,MUTED);
+ _number(c,424,40,remaining,3,4,WHITE);
+ c.text(584,20,"BALLS",2,MUTED);
+ for( int i = 0; i < lives; i++ ) c.fillCircle(590+23*i,50,5,CYAN);
+ c.text(714,20,"SPEED",2,MUTED);
+ int ispeed = speed;
+ _number(c,714,40,ispeed,3,4,boosted ? COLORS[0] : WHITE);
+ c.text(838,40,boosted ? "BOOST!" : "NORMAL",3,boosted ? COLORS[0] : MUTED);
+ };
+
+
+ val _bricks = { !sys.draw.Canvas c ->
+ c.fillRect(LEFT-4,TOP-4,RIGHT-LEFT+8,4,MUTED);
+ c.fillRect(LEFT-4,TOP,4,BOTTOM-TOP,0x29435a);
+ c.fillRect(RIGHT,TOP,4,BOTTOM-TOP,0x29435a);
+ c.text(376,108,boosted ? "BACK WALL BOOST ACTIVE" : "BREAK THROUGH FOR A BOOST",2,boosted ? COLORS[0] : MUTED);
+ for( int i = 0; i < bricks#; i++ ) {
+ if( bricks[i] == 0 ) continue;
+ int row = i/COLS;
+ i64 x = LEFT+2+(i%COLS)*BRICK_DX, y = BRICK_TOP+row*BRICK_DY;
+ c.fillRect(x,y,BRICK_W,BRICK_H,COLORS[row]);
+ c.fillRect(x,y,BRICK_W,2,WHITE);
}
- if( g.dy > 0.0 && oldY <= PADDLE_Y-RADIUS && g.y >= PADDLE_Y-RADIUS &&
- g.paddle-PADDLE_HALF-RADIUS <= g.x <= g.paddle+PADDLE_HALF+RADIUS ) g._rebound();
- if( g.y > BOTTOM+RADIUS ) {
- g.lives--;
- g.phase = g.lives == 0 ? LOST : READY;
- g.backWall = false;
- g.depth = 1;
- g.boosted = false;
- g._speed();
- g.x = g.paddle; g.y = PADDLE_Y-RADIUS-6;
- g._cue(5);
- break;
+ };
+
+ val _overlay = { !sys.draw.Canvas c ->
+ if( phase != PLAY || paused ) {
+ c.fillRect(246,422,516,108,0x17263a).rect(246,422,516,108,2,0x29435a);
+ u8[~] title = paused ? "PAUSED" : phase == WON ? "WALL CLEARED!" : phase == LOST ? "GAME OVER" : "READY?";
+ c.text(504-(title#*4-1)*4/2,442,title,4,WHITE);
+ u8[~] help = paused ? "P TO CONTINUE" : phase == WON || phase == LOST ? "R TO PLAY AGAIN" : "SPACE OR CLICK TO SERVE";
+ c.text(504-(help#*4-1)*2/2,490,help,2,CYAN);
}
- for( int i = 0; i < g.bricks#; i++ ) {
- if( g.bricks[i] == 0 ) continue;
- f64 left = LEFT+2+(i-i/COLS*COLS)*BRICK_DX-RADIUS;
- f64 top = BRICK_TOP+(i/COLS)*BRICK_DY-RADIUS;
- f64 right = left+BRICK_W+2*RADIUS, bottom = top+BRICK_H+2*RADIUS;
- if( left < g.x < right && top < g.y < bottom ) {
- bool back = false;
- // Resolve the face crossed this step, using the previous center.
- // Vertical faces win a simultaneous corner contact.
- if( oldY <= top && g.dy > 0.0 ) {
- g.y = top; g.dy = -g.dy; back = true;
- } else if( oldY >= bottom && g.dy < 0.0 ) {
- g.y = bottom; g.dy = -g.dy;
- } else if( oldX <= left && g.dx > 0.0 ) {
- g.x = left; g.dx = -g.dx;
- } else if( oldX >= right && g.dx < 0.0 ) {
- g.x = right; g.dx = -g.dx;
- } else continue;
- g._brick(i,back);
- break;
+ return 0;
+ };
+
+ // With this Canvas, we draw into the blank canvas, then "present". The
+ // underlying graphics lib copies the bits, and we are then free to clear
+ // and draw again while the old bits continue to be presented.
+ val _draw = { !sys.draw.Canvas c ->
+ c.clear(BACKGROUND);
+ _hud(c);
+ _bricks(c);
+ i64 paddle = paddle, ballX = x, ballY = y;
+ int glowRadius = RADIUS+3;
+ c.fillRect(paddle-PADDLE_HALF,PADDLE_Y,2*PADDLE_HALF,12,CYAN);
+ c.fillRect(paddle-PADDLE_HALF+4,PADDLE_Y+2,2*PADDLE_HALF-8,2,WHITE);
+ c.fillCircle(ballX,ballY,glowRadius,boosted ? 0x672a42 : 0x224b61);
+ c.fillCircle(ballX,ballY,RADIUS,boosted ? COLORS[0] : WHITE);
+ _overlay(c);
+ c.text(24,738,"ARROWS / MOUSE: MOVE SPACE / CLICK: SERVE P: PAUSE R: RESTART Q / ESC: QUIT",2,MUTED);
+ };
+
+ // Served and still holding serve key
+ bool serveHeld;
+ // Paused and still holding pause key
+ bool pauseHeld;
+ // Restart and still holding restart key
+ bool restartHeld;
+ // Last mouse position; track moving mouse
+ int lastMouse;
+
+ // Read and act on the controls
+ val _input = { sys.draw.Canvas c ->
+ val gfx = sys.gfx;
+ bool serve = gfx.key(' ') || gfx.button(gfx.LEFT);
+ bool pause = gfx.key('P');
+ bool restart= gfx.key('R');
+
+ // Keyboard direction and mouse position
+ int direction = (gfx.key(KEY_RIGHT) ? 1 : 0)-(gfx.key(KEY_LEFT) ? 1 : 0);
+ int mouse = c.localX(gfx.mouseX());
+
+ // Restart requested
+ restartHeld = debounce( restart, restartHeld, { -> _reset(); sys.audio.stop(); } );
+
+ // Playing or ready to play game?
+ if( phase == READY || phase == PLAY ) {
+ // Flip pause state
+ pauseHeld = debounce( pause, pauseHeld, { -> paused = !paused; } );
+
+ // If no key and mouse moved, set paddle to mouse
+ if( mouse >= 0 && mouse != lastMouse && direction == 0 && !paused ) {
+ _paddle(mouse*1.0); // Set paddle to mouse
+ // If READY and not PLAY, ball tracks paddle directly
+ if( phase == READY ) x = paddle;
}
+ lastMouse = mouse;
+
}
- }
- return 0;
+
+ // Serve requested
+ serveHeld = debounce( serve, serveHeld, _serve );
+
+ // Return key direction, so the tick tracking can slide paddle smoothly
+ return direction;
+ };
+
+ val debounce = { bool b, bool bHeld, { int } action ->
+ if( b && !bHeld ) // Action requested and repeating
+ action(); // Do action
+ b; // Dont action again, until 'b' is released
+ };
+
+
+ // Serve the ball; give it a nominal direction and speed
+ val _serve = { ->
+ if( phase == READY && !paused ) {
+ phase = PLAY;
+ dx = 0.4;
+ dy = -_sqrt(1.0-dx*dx);
+ }
+ return 0;
+ };
};
// Fixed-width decimal labels avoid allocating new strings on every frame.
val _number = { !sys.draw.Canvas c, i64 x, i64 y, int value, int digits, int scale, u32 color ->
for( int i = 0; i < digits; i++ ) {
- c.text(x+(digits-1-i)*4*scale,y,DIGITS[value-value/10*10],scale,color);
+ c.text(x+(digits-1-i)*4*scale,y,DIGITS[value%10],scale,color);
value /= 10;
}
};
-val _hud = { !sys.draw.Canvas c, Game g ->
- c.text(24,22,"BREAKOUT",5,WHITE);
- c.text(264,20,"SCORE",2,MUTED);
- _number(c,264,40,g.score,3,4,WHITE);
- c.text(424,20,"BRICKS",2,MUTED);
- _number(c,424,40,g.remaining,3,4,WHITE);
- c.text(584,20,"BALLS",2,MUTED);
- for( int i = 0; i < g.lives; i++ ) c.fillCircle(590+23*i,50,5,CYAN);
- c.text(714,20,"SPEED",2,MUTED);
- int speed = g.speed;
- _number(c,714,40,speed,3,4,g.boosted ? COLORS[0] : WHITE);
- c.text(838,40,g.boosted ? "BOOST!" : "NORMAL",3,g.boosted ? COLORS[0] : MUTED);
-};
-val _bricks = { !sys.draw.Canvas c, Game g ->
- c.fillRect(LEFT-4,TOP-4,RIGHT-LEFT+8,4,MUTED);
- c.fillRect(LEFT-4,TOP,4,BOTTOM-TOP,0x29435a);
- c.fillRect(RIGHT,TOP,4,BOTTOM-TOP,0x29435a);
- c.text(376,108,g.boosted ? "BACK WALL BOOST ACTIVE" : "BREAK THROUGH FOR A BOOST",2,g.boosted ? COLORS[0] : MUTED);
- for( int i = 0; i < g.bricks#; i++ ) {
- if( g.bricks[i] == 0 ) continue;
- int row = i/COLS;
- i64 x = LEFT+2+(i-row*COLS)*BRICK_DX, y = BRICK_TOP+row*BRICK_DY;
- c.fillRect(x,y,BRICK_W,BRICK_H,COLORS[row]);
- c.fillRect(x,y,BRICK_W,2,WHITE);
- }
-};
-val _overlay = { !sys.draw.Canvas c, Game g ->
- if( g.phase != PLAY || g.paused ) {
- c.fillRect(246,422,516,108,0x17263a).rect(246,422,516,108,2,0x29435a);
- u8[~] title = g.paused ? "PAUSED" : g.phase == WON ? "WALL CLEARED!" : g.phase == LOST ? "GAME OVER" : "READY?";
- c.text(504-(title#*4-1)*4/2,442,title,4,WHITE);
- u8[~] help = g.paused ? "P TO CONTINUE" : g.phase == WON || g.phase == LOST ? "R TO PLAY AGAIN" : "SPACE OR CLICK TO SERVE";
- c.text(504-(help#*4-1)*2/2,490,help,2,CYAN);
- }
- return 0;
-};
-val _draw = { !sys.draw.Canvas c, Game g ->
- c.clear(BACKGROUND);
- _hud(c,g);
- _bricks(c,g);
- i64 paddle = g.paddle, ballX = g.x, ballY = g.y;
- int glowRadius = RADIUS+3;
- c.fillRect(paddle-PADDLE_HALF,PADDLE_Y,2*PADDLE_HALF,12,CYAN);
- c.fillRect(paddle-PADDLE_HALF+4,PADDLE_Y+2,2*PADDLE_HALF-8,2,WHITE);
- c.fillCircle(ballX,ballY,glowRadius,g.boosted ? 0x672a42 : 0x224b61);
- c.fillCircle(ballX,ballY,RADIUS,g.boosted ? COLORS[0] : WHITE);
- _overlay(c,g);
- c.text(24,738,"ARROWS / MOUSE: MOVE SPACE / CLICK: SERVE P: PAUSE R: RESTART Q / ESC: QUIT",2,MUTED);
-};
// Short, fading triangle waves; the array initializer builds PCM once at startup.
val _tone = { int period ->
val samples = new i16[~2400]{int i ->
- int phase = i-i/period*period;
+ int phase = i%period;
int triangle = phase < period/2 ? phase : period-phase;
return (triangle*4-period)*6000/period*(2400-i)/2400;
};
int handle = sys.audio.load(samples);
return handle < 0 ? sys.audio.BOOP : handle;
};
-struct Controls {
- bool serveHeld = false, pauseHeld = false, restartHeld = false;
- int lastMouse = 504;
-};
-val _input = { !Game g, !Controls keys ->
- val gfx = sys.gfx;
- bool serve = gfx.key(' ') || gfx.button(gfx.LEFT);
- bool pause = gfx.key('P'), restart = gfx.key('R');
- if( restart && !keys.restartHeld ) { g._reset(); sys.audio.stop(); }
- if( pause && !keys.pauseHeld && (g.phase == READY || g.phase == PLAY) ) g.paused = !g.paused;
- int direction = (gfx.key(KEY_RIGHT) ? 1 : 0)-(gfx.key(KEY_LEFT) ? 1 : 0);
- int mouse = gfx.mouseX();
- if( mouse != keys.lastMouse && direction == 0 && !g.paused && (g.phase == READY || g.phase == PLAY) ) {
- g._paddle(mouse*1.0);
- if( g.phase == READY ) g.x = g.paddle;
- }
- keys.lastMouse = mouse;
- if( serve && !keys.serveHeld ) g._serve();
- keys.serveHeld = serve; keys.pauseHeld = pause; keys.restartHeld = restart;
- return direction;
-};
+
// Fast low accuracy sqrt
val _sqrt = { f64 n ->
@@ -256,33 +316,49 @@ val _sqrt = { f64 n ->
};
val main = { u8[~][] args ->
- val gfx = sys.gfx, audio = sys.audio, time = sys.time;
- val c = new sys.draw.Canvas(WIDTH,HEIGHT);
- val g = new Game;
- if( gfx.open("Simple Breakout",c.width,c.height) != gfx.OK ) return 1;
+ // Shortcuts
+ val gfx = sys.gfx, audio = sys.audio;
+
+ // Open a window
+ if( gfx.open("Simple Breakout",WIDTH,HEIGHT) != gfx.OK ) return 1;
+
+ // Audio setup; pre-specify a series of sounds
audio.open(); // Optional: a missing audio backend leaves play silent.
val sounds = new int[~]{0,_tone(120),_tone(80),audio.BOOP,audio.WIN,audio.LOSE,audio.WIN};
// Bottom to top: roughly 333..800 Hz, below the old 1000 Hz brick tone.
val brickSounds = new int[~ROWS]{int i -> int period = 144-i*12; _tone(period);};
- val keys = new Controls;
- keys.lastMouse = gfx.mouseX();
+
+ // Setup drawing board
+ val c = new sys.draw.Canvas(WIDTH,HEIGHT);
+
+ // Setup game contents
+ val g = new Game;
+ g._reset();
+
+ //
int frames = 0, status = gfx.OK;
- i64 last_ms = time.monotonic(), pending_ms = 0, frame_ms = last_ms;
+ i64 last_ms = sys.time.monotonic(), pending_ms = 0, frame_ms = last_ms;
+
while( status == gfx.OK ) {
if( gfx.key('Q') || gfx.key(gfx.ESCAPE) ) break;
- int direction = _input(g,keys);
- i64 now_ms = time.monotonic(), elapsed_ms = now_ms-last_ms;
+ // Physics stays in base coordinates; only drawing and input scale.
+ if( c.resize(gfx.width(),gfx.height()) ) {
+ g.lastMouse = c.localX(gfx.mouseX());
+ frame_ms = 0;
+ }
+ int direction = g._input(c);
+ i64 now_ms = sys.time.monotonic(), elapsed_ms = now_ms-last_ms;
last_ms = now_ms;
// Drop long stalls instead of teleporting the ball after a window drag.
pending_ms += elapsed_ms < 0 ? 0 : elapsed_ms > 64 ? 64 : elapsed_ms;
- while( pending_ms >= STEP_ms ) { _tick(g,direction); pending_ms -= STEP_ms; }
+ while( pending_ms >= STEP_ms ) { g._tick(direction); pending_ms -= STEP_ms; }
if( g.sound != 0 ) {
audio.play(g.sound == 3 ? brickSounds[g.soundDepth-1] : sounds[g.sound]);
g.sound = 0;
}
if( now_ms >= frame_ms ) {
- _draw(c,g);
- status = gfx.present(c.pixels);
+ g._draw(c);
+ status = gfx.presentSize(c.pixels,c.width,c.height);
frame_ms = now_ms+FRAME_ms;
if( args# > 1 && ++frames == 10 ) break;
}
diff --git a/chapter31/docs/examples/Clock.smp b/chapter31/docs/examples/Clock.smp
index ecf0fae1..fb50f84e 100644
--- a/chapter31/docs/examples/Clock.smp
+++ b/chapter31/docs/examples/Clock.smp
@@ -20,12 +20,13 @@ val main = { u8[~][] args ->
// Main event loop
while( status == gfx.OK ) {
+ bool resized = screen.resize(gfx.width(),gfx.height());
// Did the user press space bar?
bool space = gfx.key(' ');
// Did the left mouse button go down?
bool down = gfx.button(gfx.LEFT);
// ANd did it go down over this button?
- bool click = button.update(gfx.mouseX(),gfx.mouseY(),down);
+ bool click = button.update(screen.localX(gfx.mouseX()),screen.localY(gfx.mouseY()),down);
// If clicked, flip the clock mode
if( click || (space && !held) ) analog = !analog;
held = space;
@@ -33,12 +34,12 @@ val main = { u8[~][] args ->
// Change button label
button.label = analog ? "DIGITAL CLOCK" : "ANALOG CLOCK";
// If the next timer event is the every-33-msec event
- if( timers.poll(time.monotonic()) == frame_id ) {
+ if( timers.poll(time.monotonic()) == frame_id || resized ) {
// Draw the clock screen and button
_draw(screen,time.now(),analog);
button.draw(screen,3,GREEN,BACKGROUND,DIM);
// Presne the canvas on screen
- status = gfx.present(screen.pixels);
+ status = gfx.presentSize(screen.pixels,screen.width,screen.height);
// Testing only: show 5 frames, flip to analog, show 5 more and exit
if( args# > 1 ) {
frames++;
@@ -66,62 +67,61 @@ val _draw = { !sys.draw.Canvas screen, i64 wall_ms, i64 analog ->
// a..g bits: top, upper-right, lower-right, bottom, lower-left, upper-left,
// middle. Faint unlit bars retain the old LED figure-eight silhouette.
+val _digitFont = new u8[~]{
+ // 0 1 2 3 4 5 6 7 8 9
+ 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f
+};
+val _digitBars = new u8[~]{
+ // x0 y0 x1 y1
+ 14, 0, 58, 0, // a: top
+ 68, 12, 68, 60, // b: upper-right
+ 68, 84, 68, 132, // c: lower-right
+ 14, 144, 58, 144, // d: bottom
+ 4, 84, 4, 132, // e: lower-left
+ 4, 12, 4, 60, // f: upper-left
+ 14, 72, 58, 72 // g: middle
+};
val _digit = { !sys.draw.Canvas c, int x, int y, i64 digit ->
- int bits = digit == 0 ? 0x3f : digit == 1 ? 0x06 : digit == 2 ? 0x5b :
- digit == 3 ? 0x4f : digit == 4 ? 0x66 : digit == 5 ? 0x6d :
- digit == 6 ? 0x7d : digit == 7 ? 0x07 : digit == 8 ? 0x7f : digit == 9 ? 0x6f : 0;
+ int bits = 0 <= digit < _digitFont# ? _digitFont[digit] : 0;
for( int i = 0; i < 7; i++ ) {
u32 color = (bits&(1<<i)) != 0 ? GREEN : DIM;
- if( i == 0 || i == 3 || i == 6 ) {
- int dy = i == 0 ? 0 : i == 3 ? 144 : 72;
- c.line(x+14,y+dy,x+58,y+dy,10,color);
- } else {
- bool right = i == 1 || i == 2;
- int dx = right ? 68 : 4, dy = i == 1 || i == 5 ? 12 : 84;
- c.line(x+dx,y+dy,x+dx,y+dy+48,10,color);
- }
+ int bar = i*4;
+ c.line(x+_digitBars[bar ],y+_digitBars[bar+1],
+ x+_digitBars[bar+2],y+_digitBars[bar+3],10,color);
}
};
val _digital = { !sys.draw.Canvas c, int hour, int minute, int second ->
- _digit(c,68,166,hour/10); _digit(c,154,166,hour-hour/10*10);
- _digit(c,284,166,minute/10); _digit(c,370,166,minute-minute/10*10);
- _digit(c,500,166,second/10); _digit(c,586,166,second-second/10*10);
+ _digit(c, 68,166, hour/10); _digit(c,154,166, hour%10);
+ _digit(c,284,166,minute/10); _digit(c,370,166,minute%10);
+ _digit(c,500,166,second/10); _digit(c,586,166,second%10);
for( int i = 0; i < 2; i++ ) {
c.fillCircle(254+i*216,214,6,GREEN);
c.fillCircle(254+i*216,262,6,GREEN);
}
c.text(272,352,"LOCAL TIME 24H",3,GREEN);
};
-// Rational sine approximation, accurate enough for pixel clock geometry.
-// Arguments are nonnegative turns; no additional native math dependency.
-val _sin = { f64 turn ->
- i64 whole = turn; turn -= whole;
- bool negative = turn > 0.5;
- f64 x = (negative ? turn-0.5 : turn)*6.283185307179586;
- f64 product = x*(3.141592653589793-x);
- f64 numerator = negative ? -16.0 : 16.0;
- return numerator*product/(49.34802200544679-4*product);
-};
val _hand = { !sys.draw.Canvas c, f64 turn, int length, int thickness, u32 color ->
- int x = 360+_sin(turn)*length, y = 232-_sin(turn+0.25)*length;
+ f64 angle = turn*2*sys.math.PI;
+ int x = 360+sys.math.sin(angle)*length, y = 232-sys.math.cos(angle)*length;
c.line(360,232,x,y,thickness,color);
};
val _analog = { !sys.draw.Canvas c, int hour, int minute, int second, int millisecond ->
c.circle(360,232,154,3,GREEN);
for( int i = 0; i < 60; i++ ) {
- f64 turn = i/60.0;
- bool major = i-i/5*5 == 0;
+ f64 angle = i/60.0*2*sys.math.PI;
+ bool major = i%5 == 0;
int inner = major ? 133 : 143;
- int x0 = 360+_sin(turn)*inner, y0 = 232-_sin(turn+0.25)*inner;
- int x1 = 360+_sin(turn)*149, y1 = 232-_sin(turn+0.25)*149;
+ f64 sine = sys.math.sin(angle), cosine = sys.math.cos(angle);
+ int x0 = 360+sine*inner, y0 = 232-cosine*inner;
+ int x1 = 360+sine* 149 , y1 = 232-cosine* 149 ;
c.line(x0,y0,x1,y1,major ? 3 : 1,GREEN);
}
c.text(349,100,"12",2,GREEN); c.text(484,227,"3",2,GREEN);
- c.text(357,354,"6",2,GREEN); c.text(230,227,"9",2,GREEN);
+ c.text(357,354, "6",2,GREEN); c.text(230,227,"9",2,GREEN);
f64 seconds = second+millisecond/1000.0;
f64 minutes = minute+seconds/60.0;
- _hand(c,(hour-hour/12*12+minutes/60.0)/12.0,78,8,GREEN);
+ _hand(c,(hour%12+minutes/60.0)/12.0,78,8,GREEN);
_hand(c,minutes/60.0,112,5,GREEN);
_hand(c,seconds/60.0,128,2,0xc3ffcb);
c.fillCircle(360,232,6,GREEN);
diff --git a/chapter31/docs/examples/Graphics.smp b/chapter31/docs/examples/Graphics.smp
index 8b251fa2..1878e97d 100644
--- a/chapter31/docs/examples/Graphics.smp
+++ b/chapter31/docs/examples/Graphics.smp
@@ -2,13 +2,22 @@
// Pass any argument for a short, self-closing test; otherwise close or press Esc.
val main = { u8[~][] args ->
if( sys.gfx.open("Simple pixels",320,240) != sys.gfx.OK ) return 1;
- val pixels = new u32[320*240];
- for( int y = 0; y < 240; y++ )
- for( int x = 0; x < 320; x++ )
- pixels[y*320+x] = (x*255/319 << 16) | (y*255/239 << 8) | 64;
- int result = sys.gfx.present(pixels);
+ val c = new sys.draw.Canvas(320,240);
+ int result = sys.gfx.OK;
+ bool dirty = true;
int frames = 0;
while( result == sys.gfx.OK ) {
+ if( c.resize(sys.gfx.width(),sys.gfx.height()) ) dirty = true;
+ if( dirty ) {
+ // The gradient fills the window, including non-4:3 shapes.
+ int dx = c.width > 1 ? c.width-1 : 1, dy = c.height > 1 ? c.height-1 : 1;
+ for( int y = 0; y < c.height; y++ )
+ for( int x = 0; x < c.width; x++ )
+ c.pixels[y*c.width+x] = (x*255/dx << 16) | (y*255/dy << 8) | 64;
+ result = sys.gfx.presentSize(c.pixels,c.width,c.height);
+ if( result != sys.gfx.OK ) break;
+ dirty = false;
+ }
result = sys.gfx.poll(true);
if( args# > 1 && ++frames == 5 ) break;
}
diff --git a/chapter31/docs/examples/README.md b/chapter31/docs/examples/README.md
index 20b644cf..05dcf6cb 100644
--- a/chapter31/docs/examples/README.md
+++ b/chapter31/docs/examples/README.md
@@ -2,25 +2,30 @@
These programs live beside the documentation so readers can find and run them.
Their non-graphical native regression tests run as part of `make tests`.
+All four graphical demos support window resizing. Clock, Tic-tac-toe, and
+Breakout scale their base layouts uniformly and center them in the window;
+mouse input follows the same transform. Breakout keeps its physics in base
+coordinates, so resizing preserves the current game and ball speed. The pixel
+gradient fills the entire window at its new resolution.
The optional [pixel-window example](Graphics.smp) uses MiniFB; see
-[graphics setup](../graphics.md). `make run-graphics` opens it explicitly.
+[graphics setup](../../src/main/smp/sys/gfx.md). `make run-graphics` opens it explicitly.
The [graphical tic-tac-toe](TicTacToeGraphical.smp) uses the Simple
-[drawing library](../drawing.md). Run it with
-`make run-graphical-tictactoe CTAGS=`; click a cell or press 1–9, R/Space to
+[drawing library](../../src/main/smp/sys/draw/README.md). Run it with
+`make run-graphical-tictactoe`; click a cell or press 1–9, R/Space to
replay, and Q/Escape to quit. The terminal game below remains available.
-Optional [background audio](../audio.md) supplies soft move and win/loss cues.
+Optional [background audio](../../src/main/smp/sys/audio.md) supplies soft move and win/loss cues.
-The [digital and analog clock](Clock.smp) demonstrates the [time library](../time.md),
+The [digital and analog clock](Clock.smp) demonstrates the [time library](../../src/main/smp/sys/time/README.md),
green seven-segment digits, smooth clock hands, and a reusable software button.
-Run `make run-clock CTAGS=`; click the button or press Space to switch faces,
+Run `make run-clock`; click the button or press Space to switch faces,
and Q/Escape to exit. Both faces show system-local time.
-`make clock-example CTAGS=` builds it without starting a window.
+`make clock-example` builds it without starting a window.
The [Breakout game](Breakout.smp) has 24 columns and 8 rows, with colors and
point values by depth: 1 at the bottom through 8 at the top, 864 points total.
Clear the wall before losing all three balls. Mouse movement or the arrow keys
move the paddle; Space/left click serves, P pauses, R restarts, Q/Escape exits.
-Run `make run-breakout CTAGS=` or build only with `make breakout CTAGS=`.
+Run `make run-breakout` or build only with `make breakout`.
The familiar paddle, serve, and limited-ball rules follow
[Atari's Breakout instructions](https://atari.com/pages/breakout).
@@ -43,7 +48,7 @@ the boost, and clearing the whole wall without a display or audio device.
From `chapter31`, build the tic-tac-toe executable (without starting it):
```sh
-make lib tictactoe CTAGS=
+make lib tictactoe
```
Run the Windows build from PowerShell:
@@ -52,9 +57,15 @@ Run the Windows build from PowerShell:
.\build\examples\x86_64_v2_win64\TicTacToe.exe
```
-Or from Cygwin:
+Or from Command Prompt (`cmd.exe`):
-```sh
+```bat
+.\build\examples\x86_64_v2_win64\TicTacToe.exe
+```
+
+Or from Bash (Cygwin, using the Windows build):
+
+```bash
./build/examples/x86_64_v2_win64/TicTacToe.exe
```
@@ -66,7 +77,7 @@ directory in WSL. Separate Java and native output directories let the Windows
and Linux builds coexist:
```sh
-make lib tictactoe CLZDIR=build/classes-linux CTAGS=
+make lib tictactoe CLZDIR=build/classes-linux
./build/examples/x86_64_v2_SystemV/TicTacToe
```
diff --git a/chapter31/docs/examples/TicTacToeGraphical.smp b/chapter31/docs/examples/TicTacToeGraphical.smp
index d3d575a7..72ee6522 100644
--- a/chapter31/docs/examples/TicTacToeGraphical.smp
+++ b/chapter31/docs/examples/TicTacToeGraphical.smp
@@ -9,7 +9,7 @@ val main = { u8[~][] args ->
if( sys.gfx.open("Simple tic-tac-toe",screen.width,screen.height) != sys.gfx.OK ) return 1;
sys.audio.open(); // Audio is optional; failure leaves the game silent.
_draw(screen,board,-1);
- int result = sys.gfx.present(screen.pixels);
+ int result = sys.gfx.presentSize(screen.pixels,screen.width,screen.height);
bool mouseHeld = false, keyHeld = false, replayHeld = false;
int hover = -1, frames = 0;
@@ -19,8 +19,9 @@ val main = { u8[~][] args ->
if( sys.gfx.key('Q') ) break;
bool down = sys.gfx.button(sys.gfx.LEFT);
bool replay = sys.gfx.key('R') || sys.gfx.key(' ');
- int square = _square(sys.gfx.mouseX(),sys.gfx.mouseY());
- bool dirty = square != hover;
+ bool resized = screen.resize(sys.gfx.width(),sys.gfx.height());
+ int square = _square(screen.localX(sys.gfx.mouseX()),screen.localY(sys.gfx.mouseY()));
+ bool dirty = resized || square != hover;
hover = square;
if( replay && !replayHeld ) { sys.audio.stop(); _reset(board); dirty = true; }
bool digit = false;
@@ -41,7 +42,7 @@ val main = { u8[~][] args ->
replayHeld = replay;
if( dirty ) {
_draw(screen,board,hover);
- result = sys.gfx.present(screen.pixels);
+ result = sys.gfx.presentSize(screen.pixels,screen.width,screen.height);
}
if( args# > 1 && ++frames == 5 ) break;
}
@@ -143,13 +144,13 @@ val _draw = { !sys.draw.Canvas screen, u8[~] board, int hover ->
screen.text(484,145,"CPU",2,0xa2b9b7);
screen.fillRect(48,168,504,504,paper);
if( !finished && hover >= 0 && hover < 9 && board[hover] == ' ' )
- screen.fillRect(48+(hover-hover/3*3)*168,168+hover/3*168,168,168,0xd9e8de);
+ screen.fillRect(48+(hover%3)*168,168+hover/3*168,168,168,0xd9e8de);
for( int i = 1; i < 3; i++ ) {
screen.fillRect(48+i*168-3,168,6,504,ink);
screen.fillRect(48,168+i*168-3,504,6,ink);
}
for( int i = 0; i < 9; i++ ) {
- int cx = 132+(i-i/3*3)*168, cy = 252+i/3*168;
+ int cx = 132+(i%3)*168, cy = 252+i/3*168;
if( board[i] == 'X' )
screen.line(cx-38,cy-38,cx+38,cy+38,12,cross).line(cx+38,cy-38,cx-38,cy+38,12,cross);
else if( board[i] == 'O' ) screen.circle(cx,cy,48,11,ring);
@@ -160,7 +161,7 @@ val _draw = { !sys.draw.Canvas screen, u8[~] board, int hover ->
if( line >= 0 ) {
int first = line < 3 ? line*3 : line < 6 ? line-3 : line == 6 ? 0 : 2;
int last = line < 3 ? first+2 : line < 6 ? first+6 : line == 6 ? 8 : 6;
- screen.line(132+(first-first/3*3)*168,252+first/3*168,132+(last-last/3*3)*168,252+last/3*168,5,0xeab64e);
+ screen.line(132+(first%3)*168,252+first/3*168,132+(last%3)*168,252+last/3*168,5,0xeab64e);
}
screen.text(48,704,"CLICK A SQUARE OR PRESS 1-9",3,paper);
screen.text(48,738,"R OR SPACE REPLAY Q OR ESC QUIT",3,0xa2b9b7);