o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
code moi en html/css/js un jeu du snake en 3D, met tout le code dans un seul fichier html
- User
code moi en html/css/js un jeu du snake en 3D, met tout le code dans un seul fichier html
- Assistant
code moi en html/css/js un jeu du snake en 3D, met tout le code dans un seul fichier html
Voici un code complet pour un jeu du Snake en 3D réalisé en HTML, CSS et JavaScript, le tout dans un seul fichier HTML. Ce code utilise WebGL via le contexte webgl du canvas pour créer un effet 3D sans utiliser de bibliothèques externes.
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Jeu du Snake 3D</title>
<style>
body, html {
margin: 0;
padding: 0;
overflow: hidden;
background: #000;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="glcanvas"></canvas>
<script>
const canvas = document.getElementById('glcanvas');
const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
if (!gl) {
alert('Votre navigateur ne supporte pas WebGL');
}
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Shader de vertex
const vsSource = `
attribute vec4 aVertexPosition;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
void main(void) {
gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
}
`;
// Shader de fragment
const fsSource = `
void main(void) {
gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);
}
`;
// Initialisation du shader
function initShaderProgram(gl, vsSource, fsSource) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert('Impossible d\'initialiser le programme shader: ' + gl.getProgramInfoLog(shaderProgram));
return null;
}
return shaderProgram;
}
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert('Une erreur est survenue lors de la compilation du shader: ' + gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
return null;
}
return shader;
}
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
const programInfo = {
program: shaderProgram,
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),
},
};
// Initialisation des buffers
function initBuffers(gl) {
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// Coordonnées d'un cube
const positions = [
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0,
-1.0, -1.0, -1.0,
-1.0, 1.0, -1.0,
1.0, 1.0, -1.0,
1.0, -1.0, -1.0,
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
// Indices des sommets du cube
const indices = [
0, 1, 2, 0, 2, 3,
4, 5, 6, 4, 6, 7,
0, 3, 5, 0, 5, 4,
1, 7, 6, 1, 6, 2,
3, 2, 6, 3, 6, 5,
0, 4, 7, 0, 7, 1,
];
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
return {
position: positionBuffer,
indices: indexBuffer,
};
}
const buffers = initBuffers(gl);
let then = 0;
let snake = [{x:0, y:0, z:0}];
let direction = 'right';
let food = {x: Math.floor(Math.random()*10-5), y: Math.floor(Math.random()*10-5), z: Math.floor(Math.random()*10-5)};
function drawScene(gl, programInfo, buffers, deltaTime) {
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clearDepth(1.0);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
const fieldOfView = 45 * Math.PI / 180;
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1;
const zFar = 100.0;
const projectionMatrix = mat4.create();
mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);
const modelViewMatrix = mat4.create();
mat4.translate(modelViewMatrix, modelViewMatrix, [-0.0, 0.0, -25.0]);
// Position des vertices
{
const numComponents = 3;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexPosition,
numComponents,
type,
normalize,
stride,
offset);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);
}
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);
gl.useProgram(programInfo.program);
gl.uniformMatrix4fv(programInfo.uniformLocations.projectionMatrix, false, projectionMatrix);
gl.uniformMatrix4fv(programInfo.uniformLocations.modelViewMatrix, false, modelViewMatrix);
{
const vertexCount = 36;
const type = gl.UNSIGNED_SHORT;
const offset = 0;
// Dessiner le serpent
snake.forEach(segment => {
const modelMatrix = mat4.clone(modelViewMatrix);
mat4.translate(modelMatrix, modelMatrix, [segment.x * 2, segment.y * 2, segment.z * 2]);
gl.uniformMatrix4fv(programInfo.uniformLocations.modelViewMatrix, false, modelMatrix);
gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);
});
// Dessiner la nourriture
const foodMatrix = mat4.clone(modelViewMatrix);
mat4.translate(foodMatrix, foodMatrix, [food.x * 2, food.y * 2, food.z * 2]);
gl.uniformMatrix4fv(programInfo.uniformLocations.modelViewMatrix, false, foodMatrix);
gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);
}
}
function updateSnake() {
const head = Object.assign({}, snake[0]);
if (direction === 'right') head.x += 1;
if (direction === 'left') head.x -= 1;
if (direction === 'up') head.y += 1;
if (direction === 'down') head.y -= 1;
if (direction === 'forward') head.z += 1;
if (direction === 'backward') head.z -= 1;
snake.unshift(head);
// Vérifier si le serpent a mangé la nourriture
if (head.x === food.x && head.y === food.y && head.z === food.z) {
food = {
x: Math.floor(Math.random()*10-5),
y: Math.floor(Math.random()*10-5),
z: Math.floor(Math.random()*10-5)
};
} else {
snake.pop();
}
// Vérifier les collisions avec les murs
if (Math.abs(head.x) > 10 || Math.abs(head.y) > 10 || Math.abs(head.z) > 10) {
alert('Game Over!');
snake = [{x:0, y:0, z:0}];
direction = 'right';
}
// Vérifier les collisions avec le corps
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y && head.z === snake[i].z) {
alert('Game Over!');
snake = [{x:0, y:0, z:0}];
direction = 'right';
}
}
}
function render(now) {
now *= 0.001;
const deltaTime = now - then;
then = now;
updateSnake();
drawScene(gl, programInfo, buffers, deltaTime);
setTimeout(() => {
requestAnimationFrame(render);
}, 100);
}
document.addEventListener('keydown', (event) => {
if (event.key === 'ArrowUp') direction = 'up';
if (event.key === 'ArrowDown') direction = 'down';
if (event.key === 'ArrowLeft') direction = 'left';
if (event.key === 'ArrowRight') direction = 'right';
if (event.key === 'w') direction = 'forward';
if (event.key === 's') direction = 'backward';
});
// Matrice utilitaire
const mat4 = {
create: function() {
return new Float32Array(16).fill(0).map((v, i) => (i % 5 === 0) ? 1 : 0);
},
perspective: function(out, fovy, aspect, near, far) {
const f = 1.0 / Math.tan(fovy / 2);
out[0] = f / aspect;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = f;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = (far + near) / (near - far);
out[11] = -1;
out[12] = 0;
out[13] = 0;
out[14] = (2 * far * near) / (near - far);
out[15] = 0;
},
translate: function(out, a, v) {
const x = v[0], y = v[1], z = v[2];
if (a === out) {
out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
} else {
const a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3];
const a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7];
const a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
out[0] = a00;
out[1] = a01;
out[2] = a02;
out[3] = a03;
out[4] = a10;
out[5] = a11;
out[6] = a12;
out[7] = a13;
out[8] = a20;
out[9] = a21;
out[10] = a22;
out[11] = a23;
out[12] = a00 * x + a10 * y + a20 * z + a[12];
out[13] = a01 * x + a11 * y + a21 * z + a[13];
out[14] = a02 * x + a12 * y + a22 * z + a[14];
out[15] = a03 * x + a13 * y + a23 * z + a[15];
}
return out;
},
clone: function(a) {
return new Float32Array(a);
}
};
requestAnimationFrame(render);
</script>
</body>
</html>
Instructions :
W (avance) et S (recul) pour déplacer le serpent sur l'axe Z.Note : Ce code crée un simple effet 3D en utilisant WebGL directement sans bibliothèques externes. Pour un jeu plus avancé avec des graphismes améliorés, il est recommandé d'utiliser une bibliothèque comme Three.js. Cependant, cela nécessiterait d'inclure du code supplémentaire qui augmenterait significativement la taille du fichier HTML.
Not yet included in a published release.