🎮ArcadeLab

C

by ChromeFlame24
346 lines6.9 KB
▶ Play

"use strict";

const canvas=document.getElementById("game");
const ctx=canvas.getContext("2d");

const SIZE=16;
const GRID=20;
const TOTAL=320;

let snake=[],apple=null,obstacles=[],particles=[];
let direction={x:1,y:0};
let nextDirection={x:1,y:0};
let score=0,level=1,best=0;
let running=false,paused=false,ended=false;
let timer=null;

let audio;

function sound(freq,duration,type="square",volume=.07){
 try{
  audio=audio||new(window.AudioContext||window.webkitAudioContext)();
  if(audio.state==="suspended")audio.resume();

  const osc=audio.createOscillator();
  const gain=audio.createGain();

  osc.type=type;
  osc.frequency.setValueAtTime(freq,audio.currentTime);
  gain.gain.setValueAtTime(volume,audio.currentTime);
  gain.gain.exponentialRampToValueAtTime(.001,audio.currentTime+duration);

  osc.connect(gain);
  gain.connect(audio.destination);
  osc.start();
  osc.stop(audio.currentTime+duration);
 }catch(e){}
}

function eatSound(){
 sound(500,.08);
 setTimeout(()=>sound(750,.12),70);
}

function coinSound(){
 sound(900,.1,"sine");
 setTimeout(()=>sound(1200,.15,"sine"),80);
}

function levelSound(){
 sound(400,.15);
 setTimeout(()=>sound(600,.15),130);
 setTimeout(()=>sound(900,.25),260);
}

function loseSound(){
 sound(180,.4,"sawtooth");
 setTimeout(()=>sound(100,.5,"sawtooth"),250);
}

function pixel(x,y,w,h,color){
 ctx.fillStyle=color;
 ctx.fillRect(x,y,w,h);
}

function drawBackground(){
 pixel(0,0,TOTAL,TOTAL,"#17251b");
 for(let y=0;y<GRID;y++){
  for(let x=0;x<GRID;x++){
   if((x+y)%2===0)
    pixel(x*SIZE,y*SIZE,SIZE,SIZE,"#1a291d");
  }
 }
 ctx.strokeStyle="#6b8950";
 ctx.lineWidth=4;
 ctx.strokeRect(2,2,316,316);
}

function drawApple(x,y){
 let px=x*SIZE,py=y*SIZE;
 pixel(px+6,py+1,4,3,"#8cbd57");
 pixel(px+5,py+4,7,2,"#a5e65e");
 pixel(px+3,py+6,10,7,"#c82e38");
 pixel(px+5,py+4,7,10,"#e83e43");
 pixel(px+4,py+8,2,3,"#ff7770");
 pixel(px+7,py+12,4,2,"#a82432");
}

function drawRock(x,y){
 let px=x*SIZE,py=y*SIZE;
 pixel(px+4,py+2,8,3,"#9ba18d");
 pixel(px+2,py+5,12,7,"#777f70");
 pixel(px+4,py+12,8,2,"#515d50");
 pixel(px+5,py+5,3,3,"#b4b9a6");
}

function drawSnake(){
 snake.forEach((s,i)=>{
  let x=s.x*SIZE,y=s.y*SIZE;
  pixel(x+2,y+2,12,12,i===0?"#b8f57a":"#64b94b");
  pixel(x+4,y+4,8,8,i===0?"#8bce54":"#79cf55");

  if(i===0){
   pixel(x+5,y+6,2,2,"#17251b");
   pixel(x+10,y+6,2,2,"#17251b");
  }
 });
}

function randomFree(){
 let available=[];
 for(let y=0;y<GRID;y++){
  for(let x=0;x<GRID;x++){
   if(
    !snake.some(s=>s.x===x&&s.y===y)&&
    !obstacles.some(o=>o.x===x&&o.y===y)&&
    !(apple&&apple.x===x&&apple.y===y)
   )available.push({x,y});
  }
 }
 return available.length?
  available[Math.floor(Math.random()*available.length)]:null;
}

function spawnApple(){
 apple=randomFree();
 if(!apple)winGame();
}

function createObstacles(){
 obstacles=[];
 for(let i=0;i<Math.min(3+(level-1)*2,22);i++){
  let p=randomFree();
  if(p)obstacles.push(p);
 }
}

function updateStats(){
 document.getElementById("score").textContent=score;
 document.getElementById("best").textContent=best;
 document.getElementById("level").textContent=level;
}

function startTimer(){
 clearInterval(timer);
 timer=setInterval(update,Math.max(75,145-(level-1)*8));
}

function startGame(){
 snake=[
  {x:8,y:10},{x:7,y:10},
  {x:6,y:10},{x:5,y:10}
 ];
 direction={x:1,y:0};
 nextDirection={x:1,y:0};
 score=0;level=1;
 obstacles=[];particles=[];
 apple=null;
 running=true;paused=false;ended=false;

 createObstacles();
 spawnApple();

 document.getElementById("overlay").classList.add("hidden");
 document.getElementById("pause").textContent="PAUSE";
 document.getElementById("status").textContent="اسحب لتغيير الاتجاه";

 updateStats();
 startTimer();
 draw();
}

