Skip to content

Instantly share code, notes, and snippets.

@Kouhei-Takagi
Created February 26, 2025 12:43
Show Gist options
  • Select an option

  • Save Kouhei-Takagi/b0c2edb8d055a7b677224182d532bd85 to your computer and use it in GitHub Desktop.

Select an option

Save Kouhei-Takagi/b0c2edb8d055a7b677224182d532bd85 to your computer and use it in GitHub Desktop.
Prime Number Tetris
const gameBoard = document.getElementById('game-board');
// ゲームボードの設定
const ROWS = 13;
const COLUMNS = 7;
const VACANT = 'WHITE'; // 空のセルの色
// セルのコンストラクタ
function Square(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
}
// ゲームボードを描画する
function getContrastColor(color) {
// まず、色が hex 形式の場合
if (color[0] === '#') {
let r = parseInt(color.substr(1, 2), 16);
let g = parseInt(color.substr(3, 2), 16);
let b = parseInt(color.substr(5, 2), 16);
// 輝度の計算(一般的なウェイト付け)
let brightness = (r * 299 + g * 587 + b * 114) / 1000;
// 輝度が高ければ黒、低ければ白を返す
return brightness > 128 ? 'black' : 'white';
}
// もし基本色名の場合(小文字に変換して比較)
const lowerColor = color.toLowerCase();
// 明るい色の場合は黒のテキストにする
if (lowerColor === 'cyan' || lowerColor === 'lightblue' || lowerColor === 'yellow') {
return 'black';
}
return 'white';
}
function drawSquare(x, y, color, digit = "") {
const div = document.createElement('div');
div.style.gridColumnStart = x + 1;
div.style.gridRowStart = y + 1;
div.style.backgroundColor = color;
div.classList.add('block');
if (digit !== "") {
div.innerText = digit;
// 動的にコントラストの良い色を選ぶ
div.style.color = getContrastColor(color);
div.style.fontWeight = 'bold';
div.style.textAlign = 'center';
div.style.lineHeight = "calc(400px/13)";
div.style.textShadow = "1px 1px 2px rgba(0,0,0,0.5)";
}
gameBoard.appendChild(div);
}
function isPrime(n) {
if (n < 2) return false;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) return false;
}
return true;
}
function updateGame() {
// まずボード全体を再描画
drawBoard();
// 次に、落下中のピースを上書き描画
p.draw();
}
// ゲームボードの初期化
let board = [];
for (let r = 0; r < ROWS; r++) {
board[r] = [];
for (let c = 0; c < COLUMNS; c++) {
board[r][c] = { color: VACANT, digit: "" };
drawSquare(c, r, board[r][c].color, board[r][c].digit);
}
}
// テトリミノの形状を定義するための配列
const Z = [
[
[1, 1, 0],
[0, 1, 1],
[0, 0, 0],
],
[
[0, 0, 1],
[0, 1, 1],
[0, 1, 0],
],
[
[0, 0, 0],
[1, 1, 0],
[0, 1, 1],
],
[
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
]
];
const I = [
[
[0, 0, 0, 0],
[1, 1, 1, 1],
[0, 0, 0, 0],
[0, 0, 0, 0]
],
[
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0]
],
[
[0, 0, 0, 0],
[0, 0, 0, 0],
[1, 1, 1, 1],
[0, 0, 0, 0]
],
[
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 0]
]
];
const J = [
[
[1, 0, 0],
[1, 1, 1],
[0, 0, 0]
],
[
[0, 1, 1],
[0, 1, 0],
[0, 1, 0]
],
[
[0, 0, 0],
[1, 1, 1],
[0, 0, 1]
],
[
[0, 1, 0],
[0, 1, 0],
[1, 1, 0]
]
];
const L = [
[
[0, 0, 1],
[1, 1, 1],
[0, 0, 0]
],
[
[0, 1, 0],
[0, 1, 0],
[0, 1, 1]
],
[
[0, 0, 0],
[1, 1, 1],
[1, 0, 0]
],
[
[1, 1, 0],
[0, 1, 0],
[0, 1, 0]
]
];
const O = [
[
[0, 1, 1, 0],
[0, 1, 1, 0],
[0, 0, 0, 0],
],
[
[0, 1, 1, 0],
[0, 1, 1, 0],
[0, 0, 0, 0],
],
[
[0, 1, 1, 0],
[0, 1, 1, 0],
[0, 0, 0, 0],
],
[
[0, 1, 1, 0],
[0, 1, 1, 0],
[0, 0, 0, 0],
]
];
const S = [
[
[0, 1, 1],
[1, 1, 0],
[0, 0, 0]
],
[
[0, 1, 0],
[0, 1, 1],
[0, 0, 1]
],
[
[0, 0, 0],
[0, 1, 1],
[1, 1, 0]
],
[
[1, 0, 0],
[1, 1, 0],
[0, 1, 0]
]
];
const T = [
[
[0, 1, 0],
[1, 1, 1],
[0, 0, 0]
],
[
[0, 1, 0],
[0, 1, 1],
[0, 1, 0]
],
[
[0, 0, 0],
[1, 1, 1],
[0, 1, 0]
],
[
[0, 1, 0],
[1, 1, 0],
[0, 1, 0]
]
];
function rotateMatrix(matrix) {
const n = matrix.length;
let newMatrix = [];
for (let i = 0; i < n; i++) {
newMatrix[i] = [];
for (let j = 0; j < n; j++) {
newMatrix[i][j] = matrix[j][n - i - 1];
}
}
return newMatrix;
}
Piece.prototype.rotate = function () {
let nextPattern = this.tetromino[(this.tetrominoN + 1) % this.tetromino.length];
let rotatedDigits = rotateMatrix(this.digits);
let kick = 0;
if (this.checkCollision(0, 0, nextPattern)) {
if (this.x > COLUMNS / 2) {
kick = -1;
} else {
kick = 1;
}
}
if (!this.checkCollision(kick, 0, nextPattern)) {
this.unDraw();
this.x += kick;
this.tetrominoN = (this.tetrominoN + 1) % this.tetromino.length;
this.activeTetromino = rotateMatrix(this.activeTetromino);
this.digits = rotateMatrix(this.digits);
for (let r = 0; r < 4; r++) {
for (let c = 0; c < 4; c++) {
if (this.activeTetromino[r][c] !== 0 && this.digits[r][c] == null) {
//this.digits[r][c] = 0;
}
}
}
updateGame();
}
};
// テトリミノの形
const PIECES = [
[Z, "red"],
[S, "green"],
[T, "yellow"],
[O, "blue"],
[L, "purple"],
[I, "cyan"],
[J, "orange"]
];
// テトリミノを生成
function randomPiece() {
let r = Math.floor(Math.random() * PIECES.length);
let piece = new Piece(PIECES[r][0], PIECES[r][1]);
// もしテトリミノが I なら、数字をすべて 0 にする
if (PIECES[r][0] === I) {
for (let row = 0; row < piece.activeTetromino.length; row++) {
for (let col = 0; col < piece.activeTetromino[row].length; col++) {
// ブロックがあるマス(1)だけ 0 を設定
if (piece.activeTetromino[row][col]) {
piece.digits[row][col] = 0;
}
}
}
} else {
// それ以外のテトリミノは数字を 1~4 にする
for (let row = 0; row < piece.activeTetromino.length; row++) {
for (let col = 0; col < piece.activeTetromino[row].length; col++) {
if (piece.activeTetromino[row][col]) {
piece.digits[row][col] = Math.floor(Math.random() * 4) + 1;
// 1,2,3,4 のどれか
}
}
}
}
return piece;
}
// Piece コンストラクター関数(前提として)
function Piece(tetromino, color) {
this.tetromino = tetromino;
this.color = color;
this.tetrominoN = 0; // 初期パターンのインデックス
this.activeTetromino = this.tetromino[this.tetrominoN];
// 各ブロックに割り当てる数字の配列を生成(形状と同じ行列サイズ)
this.digits = [];
for (let r = 0; r < this.activeTetromino.length; r++) {
this.digits[r] = [];
for (let c = 0; c < this.activeTetromino[r].length; c++) {
if (this.activeTetromino[r][c]) {
this.digits[r][c] = Math.floor(Math.random() * 4); // 0~3
} else {
this.digits[r][c] = null;
}
}
}
this.x = 0;
this.y = 0;
}
// moveRight メソッドの定義
Piece.prototype.moveRight = function() {
if (!this.checkCollision(1,0,this.activeTetromino)){
this.unDraw();
this.x++;
updateGame();
}
};
// moveLeft メソッドの定義
Piece.prototype.moveLeft = function() {
if (!this.checkCollision(-1, 0, this.activeTetromino)) {
this.unDraw();
this.x--;
updateGame();
}
};
// 衝突検出メソッド
Piece.prototype.checkCollision = function (x, y, piece) {
for (let r = 0; r < piece.length; r++) {
for (let c = 0; c < piece.length; c++) {
if (!piece[r][c]) {
continue;
}
let newX = this.x + c + x;
let newY = this.y + r + y;
if (newX < 0 || newX >= COLUMNS || newY >= ROWS) {
return true;
}
if (newY < 0) {
continue;
}
if (board[newY] && board[newY][newX].color != VACANT) {
return true;
}
}
}
return false;
};
// 描画メソッド
Piece.prototype.draw = function() {
this.fill(this.color);
};
// 描画を解除するメソッド
Piece.prototype.unDraw = function() {
this.fill(VACANT);
};
// ピースを描画する
Piece.prototype.fill = function (color) {
for (let r = 0; r < this.activeTetromino.length; r++) {
for (let c = 0; c < this.activeTetromino[r].length; c++) {
if (this.activeTetromino[r][c]) {
let digit = (this.digits[r][c] !== null) ? this.digits[r][c] : "";
drawSquare(this.x + c, this.y + r, color, digit);
}
}
}
}
// ピースをボード上に描画
Piece.prototype.draw = function () {
this.fill(this.color);
}
// ピースをボードから削除
Piece.prototype.unDraw = function () {
this.fill(VACANT);
}
// ピースを動かす
Piece.prototype.moveDown = function () {
if (!this.checkCollision(0, 1, this.activeTetromino)) {
this.unDraw();
this.y++;
updateGame();
} else {
//ピースを固定する
this.lock();
p = randomPiece();
}
}
// ボードをチェックして揃った行を削除する
function removeFullRows() {
for (let r = 0; r < ROWS; r++) {
let isRowFull = true;
let sum = 0;
// 行が全て埋まっているかと、数字の合計を計算する
for (let c = 0; c < COLUMNS; c++) {
// セルがオブジェクトで、colorプロパティがVACANTでないことを確認
if (board[r][c].color === VACANT) {
isRowFull = false;
break;
}
// 数字が格納されていると仮定(数値の場合はそのまま、文字列の場合は変換)
sum += parseInt(board[r][c].digit, 10);
}
console.log(`Row ${r}: isFull=${isRowFull}, sum=${sum}, isPrime=${isPrime(sum)}`);
// 行が埋まっていて、かつ合計が素数なら行削除を実行
if (isRowFull && isPrime(sum)) {
// 現在の行より上のすべてのセルを一行下に移動する処理
for (let y = r; y > 0; y--) {
for (let c = 0; c < COLUMNS; c++) {
board[y][c] = board[y - 1][c];
}
}
// 最上行に新しい空の行を追加
for (let c = 0; c < COLUMNS; c++) {
board[0][c] = { color: VACANT, digit: "" };
}
// 画面の再描画
drawBoard();
r--;
}
}
}
// ゲームボード全体を描画する
function drawBoard() {
while (gameBoard.firstChild) {
gameBoard.removeChild(gameBoard.firstChild);
}
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLUMNS; c++) {
drawSquare(c, r, board[r][c].color, board[r][c].digit);
}
}
}
// ピースをボードに固定するメソッド
Piece.prototype.lock = function() {
for (let r = 0; r < this.activeTetromino.length; r++) {
for (let c = 0; c < this.activeTetromino[r].length; c++) {
if (!this.activeTetromino[r][c]) continue;
if (this.y + r < 0) {
alert("Game Over");
gameOver = true;
break;
}
board[this.y + r][this.x + c] = { color: this.color, digit: this.digits[r][c] };
}
}
removeFullRows();
}
// 衝突検出
Piece.prototype.collision = function (x, y, piece) {
for (let r = 0; r < piece.length; r++) {
for (let c = 0; c < piece.length; c++) {
// 空のスクエアは無視
if (!piece[r][c]) {
continue;
}
// 移動後の座標
let newX = this.x + c + x;
let newY = this.y + r + y;
// 衝突条件
if (newX < 0 || newX >= COLUMNS || newY >= ROWS) {
return true;
}
// newYが0未満はボード上にないのでスキップ
if (newY < 0) {
continue;
}
// 他のピースに衝突
if (board[newY][newX].color != VACANT) {
return true;
}
}
}
return false;
}
// ピースの制御
document.addEventListener("keydown", CONTROL);
function CONTROL(event) {
if(p !== undefined) { // pが定義されているかをチェック
if (event.keyCode == 37) {
p.moveLeft();
} else if (event.keyCode == 38) {
p.rotate();
} else if (event.keyCode == 39) {
p.moveRight();
} else if (event.keyCode == 40) {
p.moveDown();
}
}
}
// 新しいピースの落下を開始
let dropStart = Date.now();
let gameOver = false;
function drop() {
let now = Date.now();
let delta = now - dropStart;
if (delta > 1000) {
p.moveDown();
dropStart = Date.now();
}
if (!gameOver) {
requestAnimationFrame(drop);
console.log("END")
}
}
// ランダムなピースを生成してゲームを開始
let p = randomPiece();
drop();
// すでにあるコードの最後あたりで、
// DOMが読み込まれた後にボタンのイベントを登録する
document.addEventListener('DOMContentLoaded', () => {
// ボタン要素を取得
const rotateBtn = document.getElementById('rotate-btn');
const leftBtn = document.getElementById('left-btn');
const rightBtn = document.getElementById('right-btn');
const downBtn = document.getElementById('down-btn');
// クリックイベントを登録
rotateBtn.addEventListener('click', () => {
if (p !== undefined && !gameOver) {
p.rotate();
}
});
leftBtn.addEventListener('click', () => {
if (p !== undefined && !gameOver) {
p.moveLeft();
}
});
rightBtn.addEventListener('click', () => {
if (p !== undefined && !gameOver) {
p.moveRight();
}
});
downBtn.addEventListener('click', () => {
if (p !== undefined && !gameOver) {
p.moveDown();
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment