User: Buatkan script game tetris untuk android buat semirip mungkin dengan game tetris asli dengan balok baloknya,papan scorenya,latar belakangnya, background start dan background lost atau kalah memakai html
User: Buatkan script game tetris untuk android buat semirip mungkin dengan game tetris asli dengan balok baloknya,papan scorenya,latar belakangnya, background start dan background lost atau kalah memakai html
Assistant:
Assistant
Berikut adalah contoh script game Tetris sederhana menggunakan HTML, CSS, dan JavaScript yang bisa dijalankan di browser Android (misalnya lewat Chrome). Script ini dibuat sedekat mungkin dengan game Tetris asli, dengan:
Bentuk blok yang familiar
Papan skor
Latar belakang papan
Background layar start
Background layar game over (lost)
Kamu bisa simpan sebagai file index.html dan buka di browser Android.
html
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Tetris Android Clone</title>
<style>
/* Reset and base */
* {
box-sizing: border-box;
}
body {
margin: 0;
background: #111;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
color: #eee;
user-select: none;
overflow: hidden;
}
#game-container {
margin: 0 auto;
width: 320px;
height: 640px;
position: relative;
background:
linear-gradient(45deg, #222 25%, transparent 25%),
linear-gradient(-45deg, #222 25%, transparent 25%),
linear-gradient(45deg, transparent 75%, #222 75%),
linear-gradient(-45deg, transparent 75%, #222 75%);
background-size: 40px 40px;
background-position: 0 0, 0 20px, 20px -20px, -20px 0px;
border: 3px solid #555;
box-shadow: 0 0 25px #66f, inset 0 0 20px #66f;
}
canvas {
background: #111;
display: block;
margin: 0 auto;
image-rendering: pixelated;
position: relative;
top: 0; left: 0;
}
#scoreboard {
position: absolute;
top: 10px; right: -160px;
width: 140px;
padding: 15px;
border: 2px solid #444;
background: #222a;
box-shadow: 0 0 15px #55a;
border-radius: 10px;
}
#scoreboard h2 {
margin: 0 0 15px 0;
font-weight: 700;
font-size: 22px;
text-align: center;
color: #66f;
text-shadow: 0 0 8px #66f;
}
#scoreboard div {
font-size: 18px;
margin-bottom: 10px;
}
/* Start screen and game over overlay styles */
.overlay {
position: absolute;
top: 0; left: 0;
width: 320px;
height: 640px;
background: linear-gradient(rgba(0,0,0,0.7), rgba(0,0,0,0.95));
color: #66f;
text-align: center;
z-index: 10;
border-radius: 3px;
display: flex;
flex-direction: column;
justify-content: center;
user-select: none;
}
.overlay h1 {
font-size: 48px;
margin: 0 0 20px 0;
text-shadow: 0 0 15px #66f;
}
.overlay button {
font-size: 20px;
padding: 12px 40px;
background: #2266ff;
border: none;
border-radius: 8px;
color: white;
font-weight: 600;
cursor: pointer;
box-shadow: 0 0 20px #66f;
transition: background 0.3s ease;
}
.overlay button:hover {
background: #4488ff;
}
/* Controls help */
#controls {
position: absolute;
bottom: 10px;
right: -160px;
width: 140px;
font-size: 14px;
color: #ccc;
}
</style>
</head>
<body>
<div id="game-container">
<canvas id="tetris" width="320" height="640"></canvas>
<div id="scoreboard">
<h2>Tetris</h2>
<div>Score: <span id="score">0</span></div>
<div>Lines: <span id="lines">0</span></div>
<div>Level: <span id="level">1</span></div>
</div>
<div id="controls">
<b>Kontrol:</b><br>
Swipe/Klik kiri: ←<br>
Swipe/Klik kanan: →<br>
Klik atas: Rotasi<br>
Klik bawah / turun cepat<br>
</div>
<!-- Start Screen -->
<div class="overlay" id="start-screen">
<h1>TETRIS</h1>
<button id="start-btn">Mulai Bermain</button>
</div>
<!-- Game Over Screen -->
<div class="overlay" id="gameover-screen" style="display:none;">
<h1>Game Over</h1>
<div style="margin-bottom: 20px; font-size: 20px;">Skor Akhir: <span id="final-score">0</span></div>
<button id="restart-btn">Main Lagi</button>
</div>
</div>
<script>
(() => {
const canvas = document.getElementById('tetris');
const ctx = canvas.getContext('2d');
ctx.scale(20, 20); // Scale for faster rendering at pixel level (20x20 per block)
const ROWS = 32; // Canvas height / block size: 640/20=32
const COLS = 16; // Canvas width / block size: 320/20=16, but for classic Tetris it's 10x20, will center
const PLAYFIELD_COLS = 10;
const PLAYFIELD_ROWS = 20;
// We'll center playfield horizontally, with some padding
// Block colors mimic original Tetris
const COLORS = [
null,
'#00f0f0', // Cyan - I
'#0000f0', // Blue - J
'#f0a000', // Orange - L
'#f0f000', // Yellow - O
'#00f000', // Green - S
'#a000f0', // Purple - T
'#f00000', // Red - Z
];
// Tetromino shapes - standard 4x4 matrices
const SHAPES = [
[],
[
[0,0,0,0],
[1,1,1,1],
[0,0,0,0],
[0,0,0,0],
], // I
[
[2,0,0],
[2,2,2],
[0,0,0],
], // J
[
[0,0,3],
[3,3,3],
[0,0,0],
], // L
[
[4,4],
[4,4],
], // O
[
[0,5,5],
[5,5,0],
[0,0,0],
], // S
[
[0,6,0],
[6,6,6],
[0,0,0],
], // T
[
[7,7,0],
[0,7,7],
[0,0,0],
], // Z
];
// Variables for game state
let playfield = createMatrix(PLAYFIELD_ROWS, PLAYFIELD_COLS);
let currentPiece = null;
let currentPos = {x:0, y:0};
let dropCounter = 0;
let dropInterval = 1000;
let lastTime = 0;
let score = 0;
let lines = 0;
let level = 1;
let gameOver = false;
let isPlaying = false;
// UI elements
const scoreElem = document.getElementById('score');
const linesElem = document.getElementById('lines');
const levelElem = document.getElementById('level');
const startScreen = document.getElementById('start-screen');
const gameOverScreen = document.getElementById('gameover-screen');
const finalScore = document.getElementById('final-score');
const startBtn = document.getElementById('start-btn');
const restartBtn = document.getElementById('restart-btn');
// Functions
function createMatrix(rows, cols) {
const matrix = [];
for(let i=0; i<rows; i++) {
matrix.push(new Array(cols).fill(0));
}
return matrix;
}
function createPiece(type) {
const shape = SHAPES[type];
return shape.map(row => row.slice());
}
function drawBlock(x, y, colorIndex) {
if (!colorIndex) return;
ctx.fillStyle = COLORS[colorIndex];
ctx.strokeStyle = '#111';
ctx.lineWidth = 0.06;
ctx.fillRect(x, y, 1, 1);
// Block edges for nicer look
ctx.strokeRect(x, y, 1, 1);
// Optional shading
ctx.fillStyle = 'rgba(255,255,255,0.15)';
ctx.fillRect(x+0.05, y+0.05, 0.9, 0.45);
ctx.fillStyle = 'rgba(0,0,0,0.15)';
ctx.fillRect(x+0.05, y+0.55, 0.9, 0.4);
}
function drawMatrix(matrix, offset) {
matrix.forEach((row, y) => {
row.forEach((value, x) => {
if(value) {
drawBlock(x + offset.x, y + offset.y, value);
}
});
});
}
function drawPlayfield() {
// Clear the playfield area first
ctx.fillStyle = '#111';
// Playfield position (centered horizontally)
let offsetX = Math.floor((COLS - PLAYFIELD_COLS) /2);
ctx.fillRect(0, 0, COLS, ROWS);
// Draw blocks in playfield
for(let y=0; y < PLAYFIELD_ROWS; y++) {
for(let x=0; x < PLAYFIELD_COLS; x++) {
const val = playfield[y][x];
if(val !== 0) {
drawBlock(x + offsetX, y + 6, val);
/* Positioned down 6 rows to center vertically:
Because ROWS=32, PLAYFIELD_ROWS=20,
We can add padding 6 rows top and 6 bottom approx for styling */
}
}
}
}
function mergePiece() {
let offsetX = Math.floor((COLS - PLAYFIELD_COLS) /2);
currentPiece.forEach((row, y) => {
row.forEach((val, x) => {
if(val !==0) {
playfield[y + currentPos.y][x + currentPos.x] = val;
}
});
});
}
function collide(matrix, pos) {
for(let y=0; y<matrix.length; y++) {
for(let x=0; x<matrix[y].length; x++) {
if(matrix[y][x] !==0) {
let px = x + pos.x;
let py = y + pos.y;
if(px <0 || px >= PLAYFIELD_COLS || py >= PLAYFIELD_ROWS) {
return true;
}
if(py >= 0 && playfield[py][px] !== 0) {
return true;
}
}
}
}
return false;
}
function rotate(matrix, dir) {
// transpose + reverse rows or cols - clockwise or anticlockwise rotation
for(let y=0; y < matrix.length; y++) {
for(let x=0; x < y; x++) {
[matrix[x][y], matrix[y][x]] = [matrix[y][x], matrix[x][y]];
}
}
if(dir > 0) {
matrix.forEach(row => row.reverse());
} else {
matrix.reverse();
}
}
function playerReset() {
// Random tetromino
const pieces = 'TJLOSZI';
// Using standard mapping:
// T=6, J=2, L=3, O=4, S=5, Z=7, I=1
const mapping = {T:6,J:2,L:3,O:4,S:5,Z:7,I:1};
const rand = pieces[Math.floor(Math.random()*pieces.length)];
currentPiece = createPiece(mapping[rand]);
currentPos.y = 0;
currentPos.x = Math.floor(PLAYFIELD_COLS/2 - Math.ceil(currentPiece[0].length/2));
if(collide(currentPiece, currentPos)) {
// Game Over
gameOver = true;
isPlaying = false;
gameOverScreen.style.display = "flex";
finalScore.textContent = score;
overlayHandlers(false);
}
}
function playerDrop() {
currentPos.y++;
if(collide(currentPiece, currentPos)) {
currentPos.y--;
mergePiece();
sweepLines();
playerReset();
updateScore();
}
dropCounter = 0;
}
function sweepLines() {
let linesCleared = 0;
outer: for(let y = PLAYFIELD_ROWS -1; y >= 0; y--) {
for(let x = 0; x < PLAYFIELD_COLS; x++) {
if(playfield[y][x] === 0) {
continue outer;
}
}
// Line is full, remove it
const row = playfield.splice(y,1)[0].fill(0);
playfield.unshift(row);
y++;
linesCleared++;
}
if(linesCleared > 0) {
// Scoring inspired classic Tetris
const lineScores = [0,40,100,300,1200];
score += lineScores[linesCleared]*level;
lines += linesCleared;
// Level up every 10 lines
if(lines >= level*10) {
level++;
dropInterval = Math.max(100, dropInterval - 100);
}
}
}
function updateScore() {
scoreElem.textContent = score;
linesElem.textContent = lines;
levelElem.textContent = level;
}
// Draw everything
function draw() {
ctx.clearRect(0, 0, COLS, ROWS);
// Draw grid background in playfield area
drawPlayfield();
// Draw current falling piece
let offsetX = Math.floor((COLS - PLAYFIELD_COLS) /2);
drawMatrix(currentPiece, {x: currentPos.x + offsetX, y: currentPos.y + 6});
}
// Game loop
function update(time = 0) {
if(!isPlaying) {
lastTime = time;
return;
}
const deltaTime = time - lastTime;
lastTime = time;
dropCounter += deltaTime;
if(dropCounter > dropInterval) {
playerDrop();
}
draw();
requestAnimationFrame(update);
}
// Control handlers
document.addEventListener('keydown', event => {
if(!isPlaying) return;
switch(event.code) {
case 'ArrowLeft':
case 'KeyA':
move(-1);
break;
case 'ArrowRight':
case 'KeyD':
move(1);
break;
case 'ArrowDown':
case 'KeyS':
playerDrop();
break;
case 'ArrowUp':
case 'KeyW':
case 'Space':
case 'KeyX':
rotatePiece(1);
break;
}
});
// Move piece horizontally
function move(dir) {
currentPos.x += dir;
if(collide(currentPiece, currentPos)) {
currentPos.x -= dir;
}
}
// Rotate piece
function rotatePiece(dir) {
const posX = currentPos.x;
let offset = 1;
rotate(currentPiece, dir);
while(collide(currentPiece, currentPos)) {
currentPos.x += offset;
offset = -(offset + (offset > 0 ? 1 : -1));
if(offset > currentPiece[0].length) {
rotate(currentPiece, -dir);
currentPos.x = posX;
return;
}
}
}
// Touch controls for Android friendly interaction
let touchStartX = null;
let touchStartY = null;
let touchThreshold = 30; // min swipe distance
canvas.addEventListener('touchstart', e => {
if(!isPlaying) return;
const touch = e.touches[0];
touchStartX = touch.clientX;
touchStartY = touch.clientY;
});
canvas.addEventListener('touchend', e => {
if(!isPlaying) return;
const touch = e.changedTouches[0];
const dx = touch.clientX - touchStartX;
const dy = touch.clientY - touchStartY;
if(Math.abs(dx) > Math.abs(dy)) {
// Horizontal swipe
if(dx > touchThreshold) {
move(1);
} else if(dx < -touchThreshold) {
move(-1);
}
} else {
// Vertical swipe or tap
if(dy > touchThreshold) {
playerDrop();
} else if(dy < -touchThreshold) {
rotatePiece(1);
} else {
// Tap = rotate
rotatePiece(1);
}
}
touchStartX = null;
touchStartY = null;
});
// Buttons handlers
startBtn.addEventListener('click', () => {
startScreen.style.display = 'none';
gameOverScreen.style.display = 'none';
resetGame();
isPlaying = true;
updateScore();
update();
overlayHandlers(true);
});
restartBtn.addEventListener('click', () => {
gameOverScreen.style.display = 'none';
resetGame();
isPlaying = true;
updateScore();
update();
overlayHandlers(true);
});
function resetGame() {
playfield = createMatrix(PLAYFIELD_ROWS, PLAYFIELD_COLS);
score = 0;
lines = 0;
level = 1;
dropInterval = 1000;
gameOver = false;
currentPos = {x: 0, y: 0};
currentPiece = null;
playerReset();
}
// Disable buttons outside playing
function overlayHandlers(active) {
if(active) {
startBtn.disabled = true;
restartBtn.disabled = true;
} else {
startBtn.disabled = false;
restartBtn.disabled = false;
}
}
})();
</script>
</body>
</html>
Penjelasan Singkat:
Canvas: ukuran 320x640 px, blok di-scale 20x20 px sehingga bergaya Tetris klasik 10 kolom x 20 baris.
Warna blok: sesuai warna tetromino classic.
Papan skor: menampilkan skor, lines cleared, dan level.
Latar belakang papan: pola grid sederhana gelap ala Tetris.
Layar start dan game over: overlay dengan tombol untuk start/restart.
Kontrol: keyboard arrow keys & WASD + tap/swipe touch di Android (geser kiri/kanan + tap rotate + swipe turun untuk drop).
LEVELING: semakin naik level, kecepatan jatuh blok semakin cepat.
Game logic & scoring: mengimplementasikan baris penuh (line clear), scoring standar Tetris lama, dan game over bila tetris penuh.
Cukup buka file HTML ini di browser Android kamu, maka game bisa dimainkan dengan drag / tap yang cukup responsif.
Jika ingin dikustomisasi lebih lanjut (audio, lebih visual, dll.) silakan minta kembali!