<div class="race-game">
<header class="header">
<div class="brand">🏁 STREET RACER</div>
<div class="cash">💰 $<span id="cash">0</span></div>
</header>
<div class="tabs">
<button onclick="showScreen('race')">🏎️ Race</button>
<button onclick="showScreen('garage')">🚘 Garage</button>
<button onclick="showScreen('upgrades')">⚙️ Upgrades</button>
</div>
<section id="race" class="screen active">
<div class="game-stats">
<div>Distance <strong id="distance">0 m</strong></div>
<div>Speed <strong id="speed">0 km/h</strong></div>
<div>Best <strong id="best">0 m</strong></div>
</div>
<div class="track-wrap">
<canvas id="gameCanvas" width="420" height="650"></canvas>
<div id="startOverlay" class="overlay">
<div class="overlay-card">
<div class="big-icon">🏎️</div>
<h2>READY TO RACE?</h2>
<p>Avoid traffic and drive as far as possible!</p>
<button class="primary" onclick="startGame()">START RACE</button>
</div>
</div>
<div id="crashOverlay" class="overlay hidden">
<div class="overlay-card">
<div class="big-icon">💥</div>
<h2>CRASH!</h2>
<p>You drove <strong id="finalDistance">0 m</strong></p>
<p>You earned <strong id="earned">$0</strong></p>
<button class="primary" onclick="startGame()">RACE AGAIN</button>
</div>
</div>
</div>
<div class="controls">
<button id="leftBtn" class="steer">⬅️</button>
<button id="rightBtn" class="steer">➡️</button>
</div>
<p class="hint">Use arrow keys or A / D. On iPad, hold the steering buttons.</p>
</section>
<section id="garage" class="screen">
<div class="section-heading">
<h2>🚘 Car Garage</h2>
<p>Choose your racing car.</p>
</div>
<div id="carList" class="car-list"></div>
</section>
<section id="upgrades" class="screen">
<div class="section-heading">
<h2>⚙️ Upgrades</h2>
<p>Make your car better.</p>
</div>
<div class="upgrade-card">
<div>
<h3>⚡ Engine</h3>
<p>Increase maximum speed.</p>
<small>Level <span id="engineLevel">0</span></small>
</div>
<button onclick="buyUpgrade('engine')">Buy $<span id="engineCost">250</span></button>
</div>
<div class="upgrade-card">
<div>
<h3>🛞 Handling</h3>
<p>Improve steering.</p>
<small>Level <span id="handlingLevel">0</span></small>
</div>
<button onclick="buyUpgrade('handling')">Buy $<span id="handlingCost">200</span></button>
</div>
<div class="upgrade-card">
<div>
<h3>💰 Race Bonus</h3>
<p>Earn more money per race.</p>
<small>Level <span id="bonusLevel">0</span></small>
</div>
<button onclick="buyUpgrade('bonus')">Buy $<span id="bonusCost">300</span></button>
</div>
</section>
<div id="message" class="message"></div>
</div>
<script>
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const cars = [
{id:"starter",name:"Starter",emoji:"🚗",color:"#36a9ff",price:0,speed:1},
{id:"sport",name:"Sport",emoji:"🏎️",color:"#ff4242",price:1500,speed:1.15},
{id:"racer",name:"Racer",emoji:"🚘",color:"#ffd447",price:5000,speed:1.3},
{id:"super",name:"Supercar",emoji:"🏎️",color:"#b46bff",price:15000,speed:1.5},
{id:"hyper",name:"Hypercar",emoji:"🚀",color:"#50e6a0",price:50000,speed:1.8}
];
let cash=0;
let best=0;
let selectedCar="starter";
let ownedCars=["starter"];
let engineLevel=0;
let handlingLevel=0;
let bonusLevel=0;
let running=false;
let animationId=null;
let lastTime=0;
let roadOffset=0;
let distance=0;
let obstacles=[];
let spawnTimer=0;
let keys={left:false,right:false};
const player={x:210,y:520};
const laneCenters=[115,210,305];
function saveGame(){
localStorage.setItem("streetRacerSave",JSON.stringify({
cash,best,selectedCar,ownedCars,
engineLevel,handlingLevel,bonusLevel
}));
}
function loadGame(){
try{
const saved=JSON.parse(localStorage.getItem("streetRacerSave"));
if(saved){
cash=Number(saved.cash)||0;
best=Number(saved.best)||0;
selectedCar=saved.selectedCar||"starter";
ownedCars=Array.isArray(saved.ownedCars)?saved.ownedCars:["starter"];
engineLevel=Number(saved.engineLevel)||0;
handlingLevel=Number(saved.handlingLevel)||0;
bonusLevel=Number(saved.bonusLevel)||0;
}
}catch(e){}
if(!ownedCars.includes("starter")) ownedCars.push("starter");
if(!cars.some(c=>c.id===selectedCar)||!ownedCars.includes(selectedCar)){
selectedCar="starter";
}
updateUI();
}
function showScreen(id){
if(running&&id!=="race"){
showMessage("Finish your race first!");
return;
}
document.querySelectorAll(".screen").forEach(s=>s.classList.remove("active"));
document.getElementById(id).classList.add("active");
updateUI();
}
function getSelectedCar(){
return cars.find(c=>c.id===selectedCar)||cars[0];
}
function getEngineCost(){
return Math.floor(250*Math.pow(1.65,engineLevel));
}
function getHandlingCost(){
return Math.floor(200*Math.pow(1.6,handlingLevel));
}
function getBonusCost(){
return Math.floor(300*Math.pow(1.7,bonusLevel));
}
function buyUpgrade(type){
if(running){
showMessage("Finish your race first!");
return;
}
let cost=0;
if(type==="engine") cost=getEngineCost();
if(type==="handling") cost=getHandlingCost();
if(type==="bonus") cost=getBonusCost();
if(cash<cost){
showMessage("Not enough money!");
return;
}
cash-=cost;
if(type==="engine") engineLevel++;
if(type==="handling") handlingLevel++;
if(type==="bonus") bonusLevel++;
saveGame();
updateUI();
showMessage("Upgrade purchased!");
}
function buyCar(id){
if(running) return;
const car=cars.find(c=>c.id===id);
if(!car) return;
if(ownedCars.includes(id)){
selectedCar=id;
saveGame();
updateUI();
showMessage(car.name+" selected!");
return;
}
if(cash<car.price){
showMessage("Not enough money!");
return;
}
cash-=car.price;
ownedCars.push(id);
selectedCar=id;
saveGame();
updateUI();
showMessage("You bought the "+car.name+"!");
}
function updateUI(){
document.getElementById("cash").textContent=Math.floor(cash).toLocaleString("en-US");
document.getElementById("best").textContent=best+" m";
document.getElementById("engineLevel").textContent=engineLevel;
document.getElementById("handlingLevel").textContent=handlingLevel;
document.getElementById("bonusLevel").textContent=bonusLevel;
document.getElementById("engineCost").textContent=getEngineCost().toLocaleString("en-US");
document.getElementById("handlingCost").textContent=getHandlingCost().toLocaleString("en-US");
document.getElementById("bonusCost").textContent=getBonusCost().toLocaleString("en-US");
renderCars();
}
function renderCars(){
const list=document.getElementById("carList");
list.innerHTML="";
cars.forEach(car=>{
const owned=ownedCars.includes(car.id);
const selected=selectedCar===car.id;
const card=document.createElement("div");
card.className="car-card";
card.innerHTML=`
<div class="car-preview" style="color:${car.color}">${car.emoji}</div>
<div class="car-details">
<h3>${car.name}</h3>
<p>Speed rating: ${car.speed.toFixed(1)}x</p>
<small>${owned?"Owned":"Price: $"+car.price.toLocaleString("en-US")}</small>
</div>
<button ${selected?"disabled":""} onclick="buyCar('${car.id}')">
${selected?"SELECTED":owned?"SELECT":"BUY"}
</button>
`;
list.appendChild(card);
});
}
/* WIDER CARS */
function drawCar(x,y,color){
ctx.save();
ctx.translate(x,y);
ctx.fillStyle="#111";
ctx.fillRect(-34,-28,11,20);
ctx.fillRect(23,-28,11,20);
ctx.fillRect(-34,13,11,20);
ctx.fillRect(23,13,11,20);
ctx.fillStyle=color;
ctx.beginPath();
ctx.roundRect(-29,-38,58,76,10);
ctx.fill();
ctx.fillStyle="#c9edff";
ctx.beginPath();
ctx.roundRect(-23,-24,46,20,6);
ctx.fill();
ctx.fillStyle="#26303b";
ctx.beginPath();
ctx.roundRect(-23,5,46,20,5);
ctx.fill();
ctx.fillStyle="#fff2a6";
ctx.fillRect(-24,-36,10,5);
ctx.fillRect(14,-36,10,5);
ctx.fillStyle="#ff3333";
ctx.fillRect(-24,31,10,5);
ctx.fillRect(14,31,10,5);
ctx.restore();
}
function drawRoad(){
ctx.fillStyle="#28633e";
ctx.fillRect(0,0,420,650);
ctx.fillStyle="#333943";
ctx.fillRect(55,0,310,650);
ctx.fillStyle="#f2f2f2";
ctx.fillRect(55,0,5,650);
ctx.fillRect(360,0,5,650);
ctx.strokeStyle="#e7e7e7";
ctx.lineWidth=5;
ctx.setLineDash([35,35]);
ctx.lineDashOffset=-roadOffset;
ctx.beginPath();
ctx.moveTo(158,0);
ctx.lineTo(158,650);
ctx.moveTo(262,0);
ctx.lineTo(262,650);
ctx.stroke();
ctx.setLineDash([]);
}
function drawScene(){
drawRoad();
obstacles.forEach(ob=>drawCar(ob.x,ob.y,ob.color));
drawCar(player.x,player.y,getSelectedCar().color);
}
function startGame(){
if(animationId) cancelAnimationFrame(animationId);
running=true;
distance=0;
roadOffset=0;
obstacles=[];
spawnTimer=0;
lastTime=0;
player.x=210;
keys.left=false;
keys.right=false;
document.getElementById("startOverlay").classList.add("hidden");
document.getElementById("crashOverlay").classList.add("hidden");
animationId=requestAnimationFrame(gameLoop);
}
function gameLoop(timestamp){
if(!running) return;
if(!lastTime) lastTime=timestamp;
const delta=Math.min((timestamp-lastTime)/16.67,2.5);
lastTime=timestamp;
updateGame(delta);
drawScene();
if(running) animationId=requestAnimationFrame(gameLoop);
}
function updateGame(delta){
const car=getSelectedCar();
const speed=(5.5+engineLevel*0.45)*car.speed;
roadOffset=(roadOffset+speed*delta)%70;
distance+=speed*delta*0.35;
document.getElementById("distance").textContent=Math.floor(distance)+" m";
document.getElementById("speed").textContent=Math.floor(speed*18)+" km/h";
const movement=4.8+handlingLevel*0.45;
if(keys.left) player.x-=movement*delta;
if(keys.right) player.x+=movement*delta;
player.x=Math.max(88,Math.min(332,player.x));
/* DIFFICULTY INCREASES WITH DISTANCE */
const difficulty=Math.min(distance/2200,1);
/* Cars spawn more frequently as distance increases */
const spawnInterval=82-difficulty*42;
spawnTimer+=delta;
if(spawnTimer>=spawnInterval){
spawnTimer=0;
spawnObstacleGroup(difficulty);
}
obstacles.forEach(ob=>{
ob.y+=speed*delta;
});
obstacles=obstacles.filter(ob=>ob.y<720);
/* COLLISION DETECTION */
for(const ob of obstacles){
if(Math.abs(ob.x-player.x)<42&&Math.abs(ob.y-player.y)<55){
endGame();
return;
}
}
}
/* SPAWN SYSTEM: NO OVERLAPPING CARS */
function spawnObstacleGroup(difficulty){
const spawnY=-80;
/* Find lanes where another car is not too close */
let availableLanes=laneCenters.filter(lane=>{
return !obstacles.some(ob=>
ob.x===lane && Math.abs(ob.y-spawnY)<150
);
});
if(availableLanes.length===0) return;
/* Shuffle available lanes */
availableLanes.sort(()=>Math.random()-0.5);
/* Never spawn across all three lanes */
const twoCarChance=0.05+difficulty*0.75;
const wantedCars=Math.random()<twoCarChance?2:1;
const amount=Math.min(wantedCars,availableLanes.length,2);
for(let i=0;i<amount;i++){
spawnObstacle(availableLanes[i],spawnY);
}
}
function spawnObstacle(lane,y){
const colors=["#ff4949","#ffd34d","#bd72ff","#f4f4f4","#4bd5aa"];
obstacles.push({
x:lane,
y:y,
color:colors[Math.floor(Math.random()*colors.length)]
});
}
function endGame(){
running=false;
if(animationId) cancelAnimationFrame(animationId);
const meters=Math.floor(distance);
const reward=Math.floor(meters*(1+bonusLevel*0.2));
cash+=reward;
if(meters>best) best=meters;
document.getElementById("finalDistance").textContent=meters+" m";
document.getElementById("earned").textContent="$"+reward.toLocaleString("en-US");
document.getElementById("crashOverlay").classList.remove("hidden");
saveGame();
updateUI();
}
function showMessage(text){
const el=document.getElementById("message");
el.textContent=text;
el.classList.add("visible");
clearTimeout(window.messageTimer);
window.messageTimer=setTimeout(()=>{
el.classList.remove("visible");
},1800);
}
document.addEventListener("keydown",e=>{
if(e.key==="ArrowLeft"||e.key.toLowerCase()==="a"){
keys.left=true;
e.preventDefault();
}
if(e.key==="ArrowRight"||e.key.toLowerCase()==="d"){
keys.right=true;
e.preventDefault();
}
});
document.addEventListener("keyup",e=>{
if(e.key==="ArrowLeft"||e.key.toLowerCase()==="a") keys.left=false;
if(e.key==="ArrowRight"||e.key.toLowerCase()==="d") keys.right=false;
});
function bindSteering(id,direction){
const button=document.getElementById(id);
button.addEventListener("pointerdown",e=>{
e.preventDefault();
button.setPointerCapture(e.pointerId);
keys[direction]=true;
});
button.addEventListener("pointerup",e=>{
e.preventDefault();
keys[direction]=false;
});
button.addEventListener("pointercancel",()=>{
keys[direction]=false;
});
button.addEventListener("lostpointercapture",()=>{
keys[direction]=false;
});
}
bindSteering("leftBtn","left");
bindSteering("rightBtn","right");
loadGame();
drawScene();
</script>