start of rename to cell
BIN
prosperon/examples/bunnymark/bunny.png
Normal file
|
After Width: | Height: | Size: 449 B |
5
prosperon/examples/bunnymark/config.js
Normal file
@@ -0,0 +1,5 @@
|
||||
return {
|
||||
title:"Bunnymark",
|
||||
width:1200,
|
||||
height:600,
|
||||
}
|
||||
70
prosperon/examples/bunnymark/main.js
Normal file
@@ -0,0 +1,70 @@
|
||||
var draw = use('draw2d')
|
||||
var render = use('render')
|
||||
var graphics = use('graphics')
|
||||
var sprite = use('sprite')
|
||||
var geom = use('geometry')
|
||||
var input = use('controller')
|
||||
var config = use('config')
|
||||
var color = use('color')
|
||||
|
||||
var bunnyTex = graphics.texture("bunny")
|
||||
|
||||
// We'll store our bunnies in an array of objects: { x, y, vx, vy }
|
||||
var bunnies = []
|
||||
|
||||
// Start with some initial bunnies:
|
||||
for (var i = 0; i < 100; i++) {
|
||||
bunnies.push({
|
||||
x: Math.random() * config.width,
|
||||
y: Math.random() * config.height,
|
||||
vx: (Math.random() * 300) - 150,
|
||||
vy: (Math.random() * 300) - 150
|
||||
})
|
||||
}
|
||||
|
||||
var fpsSamples = []
|
||||
var fpsAvg = 0
|
||||
|
||||
this.update = function(dt) {
|
||||
// Compute FPS average over the last 60 frames:
|
||||
var currentFPS = 1 / dt
|
||||
fpsSamples.push(currentFPS)
|
||||
if (fpsSamples.length > 60) fpsSamples.shift()
|
||||
var sum = 0
|
||||
for (var f of fpsSamples) sum += f
|
||||
fpsAvg = sum / fpsSamples.length
|
||||
|
||||
// If left mouse is down, spawn some more bunnies:
|
||||
var mouse = input.mousestate()
|
||||
if (mouse.left)
|
||||
for (var i = 0; i < 50; i++) {
|
||||
bunnies.push({
|
||||
x: mouse.x,
|
||||
y: mouse.y,
|
||||
vx: (Math.random() * 300) - 150,
|
||||
vy: (Math.random() * 300) - 150
|
||||
})
|
||||
}
|
||||
|
||||
// Update bunny positions and bounce them inside the screen:
|
||||
for (var i = 0; i < bunnies.length; i++) {
|
||||
var b = bunnies[i]
|
||||
b.x += b.vx * dt
|
||||
b.y += b.vy * dt
|
||||
|
||||
// Bounce off left/right edges
|
||||
if (b.x < 0) { b.x = 0; b.vx = -b.vx }
|
||||
else if (b.x > config.width) { b.x = config.width; b.vx = -b.vx }
|
||||
|
||||
// Bounce off bottom/top edges
|
||||
if (b.y < 0) { b.y = 0; b.vy = -b.vy }
|
||||
else if (b.y > config.height) { b.y = config.height; b.vy = -b.vy }
|
||||
}
|
||||
}
|
||||
|
||||
this.hud = function() {
|
||||
draw.images(bunnyTex, bunnies)
|
||||
|
||||
var msg = 'FPS: ' + fpsAvg.toFixed(2) + ' Bunnies: ' + bunnies.length
|
||||
draw.text(msg, {x:0, y:0, width:config.width, height:40}, undefined, 0, color.white, 0)
|
||||
}
|
||||
BIN
prosperon/examples/chess/black_bishop.png
Normal file
|
After Width: | Height: | Size: 390 B |
BIN
prosperon/examples/chess/black_king.png
Normal file
|
After Width: | Height: | Size: 438 B |
BIN
prosperon/examples/chess/black_knight.png
Normal file
|
After Width: | Height: | Size: 398 B |
BIN
prosperon/examples/chess/black_pawn.png
Normal file
|
After Width: | Height: | Size: 337 B |
BIN
prosperon/examples/chess/black_queen.png
Normal file
|
After Width: | Height: | Size: 390 B |
BIN
prosperon/examples/chess/black_rook.png
Normal file
|
After Width: | Height: | Size: 379 B |
9
prosperon/examples/chess/config.js
Normal file
@@ -0,0 +1,9 @@
|
||||
// Chess game configuration for Moth framework
|
||||
return {
|
||||
title: "Chess",
|
||||
resolution: { width: 480, height: 480 },
|
||||
internal_resolution: { width: 480, height: 480 },
|
||||
fps: 60,
|
||||
clearColor: [22/255, 120/255, 194/255, 1],
|
||||
mode: 'stretch' // No letterboxing for chess
|
||||
};
|
||||
57
prosperon/examples/chess/grid.js
Normal file
@@ -0,0 +1,57 @@
|
||||
var CELLS = Symbol()
|
||||
|
||||
var key = function key(x,y) { return `${x},${y}` }
|
||||
|
||||
function grid(w, h)
|
||||
{
|
||||
this[CELLS] = new Map()
|
||||
this.width = w;
|
||||
this.height = h;
|
||||
}
|
||||
|
||||
grid.prototype = {
|
||||
cell(x,y) {
|
||||
var k = key(x,y)
|
||||
if (!this[CELLS].has(k)) this[CELLS].set(k,[])
|
||||
return this[CELLS].get(k)
|
||||
},
|
||||
|
||||
add(entity, pos) {
|
||||
this.cell(pos.x, pos.y).push(entity);
|
||||
entity.coord = pos.slice();
|
||||
},
|
||||
|
||||
remove(entity, pos) {
|
||||
var c = this.cell(pos.x, pos.y);
|
||||
c.splice(c.indexOf(entity), 1);
|
||||
},
|
||||
|
||||
at(pos) {
|
||||
return this.cell(pos.x, pos.y);
|
||||
},
|
||||
|
||||
inBounds(pos) {
|
||||
return pos.x >= 0 && pos.x < this.width && pos.y >= 0 && pos.y < this.height;
|
||||
},
|
||||
|
||||
each(fn) {
|
||||
for (var [k, list] of this[CELLS])
|
||||
for (var p of list) fn(p, p.coord);
|
||||
},
|
||||
|
||||
toString() {
|
||||
var out = `grid [${this.width}x${this.height}]
|
||||
`
|
||||
for (var y = 0; y < this.height; y++) {
|
||||
for (var x = 0; x < this.width; x++) {
|
||||
var cell = this.at([x,y]);
|
||||
out += cell.length
|
||||
}
|
||||
if (y !== this.height - 1) out += "\n"
|
||||
}
|
||||
|
||||
return out
|
||||
},
|
||||
}
|
||||
|
||||
return grid
|
||||
400
prosperon/examples/chess/main.js
Normal file
@@ -0,0 +1,400 @@
|
||||
/* main.js – runs the demo with your prototype-based grid */
|
||||
|
||||
var json = use('json')
|
||||
var draw2d = use('draw2d')
|
||||
|
||||
var blob = use('blob')
|
||||
|
||||
/*──── import our pieces + systems ───────────────────────────────────*/
|
||||
var Grid = use('examples/chess/grid'); // your new ctor
|
||||
var MovementSystem = use('examples/chess/movement').MovementSystem;
|
||||
var startingPos = use('examples/chess/pieces').startingPosition;
|
||||
var rules = use('examples/chess/rules');
|
||||
|
||||
/*──── build board ───────────────────────────────────────────────────*/
|
||||
var grid = new Grid(8, 8);
|
||||
grid.width = 8; // (the ctor didn't store them)
|
||||
grid.height = 8;
|
||||
|
||||
var mover = new MovementSystem(grid, rules);
|
||||
startingPos(grid);
|
||||
|
||||
/*──── networking and game state ─────────────────────────────────────*/
|
||||
var gameState = 'waiting'; // 'waiting', 'searching', 'server_waiting', 'connected'
|
||||
var isServer = false;
|
||||
var opponent = null;
|
||||
var myColor = null; // 'white' or 'black'
|
||||
var isMyTurn = false;
|
||||
|
||||
function updateTitle() {
|
||||
var title = "Misty Chess - ";
|
||||
|
||||
switch(gameState) {
|
||||
case 'waiting':
|
||||
title += "Press S to start server or J to join";
|
||||
break;
|
||||
case 'searching':
|
||||
title += "Searching for server...";
|
||||
break;
|
||||
case 'server_waiting':
|
||||
title += "Waiting for player to join...";
|
||||
break;
|
||||
case 'connected':
|
||||
if (myColor) {
|
||||
title += (mover.turn === myColor ? "Your turn (" + myColor + ")" : "Opponent's turn (" + mover.turn + ")");
|
||||
} else {
|
||||
title += mover.turn + " turn";
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
log.console(title)
|
||||
}
|
||||
|
||||
// Initialize title
|
||||
updateTitle();
|
||||
|
||||
/*──── mouse → click-to-move ─────────────────────────────────────────*/
|
||||
var selectPos = null;
|
||||
var hoverPos = null;
|
||||
var holdingPiece = false;
|
||||
|
||||
var opponentMousePos = null;
|
||||
var opponentHoldingPiece = false;
|
||||
var opponentSelectPos = null;
|
||||
|
||||
function handleMouseButtonDown(e) {
|
||||
if (e.which !== 0) return;
|
||||
|
||||
// Don't allow piece selection unless we have an opponent
|
||||
if (gameState !== 'connected' || !opponent) return;
|
||||
|
||||
var mx = e.mouse.x;
|
||||
var my = e.mouse.y;
|
||||
|
||||
var c = [Math.floor(mx / 60), Math.floor(my / 60)];
|
||||
if (!grid.inBounds(c)) return;
|
||||
|
||||
var cell = grid.at(c);
|
||||
if (cell.length && cell[0].colour === mover.turn) {
|
||||
selectPos = c;
|
||||
holdingPiece = true;
|
||||
// Send pickup notification to opponent
|
||||
if (opponent) {
|
||||
send(opponent, {
|
||||
type: 'piece_pickup',
|
||||
pos: c
|
||||
});
|
||||
}
|
||||
} else {
|
||||
selectPos = null;
|
||||
}
|
||||
}
|
||||
|
||||
function handleMouseButtonUp(e) {
|
||||
if (e.which !== 0 || !holdingPiece || !selectPos) return;
|
||||
|
||||
// Don't allow moves unless we have an opponent and it's our turn
|
||||
if (gameState !== 'connected' || !opponent || !isMyTurn) {
|
||||
holdingPiece = false;
|
||||
return;
|
||||
}
|
||||
|
||||
var mx = e.mouse.x;
|
||||
var my = e.mouse.y;
|
||||
|
||||
var c = [Math.floor(mx / 60), Math.floor(my / 60)];
|
||||
if (!grid.inBounds(c)) {
|
||||
holdingPiece = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (mover.tryMove(grid.at(selectPos)[0], c)) {
|
||||
log.console("Made move from", selectPos, "to", c);
|
||||
// Send move to opponent
|
||||
log.console("Sending move to opponent:", opponent);
|
||||
send(opponent, {
|
||||
type: 'move',
|
||||
from: selectPos,
|
||||
to: c
|
||||
});
|
||||
isMyTurn = false; // It's now opponent's turn
|
||||
log.console("Move sent, now opponent's turn");
|
||||
selectPos = null;
|
||||
updateTitle();
|
||||
}
|
||||
|
||||
holdingPiece = false;
|
||||
|
||||
// Send piece drop notification to opponent
|
||||
if (opponent) {
|
||||
send(opponent, {
|
||||
type: 'piece_drop'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function handleMouseMotion(e) {
|
||||
var mx = e.pos.x;
|
||||
var my = e.pos.y;
|
||||
|
||||
var c = [Math.floor(mx / 60), Math.floor(my / 60)];
|
||||
if (!grid.inBounds(c)) {
|
||||
hoverPos = null;
|
||||
return;
|
||||
}
|
||||
|
||||
hoverPos = c;
|
||||
|
||||
// Send mouse position to opponent in real-time
|
||||
if (opponent && gameState === 'connected') {
|
||||
send(opponent, {
|
||||
type: 'mouse_move',
|
||||
pos: c,
|
||||
holding: holdingPiece,
|
||||
selectPos: selectPos
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function handleKeyDown(e) {
|
||||
// S key - start server
|
||||
if (e.scancode === 22 && gameState === 'waiting') { // S key
|
||||
startServer();
|
||||
}
|
||||
// J key - join server
|
||||
else if (e.scancode === 13 && gameState === 'waiting') { // J key
|
||||
joinServer();
|
||||
}
|
||||
}
|
||||
|
||||
/*──── drawing helpers ───────────────────────────────────────────────*/
|
||||
/* ── constants ─────────────────────────────────────────────────── */
|
||||
var S = 60; // square size in px
|
||||
var light = [0.93,0.93,0.93,1];
|
||||
var dark = [0.25,0.25,0.25,1];
|
||||
var allowedColor = [1.0, 0.84, 0.0, 1.0]; // Gold for allowed moves
|
||||
var myMouseColor = [0.0, 1.0, 0.0, 1.0]; // Green for my mouse
|
||||
var opponentMouseColor = [1.0, 0.0, 0.0, 1.0]; // Red for opponent mouse
|
||||
|
||||
/* ── draw one 8×8 chess board ──────────────────────────────────── */
|
||||
function drawBoard() {
|
||||
for (var y = 0; y < 8; ++y)
|
||||
for (var x = 0; x < 8; ++x) {
|
||||
var isMyHover = hoverPos && hoverPos[0] === x && hoverPos[1] === y;
|
||||
var isOpponentHover = opponentMousePos && opponentMousePos[0] === x && opponentMousePos[1] === y;
|
||||
var isValidMove = selectPos && holdingPiece && isValidMoveForTurn(selectPos, [x, y]);
|
||||
|
||||
var color = ((x+y)&1) ? dark : light;
|
||||
|
||||
if (isValidMove) {
|
||||
color = allowedColor; // Gold for allowed moves
|
||||
} else if (isMyHover && !isOpponentHover) {
|
||||
color = myMouseColor; // Green for my mouse
|
||||
} else if (isOpponentHover) {
|
||||
color = opponentMouseColor; // Red for opponent mouse
|
||||
}
|
||||
|
||||
draw2d.rectangle(
|
||||
{ x: x*S, y: y*S, width: S, height: S },
|
||||
{ thickness: 0 },
|
||||
{ color: color }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function isValidMoveForTurn(from, to) {
|
||||
if (!grid.inBounds(to)) return false;
|
||||
|
||||
var piece = grid.at(from)[0];
|
||||
if (!piece) return false;
|
||||
|
||||
// Check if the destination has a piece of the same color
|
||||
var destCell = grid.at(to);
|
||||
if (destCell.length && destCell[0].colour === piece.colour) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return rules.canMove(piece, from, to, grid);
|
||||
}
|
||||
|
||||
/* ── draw every live piece ─────────────────────────────────────── */
|
||||
function drawPieces() {
|
||||
grid.each(function (piece) {
|
||||
if (piece.captured) return;
|
||||
|
||||
// Skip drawing the piece being held (by me or opponent)
|
||||
if (holdingPiece && selectPos &&
|
||||
piece.coord[0] === selectPos[0] &&
|
||||
piece.coord[1] === selectPos[1]) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip drawing the piece being held by opponent
|
||||
if (opponentHoldingPiece && opponentSelectPos &&
|
||||
piece.coord[0] === opponentSelectPos[0] &&
|
||||
piece.coord[1] === opponentSelectPos[1]) {
|
||||
return;
|
||||
}
|
||||
|
||||
var r = { x: piece.coord[0]*S, y: piece.coord[1]*S,
|
||||
width:S, height:S };
|
||||
|
||||
draw2d.image(piece.sprite, r);
|
||||
});
|
||||
|
||||
// Draw the held piece at the mouse position if we're holding one
|
||||
if (holdingPiece && selectPos && hoverPos) {
|
||||
var piece = grid.at(selectPos)[0];
|
||||
if (piece) {
|
||||
var r = { x: hoverPos[0]*S, y: hoverPos[1]*S,
|
||||
width:S, height:S };
|
||||
|
||||
draw2d.image(piece.sprite, r);
|
||||
}
|
||||
}
|
||||
|
||||
// Draw opponent's held piece if they're dragging one
|
||||
if (opponentHoldingPiece && opponentSelectPos && opponentMousePos) {
|
||||
var opponentPiece = grid.at(opponentSelectPos)[0];
|
||||
if (opponentPiece) {
|
||||
var r = { x: opponentMousePos[0]*S, y: opponentMousePos[1]*S,
|
||||
width:S, height:S };
|
||||
|
||||
// Draw with slight transparency to show it's the opponent's piece
|
||||
draw2d.image(opponentPiece.sprite, r);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function update(dt)
|
||||
{
|
||||
return {}
|
||||
}
|
||||
|
||||
function draw()
|
||||
{
|
||||
draw2d.clear()
|
||||
drawBoard()
|
||||
drawPieces()
|
||||
draw2d.text("HELL", {x: 100, y: 100}, 'fonts/c64.ttf', 16, [1,1,1,1])
|
||||
return draw2d.get_commands()
|
||||
}
|
||||
|
||||
|
||||
function startServer() {
|
||||
gameState = 'server_waiting';
|
||||
isServer = true;
|
||||
myColor = 'white';
|
||||
isMyTurn = true;
|
||||
updateTitle();
|
||||
|
||||
$_.portal(e => {
|
||||
log.console("Portal received contact message");
|
||||
// Reply with this actor to establish connection
|
||||
log.console (json.encode($_))
|
||||
send(e, $_);
|
||||
log.console("Portal replied with server actor");
|
||||
}, 5678);
|
||||
}
|
||||
|
||||
function joinServer() {
|
||||
gameState = 'searching';
|
||||
updateTitle();
|
||||
|
||||
function contact_fn(actor, reason) {
|
||||
log.console("CONTACTED!", actor ? "SUCCESS" : "FAILED", reason);
|
||||
if (actor) {
|
||||
opponent = actor;
|
||||
log.console("Connection established with server, sending join request");
|
||||
|
||||
// Send a greet message with our actor object
|
||||
send(opponent, {
|
||||
type: 'greet',
|
||||
client_actor: $_
|
||||
});
|
||||
} else {
|
||||
log.console(`Failed to connect: ${json.encode(reason)}`);
|
||||
gameState = 'waiting';
|
||||
updateTitle();
|
||||
}
|
||||
}
|
||||
|
||||
$_.contact(contact_fn, {
|
||||
address: "192.168.0.149",
|
||||
port: 5678
|
||||
});
|
||||
}
|
||||
|
||||
$_.receiver(e => {
|
||||
if (e.kind == 'update')
|
||||
send(e, update(e.dt))
|
||||
else if (e.kind == 'draw')
|
||||
send(e, draw())
|
||||
else if (e.type === 'game_start' || e.type === 'move' || e.type === 'greet')
|
||||
log.console("Receiver got message:", e.type, e);
|
||||
|
||||
if (e.type === 'greet') {
|
||||
log.console("Server received greet from client");
|
||||
// Store the client's actor object for ongoing communication
|
||||
opponent = e.client_actor;
|
||||
log.console("Stored client actor:", json.encode(opponent));
|
||||
gameState = 'connected';
|
||||
updateTitle();
|
||||
|
||||
// Send game_start to the client
|
||||
log.console("Sending game_start to client");
|
||||
send(opponent, {
|
||||
type: 'game_start',
|
||||
your_color: 'black'
|
||||
});
|
||||
log.console("game_start message sent to client");
|
||||
}
|
||||
else if (e.type === 'game_start') {
|
||||
log.console("Game starting, I am:", e.your_color);
|
||||
myColor = e.your_color;
|
||||
isMyTurn = (myColor === 'white');
|
||||
gameState = 'connected';
|
||||
updateTitle();
|
||||
} else if (e.type === 'move') {
|
||||
log.console("Received move from opponent:", e.from, "to", e.to);
|
||||
// Apply opponent's move
|
||||
var fromCell = grid.at(e.from);
|
||||
if (fromCell.length) {
|
||||
var piece = fromCell[0];
|
||||
if (mover.tryMove(piece, e.to)) {
|
||||
isMyTurn = true; // It's now our turn
|
||||
updateTitle();
|
||||
log.console("Applied opponent move, now my turn");
|
||||
} else {
|
||||
log.console("Failed to apply opponent move");
|
||||
}
|
||||
} else {
|
||||
log.console("No piece found at from position");
|
||||
}
|
||||
} else if (e.type === 'mouse_move') {
|
||||
// Update opponent's mouse position
|
||||
opponentMousePos = e.pos;
|
||||
opponentHoldingPiece = e.holding;
|
||||
opponentSelectPos = e.selectPos;
|
||||
} else if (e.type === 'piece_pickup') {
|
||||
// Opponent picked up a piece
|
||||
opponentSelectPos = e.pos;
|
||||
opponentHoldingPiece = true;
|
||||
} else if (e.type === 'piece_drop') {
|
||||
// Opponent dropped their piece
|
||||
opponentHoldingPiece = false;
|
||||
opponentSelectPos = null;
|
||||
} else if (e.type === 'mouse_button_down') {
|
||||
handleMouseButtonDown(e)
|
||||
} else if (e.type === 'mouse_button_up') {
|
||||
handleMouseButtonUp(e)
|
||||
} else if (e.type === 'mouse_motion') {
|
||||
handleMouseMotion(e)
|
||||
} else if (e.type === 'key_down') {
|
||||
handleKeyDown(e)
|
||||
}
|
||||
})
|
||||
|
||||
var parseq = use('parseq', $_.delay)
|
||||
for (var i in parseq) log.console(i)
|
||||
32
prosperon/examples/chess/movement.js
Normal file
@@ -0,0 +1,32 @@
|
||||
var MovementSystem = function(grid, rules) {
|
||||
this.grid = grid;
|
||||
this.rules = rules || {}; // expects { canMove: fn }
|
||||
this.turn = 'white';
|
||||
}
|
||||
|
||||
MovementSystem.prototype.tryMove = function (piece, to) {
|
||||
if (piece.colour !== this.turn) return false;
|
||||
|
||||
// normalise ‘to’ into our hybrid coord
|
||||
var dest = [to.x !== undefined ? to.x : to[0],
|
||||
to.y !== undefined ? to.y : to[1]];
|
||||
|
||||
if (!this.grid.inBounds(dest)) return false;
|
||||
if (!this.rules.canMove(piece, piece.coord, dest, this.grid)) return false;
|
||||
|
||||
var victims = this.grid.at(dest);
|
||||
if (victims.length && victims[0].colour === piece.colour) return false;
|
||||
if (victims.length) victims[0].captured = true;
|
||||
|
||||
this.grid.remove(piece, piece.coord);
|
||||
this.grid.add (piece, dest);
|
||||
|
||||
// grid.add() re-creates coord; re-add .x/.y fields:
|
||||
piece.coord.x = dest.x;
|
||||
piece.coord.y = dest.y;
|
||||
|
||||
this.turn = (this.turn === 'white') ? 'black' : 'white';
|
||||
return true;
|
||||
};
|
||||
|
||||
return { MovementSystem: MovementSystem };
|
||||
29
prosperon/examples/chess/pieces.js
Normal file
@@ -0,0 +1,29 @@
|
||||
/* pieces.js – simple data holders + starting layout */
|
||||
function Piece(kind, colour) {
|
||||
this.kind = kind; // "pawn" etc.
|
||||
this.colour = colour; // "white"/"black"
|
||||
this.sprite = colour + '_' + kind; // for draw2d.image
|
||||
this.captured = false;
|
||||
this.coord = [0,0];
|
||||
}
|
||||
Piece.prototype.toString = function () {
|
||||
return this.colour.charAt(0) + this.kind.charAt(0).toUpperCase();
|
||||
};
|
||||
|
||||
function startingPosition(grid) {
|
||||
var W = 'white', B = 'black', x;
|
||||
|
||||
// pawns
|
||||
for (x = 0; x < 8; x++) {
|
||||
grid.add(new Piece('pawn', W), [x, 6]);
|
||||
grid.add(new Piece('pawn', B), [x, 1]);
|
||||
}
|
||||
// major pieces
|
||||
var back = ['rook','knight','bishop','queen','king','bishop','knight','rook'];
|
||||
for (x = 0; x < 8; x++) {
|
||||
grid.add(new Piece(back[x], W), [x, 7]);
|
||||
grid.add(new Piece(back[x], B), [x, 0]);
|
||||
}
|
||||
}
|
||||
|
||||
return { Piece, startingPosition };
|
||||
BIN
prosperon/examples/chess/prosperon
Executable file
45
prosperon/examples/chess/rules.js
Normal file
@@ -0,0 +1,45 @@
|
||||
/* helper – robust coord access */
|
||||
function cx(c) { return (c.x !== undefined) ? c.x : c[0]; }
|
||||
function cy(c) { return (c.y !== undefined) ? c.y : c[1]; }
|
||||
|
||||
/* simple move-shape checks */
|
||||
var deltas = {
|
||||
pawn: function (pc, dx, dy, grid, to) {
|
||||
var dir = (pc.colour === 'white') ? -1 : 1;
|
||||
var base = (pc.colour === 'white') ? 6 : 1;
|
||||
var one = (dy === dir && dx === 0 && grid.at(to).length === 0);
|
||||
var two = (dy === 2 * dir && dx === 0 && cy(pc.coord) === base &&
|
||||
grid.at({ x: cx(pc.coord), y: cy(pc.coord)+dir }).length === 0 &&
|
||||
grid.at(to).length === 0);
|
||||
var cap = (dy === dir && Math.abs(dx) === 1 && grid.at(to).length);
|
||||
return one || two || cap;
|
||||
},
|
||||
rook : function (pc, dx, dy) { return (dx === 0 || dy === 0); },
|
||||
bishop: function (pc, dx, dy) { return Math.abs(dx) === Math.abs(dy); },
|
||||
queen : function (pc, dx, dy) { return (dx === 0 || dy === 0 || Math.abs(dx) === Math.abs(dy)); },
|
||||
knight: function (pc, dx, dy) { return (Math.abs(dx) === 1 && Math.abs(dy) === 2) ||
|
||||
(Math.abs(dx) === 2 && Math.abs(dy) === 1); },
|
||||
king : function (pc, dx, dy) { return Math.max(Math.abs(dx), Math.abs(dy)) === 1; }
|
||||
};
|
||||
|
||||
function clearLine(from, to, grid) {
|
||||
var dx = Math.sign(cx(to) - cx(from));
|
||||
var dy = Math.sign(cy(to) - cy(from));
|
||||
var x = cx(from) + dx, y = cy(from) + dy;
|
||||
while (x !== cx(to) || y !== cy(to)) {
|
||||
if (grid.at({ x: x, y: y }).length) return false;
|
||||
x += dx; y += dy;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function canMove(piece, from, to, grid) {
|
||||
var dx = cx(to) - cx(from);
|
||||
var dy = cy(to) - cy(from);
|
||||
var f = deltas[piece.kind];
|
||||
if (!f || !f(piece, dx, dy, grid, to)) return false;
|
||||
if (piece.kind === 'knight') return true;
|
||||
return clearLine(from, to, grid);
|
||||
}
|
||||
|
||||
return { canMove };
|
||||
BIN
prosperon/examples/chess/white_bishop.png
Normal file
|
After Width: | Height: | Size: 376 B |
BIN
prosperon/examples/chess/white_king.png
Normal file
|
After Width: | Height: | Size: 403 B |
BIN
prosperon/examples/chess/white_knight.png
Normal file
|
After Width: | Height: | Size: 381 B |
BIN
prosperon/examples/chess/white_pawn.png
Normal file
|
After Width: | Height: | Size: 313 B |
BIN
prosperon/examples/chess/white_queen.png
Normal file
|
After Width: | Height: | Size: 378 B |
BIN
prosperon/examples/chess/white_rook.png
Normal file
|
After Width: | Height: | Size: 378 B |
5
prosperon/examples/pong/config.js
Normal file
@@ -0,0 +1,5 @@
|
||||
return {
|
||||
title: "Pong",
|
||||
width: 858,
|
||||
height: 525
|
||||
}
|
||||
86
prosperon/examples/pong/main.js
Normal file
@@ -0,0 +1,86 @@
|
||||
// main.js
|
||||
var draw = use('draw2d')
|
||||
var input = use('controller')
|
||||
var config = use('config')
|
||||
var color = use('color')
|
||||
|
||||
prosperon.camera.transform.pos = [0,0]
|
||||
|
||||
var paddleW = 10, paddleH = 80
|
||||
var p1 = {x: 30, y: config.height*0.5, speed: 300}
|
||||
var p2 = {x: config.width-30, y: config.height*0.5, speed: 300}
|
||||
var ball = {x: 0, y: 0, vx: 220, vy: 150, size: 10}
|
||||
var score1 = 0, score2 = 0
|
||||
|
||||
function resetBall() {
|
||||
ball.x = config.width*0.5
|
||||
ball.y = config.height*0.5
|
||||
// give it a random vertical bounce
|
||||
ball.vy = (Math.random()<0.5 ? -1:1)*150
|
||||
// keep horizontal speed to the same magnitude
|
||||
ball.vx = ball.vx>0 ? 220 : -220
|
||||
}
|
||||
|
||||
resetBall()
|
||||
|
||||
this.update = function(dt) {
|
||||
// Move paddles: positive Y is up, so W/↑ means p.y += speed
|
||||
if (input.keyboard.down('w')) p1.y += p1.speed*dt
|
||||
if (input.keyboard.down('s')) p1.y -= p1.speed*dt
|
||||
|
||||
// Paddle 2 movement (ArrowUp = up, ArrowDown = down)
|
||||
if (input.keyboard.down('i')) p2.y += p2.speed*dt
|
||||
if (input.keyboard.down('k')) p2.y -= p2.speed*dt
|
||||
|
||||
// Clamp paddles to screen
|
||||
if (p1.y < paddleH*0.5) p1.y = paddleH*0.5
|
||||
if (p1.y > config.height - paddleH*0.5) p1.y = config.height - paddleH*0.5
|
||||
if (p2.y < paddleH*0.5) p2.y = paddleH*0.5
|
||||
if (p2.y > config.height - paddleH*0.5) p2.y = config.height - paddleH*0.5
|
||||
|
||||
// Move ball
|
||||
ball.x += ball.vx*dt
|
||||
ball.y += ball.vy*dt
|
||||
|
||||
// Bounce top/bottom
|
||||
if (ball.y+ball.size*0.5>config.height || ball.y-ball.size*0.5<0) ball.vy = -ball.vy
|
||||
|
||||
// Check paddle collisions
|
||||
// p1 bounding box
|
||||
var left1 = p1.x - paddleW*0.5, right1 = p1.x + paddleW*0.5
|
||||
var top1 = p1.y + paddleH*0.5, bottom1 = p1.y - paddleH*0.5
|
||||
// p2 bounding box
|
||||
var left2 = p2.x - paddleW*0.5, right2 = p2.x + paddleW*0.5
|
||||
var top2 = p2.y + paddleH*0.5, bottom2 = p2.y - paddleH*0.5
|
||||
|
||||
// ball half-edges
|
||||
var l = ball.x - ball.size*0.5, r = ball.x + ball.size*0.5
|
||||
var b = ball.y - ball.size*0.5, t = ball.y + ball.size*0.5
|
||||
|
||||
// Collide with paddle 1?
|
||||
if (r>left1 && l<right1 && t>bottom1 && b<top1)
|
||||
ball.vx = Math.abs(ball.vx)
|
||||
// Collide with paddle 2?
|
||||
if (r>left2 && l<right2 && t>bottom2 && b<top2)
|
||||
ball.vx = -Math.abs(ball.vx)
|
||||
|
||||
// Check left/right out-of-bounds
|
||||
if (r<0) { score2++; resetBall() }
|
||||
if (l>config.width) { score1++; resetBall() }
|
||||
}
|
||||
|
||||
this.hud = function() {
|
||||
// Clear screen black
|
||||
draw.rectangle({x:0, y:0, width:config.width, height:config.height}, [0,0,0,1])
|
||||
|
||||
// Draw paddles
|
||||
draw.rectangle({x:p1.x - paddleW*0.5, y:p1.y - paddleH*0.5, width:paddleW, height:paddleH}, color.white)
|
||||
draw.rectangle({x:p2.x - paddleW*0.5, y:p2.y - paddleH*0.5, width:paddleW, height:paddleH}, color.white)
|
||||
|
||||
// Draw ball
|
||||
draw.rectangle({x:ball.x - ball.size*0.5, y:ball.y - ball.size*0.5, width:ball.size, height:ball.size}, color.white)
|
||||
|
||||
// Simple score display
|
||||
var msg = score1 + " " + score2
|
||||
draw.text(msg, {x:0, y:10, width:config.width, height:40}, undefined, 0, color.white, 0)
|
||||
}
|
||||
5
prosperon/examples/snake/config.js
Normal file
@@ -0,0 +1,5 @@
|
||||
return {
|
||||
title: "Snake",
|
||||
width: 600,
|
||||
height: 600
|
||||
}
|
||||
119
prosperon/examples/snake/main.js
Normal file
@@ -0,0 +1,119 @@
|
||||
// main.js
|
||||
var draw = use('draw2d')
|
||||
var render = use('render')
|
||||
var graphics = use('graphics')
|
||||
var input = use('input')
|
||||
var config = use('config')
|
||||
var color = use('color')
|
||||
|
||||
prosperon.camera.transform.pos = [0,0]
|
||||
|
||||
var cellSize = 20
|
||||
var gridW = Math.floor(config.width / cellSize)
|
||||
var gridH = Math.floor(config.height / cellSize)
|
||||
|
||||
var snake, direction, nextDirection, apple
|
||||
var moveInterval = 0.1
|
||||
var moveTimer = 0
|
||||
var gameState = "playing"
|
||||
|
||||
function resetGame() {
|
||||
var cx = Math.floor(gridW / 2)
|
||||
var cy = Math.floor(gridH / 2)
|
||||
snake = [
|
||||
{x: cx, y: cy},
|
||||
{x: cx-1, y: cy},
|
||||
{x: cx-2, y: cy}
|
||||
]
|
||||
direction = {x:1, y:0}
|
||||
nextDirection = {x:1, y:0}
|
||||
spawnApple()
|
||||
gameState = "playing"
|
||||
moveTimer = 0
|
||||
}
|
||||
|
||||
function spawnApple() {
|
||||
apple = {x:Math.floor(Math.random()*gridW), y:Math.floor(Math.random()*gridH)}
|
||||
// Re-spawn if apple lands on snake
|
||||
for (var i=0; i<snake.length; i++)
|
||||
if (snake[i].x === apple.x && snake[i].y === apple.y) { spawnApple(); return }
|
||||
}
|
||||
|
||||
function wrap(pos) {
|
||||
if (pos.x < 0) pos.x = gridW - 1
|
||||
if (pos.x >= gridW) pos.x = 0
|
||||
if (pos.y < 0) pos.y = gridH - 1
|
||||
if (pos.y >= gridH) pos.y = 0
|
||||
}
|
||||
|
||||
resetGame()
|
||||
|
||||
this.update = function(dt) {
|
||||
if (gameState !== "playing") return
|
||||
moveTimer += dt
|
||||
if (moveTimer < moveInterval) return
|
||||
moveTimer -= moveInterval
|
||||
|
||||
// Update direction
|
||||
direction = {x: nextDirection.x, y: nextDirection.y}
|
||||
|
||||
// New head
|
||||
var head = {x: snake[0].x + direction.x, y: snake[0].y + direction.y}
|
||||
wrap(head)
|
||||
|
||||
// Check collision with body
|
||||
for (var i=0; i<snake.length; i++) {
|
||||
if (snake[i].x === head.x && snake[i].y === head.y) {
|
||||
gameState = "gameover"
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Place head
|
||||
snake.unshift(head)
|
||||
|
||||
// Eat apple?
|
||||
if (head.x === apple.x && head.y === apple.y) spawnApple()
|
||||
else snake.pop()
|
||||
}
|
||||
|
||||
this.hud = function() {
|
||||
// Optional clear screen
|
||||
draw.rectangle({x:0, y:0, width:config.width, height:config.height}, [0,0,0,1])
|
||||
|
||||
// Draw snake
|
||||
for (var i=0; i<snake.length; i++) {
|
||||
var s = snake[i]
|
||||
draw.rectangle({x:s.x*cellSize, y:s.y*cellSize, width:cellSize, height:cellSize}, color.green)
|
||||
}
|
||||
|
||||
// Draw apple
|
||||
draw.rectangle({x:apple.x*cellSize, y:apple.y*cellSize, width:cellSize, height:cellSize}, color.red)
|
||||
|
||||
if (gameState === "gameover") {
|
||||
var msg = "GAME OVER! Press SPACE to restart."
|
||||
draw.text(msg, {x:0, y:config.height*0.5-10, width:config.width, height:20}, undefined, 0, color.white)
|
||||
}
|
||||
}
|
||||
|
||||
// No immediate reversal
|
||||
// "Up" means y=1, so going physically up on screen
|
||||
this.inputs = {
|
||||
up: function() {
|
||||
if (direction.y !== -1) nextDirection = {x:0,y:1}
|
||||
},
|
||||
down: function() {
|
||||
if (direction.y !== 1) nextDirection = {x:0,y:-1}
|
||||
},
|
||||
left: function() {
|
||||
if (direction.x !== 1) nextDirection = {x:-1,y:0}
|
||||
},
|
||||
right: function() {
|
||||
if (direction.x !== -1) nextDirection = {x:1,y:0}
|
||||
},
|
||||
space: function() {
|
||||
if (gameState==="gameover") resetGame()
|
||||
}
|
||||
}
|
||||
|
||||
input.player[0].control(this)
|
||||
187
prosperon/examples/steam_example.js
Normal file
@@ -0,0 +1,187 @@
|
||||
// Steam Integration Example
|
||||
// This example shows how to use Steam achievements and stats
|
||||
|
||||
var steam = use("steam");
|
||||
|
||||
// Achievement names (these should match your Steam app configuration)
|
||||
var ACHIEVEMENTS = {
|
||||
FIRST_WIN: "ACH_FIRST_WIN",
|
||||
PLAY_10_GAMES: "ACH_PLAY_10_GAMES",
|
||||
HIGH_SCORE: "ACH_HIGH_SCORE_1000"
|
||||
};
|
||||
|
||||
// Stat names
|
||||
var STATS = {
|
||||
GAMES_PLAYED: "stat_games_played",
|
||||
TOTAL_SCORE: "stat_total_score",
|
||||
PLAY_TIME: "stat_play_time"
|
||||
};
|
||||
|
||||
var steam_available = false;
|
||||
var stats_loaded = false;
|
||||
|
||||
// Initialize Steam
|
||||
function init_steam() {
|
||||
if (!steam) {
|
||||
log.console("Steam module not available");
|
||||
return false;
|
||||
}
|
||||
|
||||
log.console("Initializing Steam...");
|
||||
steam_available = steam.steam_init();
|
||||
|
||||
if (steam_available) {
|
||||
log.console("Steam initialized successfully");
|
||||
|
||||
// Request current stats/achievements
|
||||
if (steam.stats.stats_request()) {
|
||||
log.console("Stats requested");
|
||||
stats_loaded = true;
|
||||
}
|
||||
} else {
|
||||
log.console("Failed to initialize Steam");
|
||||
}
|
||||
|
||||
return steam_available;
|
||||
}
|
||||
|
||||
// Update Steam (call this regularly, e.g., once per frame)
|
||||
function update_steam() {
|
||||
if (steam_available) {
|
||||
steam.steam_run_callbacks();
|
||||
}
|
||||
}
|
||||
|
||||
// Unlock an achievement
|
||||
function unlock_achievement(achievement_name) {
|
||||
if (!steam_available || !stats_loaded) return false;
|
||||
|
||||
// Check if already unlocked
|
||||
var unlocked = steam.achievement.achievement_get(achievement_name);
|
||||
if (unlocked) {
|
||||
log.console("Achievement already unlocked:", achievement_name);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Unlock it
|
||||
if (steam.achievement.achievement_set(achievement_name)) {
|
||||
log.console("Achievement unlocked:", achievement_name);
|
||||
|
||||
// Store stats to make it permanent
|
||||
steam.stats.stats_store();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Update a stat
|
||||
function update_stat(stat_name, value, is_float) {
|
||||
if (!steam_available || !stats_loaded) return false;
|
||||
|
||||
var success;
|
||||
if (is_float) {
|
||||
success = steam.stats.stats_set_float(stat_name, value);
|
||||
} else {
|
||||
success = steam.stats.stats_set_int(stat_name, value);
|
||||
}
|
||||
|
||||
if (success) {
|
||||
log.console("Stat updated:", stat_name, "=", value);
|
||||
steam.stats.stats_store();
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
// Get a stat value
|
||||
function get_stat(stat_name, is_float) {
|
||||
if (!steam_available || !stats_loaded) return 0;
|
||||
|
||||
if (is_float) {
|
||||
return steam.stats.stats_get_float(stat_name) || 0;
|
||||
} else {
|
||||
return steam.stats.stats_get_int(stat_name) || 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Example game logic
|
||||
var games_played = 0;
|
||||
var total_score = 0;
|
||||
var current_score = 0;
|
||||
|
||||
function start_game() {
|
||||
games_played = get_stat(STATS.GAMES_PLAYED, false);
|
||||
total_score = get_stat(STATS.TOTAL_SCORE, false);
|
||||
current_score = 0;
|
||||
|
||||
log.console("Starting game #" + (games_played + 1));
|
||||
}
|
||||
|
||||
function end_game(score) {
|
||||
current_score = score;
|
||||
games_played++;
|
||||
total_score += score;
|
||||
|
||||
// Update stats
|
||||
update_stat(STATS.GAMES_PLAYED, games_played, false);
|
||||
update_stat(STATS.TOTAL_SCORE, total_score, false);
|
||||
|
||||
// Check for achievements
|
||||
if (games_played === 1) {
|
||||
unlock_achievement(ACHIEVEMENTS.FIRST_WIN);
|
||||
}
|
||||
|
||||
if (games_played >= 10) {
|
||||
unlock_achievement(ACHIEVEMENTS.PLAY_10_GAMES);
|
||||
}
|
||||
|
||||
if (score >= 1000) {
|
||||
unlock_achievement(ACHIEVEMENTS.HIGH_SCORE);
|
||||
}
|
||||
}
|
||||
|
||||
// Cloud save example
|
||||
function save_to_cloud(save_data) {
|
||||
if (!steam_available) return false;
|
||||
|
||||
var json_data = JSON.stringify(save_data);
|
||||
return steam.cloud.cloud_write("savegame.json", json_data);
|
||||
}
|
||||
|
||||
function load_from_cloud() {
|
||||
if (!steam_available) return null;
|
||||
|
||||
var data = steam.cloud.cloud_read("savegame.json");
|
||||
if (data) {
|
||||
// Convert ArrayBuffer to string
|
||||
var decoder = new TextDecoder();
|
||||
var json_str = decoder.decode(data);
|
||||
return JSON.parse(json_str);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
function cleanup_steam() {
|
||||
if (steam_available) {
|
||||
steam.steam_shutdown();
|
||||
log.console("Steam shut down");
|
||||
}
|
||||
}
|
||||
|
||||
// Export the API
|
||||
module.exports = {
|
||||
init: init_steam,
|
||||
update: update_steam,
|
||||
cleanup: cleanup_steam,
|
||||
unlock_achievement: unlock_achievement,
|
||||
update_stat: update_stat,
|
||||
get_stat: get_stat,
|
||||
start_game: start_game,
|
||||
end_game: end_game,
|
||||
save_to_cloud: save_to_cloud,
|
||||
load_from_cloud: load_from_cloud,
|
||||
is_available: function() { return steam_available; }
|
||||
};
|
||||
5
prosperon/examples/tetris/config.js
Normal file
@@ -0,0 +1,5 @@
|
||||
return {
|
||||
title: "Tetris",
|
||||
width:160,
|
||||
height:144
|
||||
}
|
||||
271
prosperon/examples/tetris/main.js
Normal file
@@ -0,0 +1,271 @@
|
||||
var draw = use('draw2d')
|
||||
var input = use('input')
|
||||
var config = use('config')
|
||||
var color = use('color')
|
||||
|
||||
prosperon.camera.transform.pos = [0,0]
|
||||
|
||||
// Board constants
|
||||
var COLS = 10, ROWS = 20
|
||||
var TILE = 6 // each cell is 6x6
|
||||
|
||||
// Board storage (2D), each cell is either 0 or a [r,g,b,a] color
|
||||
var board = []
|
||||
|
||||
// Gravity timing
|
||||
var baseGravity = 0.8 // seconds between drops at level 0
|
||||
var gravityTimer = 0
|
||||
|
||||
// Current piece & position
|
||||
var piece = null
|
||||
var pieceX = 0
|
||||
var pieceY = 0
|
||||
|
||||
// Next piece
|
||||
var nextPiece = null
|
||||
|
||||
// Score/lines/level
|
||||
var score = 0
|
||||
var linesCleared = 0
|
||||
var level = 0
|
||||
|
||||
// Rotation lock to prevent spinning with W
|
||||
var rotateHeld = false
|
||||
var gameOver = false
|
||||
|
||||
// Horizontal movement gating
|
||||
var hMoveTimer = 0
|
||||
var hDelay = 0.2 // delay before repeated moves begin
|
||||
var hRepeat = 0.05 // time between repeated moves
|
||||
var prevLeft = false
|
||||
var prevRight = false
|
||||
|
||||
// Tetrimino definitions
|
||||
var SHAPES = {
|
||||
I: { color:[0,1,1,1], blocks:[[0,0],[1,0],[2,0],[3,0]] },
|
||||
O: { color:[1,1,0,1], blocks:[[0,0],[1,0],[0,1],[1,1]] },
|
||||
T: { color:[1,0,1,1], blocks:[[0,0],[1,0],[2,0],[1,1]] },
|
||||
S: { color:[0,1,0,1], blocks:[[1,0],[2,0],[0,1],[1,1]] },
|
||||
Z: { color:[1,0,0,1], blocks:[[0,0],[1,0],[1,1],[2,1]] },
|
||||
J: { color:[0,0,1,1], blocks:[[0,0],[0,1],[1,1],[2,1]] },
|
||||
L: { color:[1,0.5,0,1], blocks:[[2,0],[0,1],[1,1],[2,1]] }
|
||||
}
|
||||
var shapeKeys = Object.keys(SHAPES)
|
||||
|
||||
// Initialize board with empty (0)
|
||||
function initBoard() {
|
||||
board = []
|
||||
for (var r=0; r<ROWS; r++) {
|
||||
var row = []
|
||||
for (var c=0; c<COLS; c++) row.push(0)
|
||||
board.push(row)
|
||||
}
|
||||
}
|
||||
initBoard()
|
||||
|
||||
function randomShape() {
|
||||
var key = shapeKeys[Math.floor(Math.random()*shapeKeys.length)]
|
||||
// Make a copy of the shape’s blocks
|
||||
return {
|
||||
type: key,
|
||||
color: SHAPES[key].color,
|
||||
blocks: SHAPES[key].blocks.map(b => [b[0], b[1]])
|
||||
}
|
||||
}
|
||||
|
||||
function spawnPiece() {
|
||||
piece = nextPiece || randomShape()
|
||||
nextPiece = randomShape()
|
||||
pieceX = 3
|
||||
pieceY = 0
|
||||
// Collision on spawn => game over
|
||||
if (collides(pieceX, pieceY, piece.blocks)) gameOver = true
|
||||
}
|
||||
|
||||
function collides(px, py, blocks) {
|
||||
for (var i=0; i<blocks.length; i++) {
|
||||
var x = px + blocks[i][0]
|
||||
var y = py + blocks[i][1]
|
||||
if (x<0 || x>=COLS || y<0 || y>=ROWS) return true
|
||||
if (y>=0 && board[y][x]) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Lock piece into board
|
||||
function lockPiece() {
|
||||
for (var i=0; i<piece.blocks.length; i++) {
|
||||
var x = pieceX + piece.blocks[i][0]
|
||||
var y = pieceY + piece.blocks[i][1]
|
||||
if (y>=0) board[y][x] = piece.color
|
||||
}
|
||||
}
|
||||
|
||||
// Rotate 90° clockwise
|
||||
function rotate(blocks) {
|
||||
// (x,y) => (y,-x)
|
||||
for (var i=0; i<blocks.length; i++) {
|
||||
var x = blocks[i][0]
|
||||
var y = blocks[i][1]
|
||||
blocks[i][0] = y
|
||||
blocks[i][1] = -x
|
||||
}
|
||||
}
|
||||
|
||||
function clearLines() {
|
||||
var lines = 0
|
||||
for (var r=ROWS-1; r>=0;) {
|
||||
if (board[r].every(cell => cell)) {
|
||||
lines++
|
||||
// remove row
|
||||
board.splice(r,1)
|
||||
// add empty row on top
|
||||
var newRow = []
|
||||
for (var c=0; c<COLS; c++) newRow.push(0)
|
||||
board.unshift(newRow)
|
||||
} else {
|
||||
r--
|
||||
}
|
||||
}
|
||||
// Score
|
||||
if (lines===1) score += 100
|
||||
else if (lines===2) score += 300
|
||||
else if (lines===3) score += 500
|
||||
else if (lines===4) score += 800
|
||||
linesCleared += lines
|
||||
level = Math.floor(linesCleared/10)
|
||||
}
|
||||
|
||||
function placePiece() {
|
||||
lockPiece()
|
||||
clearLines()
|
||||
spawnPiece()
|
||||
}
|
||||
|
||||
// Hard drop
|
||||
function hardDrop() {
|
||||
while(!collides(pieceX, pieceY+1, piece.blocks)) pieceY++
|
||||
placePiece()
|
||||
}
|
||||
|
||||
spawnPiece()
|
||||
|
||||
this.update = function(dt) {
|
||||
if (gameOver) return
|
||||
|
||||
// ========== Horizontal Movement Gate ==========
|
||||
var leftPressed = input.keyboard.down('a')
|
||||
var rightPressed = input.keyboard.down('d')
|
||||
var horizontalMove = 0
|
||||
|
||||
// If user just pressed A, move once & start gating
|
||||
if (leftPressed && !prevLeft) {
|
||||
horizontalMove = -1
|
||||
hMoveTimer = hDelay
|
||||
}
|
||||
// If user is holding A & the timer is up, move again, then reset timer to repeat
|
||||
else if (leftPressed && hMoveTimer <= 0) {
|
||||
horizontalMove = -1
|
||||
hMoveTimer = hRepeat
|
||||
}
|
||||
|
||||
// Same logic for D
|
||||
if (rightPressed && !prevRight) {
|
||||
horizontalMove = 1
|
||||
hMoveTimer = hDelay
|
||||
} else if (rightPressed && hMoveTimer <= 0) {
|
||||
horizontalMove = 1
|
||||
hMoveTimer = hRepeat
|
||||
}
|
||||
|
||||
// Move horizontally if it doesn't collide
|
||||
if (horizontalMove < 0 && !collides(pieceX-1, pieceY, piece.blocks)) pieceX--
|
||||
else if (horizontalMove > 0 && !collides(pieceX+1, pieceY, piece.blocks)) pieceX++
|
||||
|
||||
// If neither A nor D is pressed, reset the timer so next press is immediate
|
||||
if (!leftPressed && !rightPressed) {
|
||||
hMoveTimer = 0
|
||||
}
|
||||
|
||||
// Decrement horizontal timer
|
||||
hMoveTimer -= dt
|
||||
prevLeft = leftPressed
|
||||
prevRight = rightPressed
|
||||
// ========== End Horizontal Movement Gate ==========
|
||||
|
||||
// Rotate with W (once per press, no spinning)
|
||||
if (input.keyboard.down('w')) {
|
||||
if (!rotateHeld) {
|
||||
rotateHeld = true
|
||||
var test = piece.blocks.map(b => [b[0], b[1]])
|
||||
rotate(test)
|
||||
if (!collides(pieceX, pieceY, test)) piece.blocks = test
|
||||
}
|
||||
} else {
|
||||
rotateHeld = false
|
||||
}
|
||||
|
||||
// Soft drop if S is held (accelerates gravity)
|
||||
var fallSpeed = input.keyboard.down('s') ? 10 : 1
|
||||
|
||||
// Gravity
|
||||
gravityTimer += dt * fallSpeed
|
||||
var dropInterval = Math.max(0.1, baseGravity - level*0.05)
|
||||
if (gravityTimer >= dropInterval) {
|
||||
gravityTimer = 0
|
||||
if (!collides(pieceX, pieceY+1, piece.blocks)) {
|
||||
pieceY++
|
||||
} else {
|
||||
placePiece()
|
||||
}
|
||||
}
|
||||
|
||||
// Hard drop if space is held
|
||||
if (input.keyboard.down('space')) {
|
||||
// hardDrop()
|
||||
}
|
||||
}
|
||||
|
||||
this.hud = function() {
|
||||
// Clear screen
|
||||
draw.rectangle({x:0, y:0, width:config.width, height:config.height}, [0,0,0,1])
|
||||
|
||||
// Draw board
|
||||
for (var r=0; r<ROWS; r++) {
|
||||
for (var c=0; c<COLS; c++) {
|
||||
var cell = board[r][c]
|
||||
if (!cell) continue
|
||||
draw.rectangle({x:c*TILE, y:(ROWS-1-r)*TILE, width:TILE, height:TILE}, cell)
|
||||
}
|
||||
}
|
||||
|
||||
// Draw falling piece
|
||||
if (!gameOver && piece) {
|
||||
for (var i=0; i<piece.blocks.length; i++) {
|
||||
var x = pieceX + piece.blocks[i][0]
|
||||
var y = pieceY + piece.blocks[i][1]
|
||||
draw.rectangle({x:x*TILE, y:(ROWS-1-y)*TILE, width:TILE, height:TILE}, piece.color)
|
||||
}
|
||||
}
|
||||
|
||||
// Next piece window
|
||||
draw.text("Next", {x:70, y:5, width:50, height:10}, undefined, 0, color.white)
|
||||
if (nextPiece) {
|
||||
for (var i=0; i<nextPiece.blocks.length; i++) {
|
||||
var nx = nextPiece.blocks[i][0]
|
||||
var ny = nextPiece.blocks[i][1]
|
||||
var dx = 12 + nx
|
||||
var dy = 16 - ny
|
||||
draw.rectangle({x:dx*TILE, y:(ROWS-1-dy)*TILE, width:TILE, height:TILE}, nextPiece.color)
|
||||
}
|
||||
}
|
||||
|
||||
// Score & Level
|
||||
var info = "Score: " + score + "\nLines: " + linesCleared + "\nLevel: " + level
|
||||
draw.text(info, {x:70, y:30, width:90, height:50}, undefined, 0, color.white)
|
||||
|
||||
if (gameOver) {
|
||||
draw.text("GAME OVER", {x:10, y:config.height*0.5-5, width:config.width-20, height:20}, undefined, 0, color.red)
|
||||
}
|
||||
}
|
||||
|
||||