function setDirection(name){
 if(!running||paused||ended)return;

 const dirs={
  up:{x:0,y:-1},
  down:{x:0,y:1},
  left:{x:-1,y:0},
  right:{x:1,y:0}
 };
 const d=dirs[name];
 if(!d)return;

 if(d.x===-direction.x&&d.y===-direction.y)return;
 nextDirection=d;
}

// التحكم بالسحب
let startX=0,startY=0,dragging=false;

canvas.addEventListener("pointerdown",e=>{
 startX=e.clientX;
 startY=e.clientY;
 dragging=true;
 canvas.setPointerCapture(e.pointerId);
});

canvas.addEventListener("pointerup",e=>{
 if(!dragging)return;
 dragging=false;

 let dx=e.clientX-startX;
 let dy=e.clientY-startY;

 if(Math.max(Math.abs(dx),Math.abs(dy))<15)return;

 if(Math.abs(dx)>Math.abs(dy))
  setDirection(dx>0?"right":"left");
 else
  setDirection(dy>0?"down":"up");
});

// حركة اللعبة
function update(){
 if(!running||paused||ended)return;

 direction=nextDirection;

 const head={
  x:snake[0].x+direction.x,
  y:snake[0].y+direction.y
 };

 // اختراق الجدران
 if(head.x<0)head.x=GRID-1;
 if(head.x>=GRID)head.x=0;
 if(head.y<0)head.y=GRID-1;
 if(head.y>=GRID)head.y=0;

 const eating=apple&&head.x===apple.x&&head.y===apple.y;

 if(obstacles.some(o=>o.x===head.x&&o.y===head.y)){
  endGame();
  return;
 }

 const body=eating?snake:snake.slice(0,-1);

 if(body.some(s=>s.x===head.x&&s.y===head.y)){
  endGame();
  return;
 }

 snake.unshift(head);

 if(eating){
  score+=10;
  eatSound();
  explode(head.x,head.y);
  spawnApple();

  const newLevel=Math.floor(score/50)+1;

  if(newLevel>level){
   level=newLevel;
   levelSound();
   createObstacles();
   startTimer();
  }

  if(score>best){
   best=score;
   try{localStorage.setItem("pixelSnakeBest",best)}catch(e){}
  }
 }else{
  snake.pop();
 }

 updateParticles();
 updateStats();
 draw();
}

function explode(x,y){
 for(let i=0;i<10;i++){
  particles.push({
   x:x*SIZE+8,y:y*SIZE+8,
   vx:(Math.random()-.5)*5,
   vy:(Math.random()-.5)*5,
   life:20,
   color:"#b9f58d"
  });
 }
}

function updateParticles(){
 particles.forEach(p=>{
  p.x+=p.vx;p.y+=p.vy;p.life--;
 });
 particles=particles.filter(p=>p.life>0);
}

function draw(){
 drawBackground();
 obstacles.forEach(o=>drawRock(o.x,o.y));
 if(apple)drawApple(apple.x,apple.y);
 drawSnake();

 particles.forEach(p=>{
  ctx.globalAlpha=p.life/20;
  pixel(p.x,p.y,3,3,p.color);
 });
 ctx.globalAlpha=1;
}

function endGame(){
 running=false;
 ended=true;
 clearInterval(timer);
 loseSound();

 document.getElementById("overlay").classList.remove("hidden");
 document.getElementById("menu").innerHTML=`
  <h2 style="color:#e87979">GAME OVER</h2>
  <p>YOUR SCORE: ${score}</p>
  <p>BEST SCORE: ${best}</p>
  <button id="again">PLAY AGAIN</button>
 `;
 document.getElementById("again").onclick=startGame;
}

function winGame(){
 running=false;
 clearInterval(timer);
 document.getElementById("overlay").classList.remove("hidden");
 document.getElementById("menu").innerHTML=`
  <h2>YOU WIN</h2>
  <p>YOU COMPLETED THE ARENA</p>
  <button id="again">PLAY AGAIN</button>
 `;
 document.getElementById("again").onclick=startGame;
}

document.getElementById("pause").onclick=()=>{
 if(!running||ended)return;
 paused=!paused;
 document.getElementById("pause").textContent=
  paused?"RESUME":"PAUSE";
 draw();
};

document.getElementById("restart").onclick=startGame;
document.getElementById("start").onclick=startGame;

draw();

Game Source: C

Creator: ChromeFlame24

Libraries: none

Complexity: complex (346 lines, 6.9 KB)

The full source code is displayed above on this page.

Remix Instructions

To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: c-chromeflame24" to link back to the original. Then publish at arcadelab.ai/publish.