<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Dùng phím mũi tên để di chuyển!</h1>
<div class="box">
<div id="robot">????</div>
</div>
<script src="script.js"></script>
</body>
</html>
.box {
width: 400px;
height: 400px;
border: 5px solid white;
position: relative;
background: #34495e;
margin: 0
auto;
}
#robot {
font-size: 40px;
position: absolute;
top: 0;
left: 0;
transition: 0.1s;
}
body {
background: #2c3e50;
color: white;
text-align: center;
}
let x = 0; // Vị trí trái - phải
let y = 0; // Vị trí trên - dưới
const robot = document.getElementById('robot');
document.addEventListener('keydown', function(event) {
// Kiểm tra phím mũi tên
if (event.key === "ArrowRight") {
x = x + 20;
} else if (event.key === "ArrowLeft") {
x = x - 20;
} else if (event.key === "ArrowDown") {
y = y + 20;
} else if (event.key ==="ArrowUp") {
y = y- 20;
}
// Cập nhật lại vị trí cho robot
robot.style.left = x + "px";
robot.style.top = y + "px";
// điều kiện game over
// Thử thách If-Else: Nếu robot ra ngoài khung thì báo Game Over
if (x < 0 || x > 360 || y < 0 || y > 360) {
alert("Bạn đã va vào tường!");
x = 0; y = 0; // Reset vị trí
robot.style.left = "0px";
robot.style.top = "0px";
}
});