Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Pixel Jets</title>
- <style>
- body { margin: 0; }
- canvas { display: block; }
- #scoreboard {
- position: absolute;
- top: 10px;
- left: 10px;
- color: white;
- font-family: Arial, sans-serif;
- font-size: 18px;
- z-index: 100;
- }
- </style>
- </head>
- <body>
- <div>
- <input type="text" id="username" placeholder="Enter your username">
- <button onclick="startGame()">Start Game</button>
- </div>
- <div id="scoreboard"></div>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/tensorflow/2.8.0/tf.min.js"></script>
- <script>
- // Set up the scene, camera, renderer...
- // Your existing code here...
- // Initialize username and score list
- let username = '';
- const scoreList = [];
- // Function to start the game
- function startGame() {
- // Get username from input field
- username = document.getElementById('username').value;
- // Hide the input field and button
- document.getElementById('username').style.display = 'none';
- document.querySelector('button').style.display = 'none';
- }
- // Function to update scoreboard with username
- function updateScoreboard() {
- scoreDisplay.textContent = `Player: ${username} - Score: ${score}`;
- }
- // Function to check if all spheres are destroyed
- function allSpheresDestroyed() {
- return activeEnemySpheres === 0 && destroyedEnemySpheres === maxEnemySpheres;
- }
- // Render loop...
- // Your existing code here...
- // Inside the render loop, check if all spheres are destroyed
- if (allSpheresDestroyed()) {
- // Add username and score to the list
- scoreList.push({ username: username, score: score });
- // Reset the game or show game over message, etc.
- console.log(scoreList); // Display the score list in the console
- }
- </script>
- <script>
- // Set up the scene, camera, renderer
- const scene = new THREE.Scene();
- const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
- camera.position.set(0, 0, 5); // Move the camera back
- const renderer = new THREE.WebGLRenderer();
- renderer.setSize(window.innerWidth, window.innerHeight);
- document.body.appendChild(renderer.domElement);
- // Add a directional light to the scene
- const light = new THREE.DirectionalLight(0xffffff, 1);
- light.position.set(0, 1, 1);
- scene.add(light);
- // Create a cube to represent the player
- const playerGeometry = new THREE.BoxGeometry(1, 1, 1);
- const playerMaterial = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
- const player = new THREE.Mesh(playerGeometry, playerMaterial);
- scene.add(player);
- // Create the ground
- //const groundGeometry = new THREE.PlaneGeometry(100, 100);
- // const groundMaterial = new THREE.MeshBasicMaterial({ color: 0xaaaaaa, side: THREE.DoubleSide });
- // const ground = new THREE.Mesh(groundGeometry, groundMaterial);
- // ground.rotation.x = -Math.PI / 2; // Rotate the ground to be horizontal
- //scene.add(ground);
- // Create the skybox (a large sphere with a texture)
- const skyGeometry = new THREE.SphereGeometry(1000, 32, 32);
- const skyMaterial = new THREE.MeshBasicMaterial({ color: 0x87CEEB, side: THREE.BackSide }); // Light blue color
- const skybox = new THREE.Mesh(skyGeometry, skyMaterial);
- scene.add(skybox);
- // Create AI cube
- const aiCubeGeometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
- const aiCubeMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
- const aiCube = new THREE.Mesh(aiCubeGeometry, aiCubeMaterial);
- aiCube.position.set(1, 0.75, 0); // Initial position relative to the player cube
- scene.add(aiCube);
- // Update function to make the AI cube follow the player cube
- function updateAICubePosition() {
- aiCube.position.copy(player.position); // Set AI cube's position to player cube's position
- aiCube.translateX(1); // Move the AI cube to the right (shoulder position)
- aiCube.translateY(0.75); // Move the AI cube upward (shoulder position)
- }
- // Create AI projectiles
- const aiProjectiles = [];
- const maxAIProjectiles = 3; // Maximum number of AI projectiles
- for (let i = 0; i < maxAIProjectiles; i++) {
- const aiProjectileGeometry = new THREE.SphereGeometry(0.1, 16, 16); // Use sphere geometry
- const aiProjectileMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
- const aiProjectiles = [];
- const maxAIProjectiles = 3; // Maximum number of AI projectiles
- for (let i = 0; i < maxAIProjectiles; i++) {
- const aiProjectile = new THREE.Mesh(aiProjectileGeometry, aiProjectileMaterial);
- aiProjectile.visible = false;
- aiProjectiles.push(aiProjectile);
- scene.add(aiProjectile);
- }
- }
- // Function to make the AI cube shoot projectiles continuously
- function shootAIProjectilesContinuously() {
- shootAIProjectiles(); // Shoot projectiles towards the player
- setTimeout(shootAIProjectilesContinuously, 5000); // Shoot every 1 second (adjust as needed)
- }
- // Function to make the AI cube shoot projectiles
- function shootAIProjectiles() {
- const direction = player.position.clone().sub(aiCube.position).normalize();
- const availableProjectile = aiProjectiles.find(proj => !proj.visible);
- if (availableProjectile) {
- availableProjectile.position.copy(aiCube.position);
- availableProjectile.direction = direction;
- availableProjectile.visible = true;
- }
- }
- shootAIProjectilesContinuously();
- // Declare enemySpheres array
- // Function to make the AI cube shoot homing missiles towards the closest enemy sphere
- // Function to make the AI cube shoot homing missiles towards nearby enemy spheres
- // Function to make the AI cube shoot homing missiles towards nearby enemy spheres
- function shootHomingMissiles() {
- const closestEnemies = findClosestEnemies();
- closestEnemies.forEach((enemy) => {
- const missile = new THREE.Mesh(
- new THREE.SphereGeometry(0.1, 16, 16),
- new THREE.MeshBasicMaterial({ color: 0xff0000 })
- );
- missile.position.copy(aiCube.position);
- missile.target = enemy; // Store the enemy object as the target
- homingMissiles.push(missile);
- scene.add(missile);
- });
- }
- // Function to find the closest enemy spheres
- function findClosestEnemies() {
- const closestEnemies = [];
- enemySpheres.forEach((enemy) => {
- if (enemy.visible) {
- const distance = aiCube.position.distanceTo(enemy.position);
- if (distance < 1.2) { // Change the range as needed
- closestEnemies.push(enemy);
- }
- }
- });
- return closestEnemies;
- }
- const enemySpheres = [];
- // Set up keyboard input
- const keyboard = {};
- document.addEventListener('keydown', (event) => {
- keyboard[event.key] = true;
- });
- document.addEventListener('keyup', (event) => {
- keyboard[event.key] = false;
- });
- // Update player position based on keyboard input
- const playerSpeed = 0.1;
- function updatePlayerPosition() {
- if (keyboard['a']) player.position.x -= playerSpeed;
- if (keyboard['d']) player.position.x += playerSpeed;
- if (keyboard['w']) player.position.y += playerSpeed;
- if (keyboard['s']) player.position.y -= playerSpeed;
- }
- // Create projectile (ball) objects
- const projectiles = [];
- const maxProjectiles = 10000; // Maximum number of projectiles
- for (let i = 0; i < maxProjectiles; i++) {
- const projectileGeometry = new THREE.SphereGeometry(0.1, 32, 32);
- const projectileMaterial = new THREE.MeshBasicMaterial({ color: 0xFFFF00 });
- const projectile = new THREE.Mesh(projectileGeometry, projectileMaterial);
- projectile.visible = false;
- projectiles.push(projectile);
- scene.add(projectile);
- }
- // Create enemy spheres
- const maxEnemySpheres = 3; // Maximum number of enemy spheres
- let activeEnemySpheres = 0; // Track the number of active enemy spheres
- let destroyedEnemySpheres = 0; // Track the number of destroyed enemy spheres
- // Function to spawn enemy spheres
- function spawnEnemySphere() {
- if (activeEnemySpheres < maxEnemySpheres) {
- const enemyGeometry = new THREE.SphereGeometry(0.2, 32, 32);
- const enemyMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
- const enemy = new THREE.Mesh(enemyGeometry, enemyMaterial);
- const spawnPosition = new THREE.Vector3(Math.random() * 10 - 5, Math.random() * 5, -10 - Math.random() * 10);
- enemy.position.copy(spawnPosition);
- enemy.userData.spawnPosition = spawnPosition; // Set the spawn position in userData
- // Set the targetPlayer property with a 10% chance
- enemy.targetPlayer = Math.random() <= 0.1;
- enemy.visible = true; // Initially visible
- activeEnemySpheres++;
- scene.add(enemy);
- enemySpheres.push(enemy);
- // Create projectiles for the enemy sphere
- enemy.projectiles = [];
- const maxEnemyProjectiles = 5; // Maximum number of enemy projectiles
- for (let i = 0; i < maxEnemyProjectiles; i++) {
- const enemyProjectileGeometry = new THREE.SphereGeometry(0.05, 16, 16);
- const enemyProjectileMaterial = new THREE.MeshBasicMaterial({ color: 0xFFFF00 });
- const enemyProjectile = new THREE.Mesh(enemyProjectileGeometry, enemyProjectileMaterial);
- enemyProjectile.visible = false;
- enemy.projectiles.push(enemyProjectile);
- scene.add(enemyProjectile);
- }
- }
- }
- // Initial spawn of enemy spheres
- for (let i = 0; i < maxEnemySpheres; i++) {
- spawnEnemySphere();
- }
- // Score variables
- let score = 0;
- const scoreDisplay = document.getElementById('scoreboard');
- // Function for enemies to shoot at the player
- function enemyShootProjectiles() {
- enemySpheres.forEach((enemy) => {
- if (enemy.visible) {
- const availableProjectile = enemy.projectiles.find(proj => !proj.visible);
- if (availableProjectile) {
- availableProjectile.position.copy(enemy.position);
- const direction = player.position.clone().sub(enemy.position).normalize();
- availableProjectile.direction = direction;
- availableProjectile.visible = true;
- }
- }
- });
- }
- const homingMissiles = [];
- // Set initial camera position and orientation
- let currentView = 2;
- function setCameraView(view) {
- currentView = view;
- switch (view) {
- case 1: // First person view
- camera.position.copy(player.position);
- camera.position.z += 0.5; // Slightly in front of the player
- camera.lookAt(player.position.clone().add(new THREE.Vector3(0, 0, -1)));
- break;
- case 2: // Default view
- camera.position.set(0, 0, 5);
- camera.lookAt(0, 0, 0);
- break;
- case 3: // Third person view
- camera.position.copy(player.position.clone().add(new THREE.Vector3(0, 5, 10)));
- camera.lookAt(player.position);
- break;
- }
- }
- // Event listener for key presses to change camera view
- document.addEventListener('keydown', (event) => {
- if (event.key === '1') setCameraView(1);
- if (event.key === '2') setCameraView(2);
- if (event.key === '3') setCameraView(3);
- });
- // Render loop
- function animate() {
- requestAnimationFrame(animate);
- updatePlayerPosition();
- updateAICubePosition();
- shootAIProjectiles(); // Shoot AI projectiles continuously
- enemyShootProjectiles(); // Enemies shoot projectiles at the player
- shootHomingMissiles(); // AI cube shoots homing missiles automatically
- moveHomingMissiles(); // Move homing missiles towards their targets
- dodgeProjectiles();
- // Move enemy spheres forward or towards the player
- enemySpheres.forEach((enemy) => {
- if (enemy.visible) {
- if (enemy.targetPlayer) {
- // Calculate direction towards the player
- const direction = player.position.clone().sub(enemy.position).normalize();
- enemy.position.add(direction.multiplyScalar(0.05)); // Move towards the player
- } else {
- enemy.position.z += 0.05; // Move forward
- }
- // Respawn enemy sphere if it goes past the cube or is not visible
- if (enemy.position.z > 10 || !isSphereVisible(enemy)) {
- enemy.visible = false;
- activeEnemySpheres--;
- // Respawn enemy sphere
- respawnEnemySphere(enemy);
- }
- }
- });
- // Update camera for first-person view
- if (currentView === 1) {
- camera.position.copy(player.position);
- camera.position.z += 0.5; // Slightly in front of the player
- camera.lookAt(player.position.clone().add(new THREE.Vector3(0, 0, -1)));
- }
- // Move projectiles
- for (let i = 0; i < maxProjectiles; i++) {
- const projectile = projectiles[i];
- if (projectile.visible) {
- projectile.position.add(projectile.direction.clone().multiplyScalar(0.2)); // Adjust speed of projectiles
- // Check if projectile is out of bounds
- if (projectile.position.z > 10) {
- projectile.visible = false; // Hide the projectile
- }
- }
- }
- // Move AI projectiles
- aiProjectiles.forEach((projectile) => {
- if (projectile.visible) {
- projectile.position.add(projectile.direction.clone().multiplyScalar(0.2));
- if (projectile.position.z > 10) {
- projectile.visible = false;
- }
- }
- });
- // Move enemy projectiles
- enemySpheres.forEach((enemy) => {
- enemy.projectiles.forEach((projectile) => {
- if (projectile.visible) {
- projectile.position.add(projectile.direction.clone().multiplyScalar(0.2)); // Adjust speed of projectiles
- // Check if projectile is out of bounds
- if (projectile.position.z > 10) {
- projectile.visible = false; // Hide the projectile
- }
- }
- });
- });
- // Check for collisions between enemy spheres and projectiles or cube
- enemySpheres.forEach((enemy) => {
- if (enemy.visible) {
- // Check for collisions with projectiles
- projectiles.forEach((projectile) => {
- if (projectile.visible && enemy.position.distanceTo(projectile.position) < 0.3) {
- // Enemy hit by projectile, respawn with a random new origin
- respawnEnemySphere(enemy);
- projectile.visible = false; // Hide the projectile
- score++; // Increment score
- updateScoreboard();
- }
- });
- // Check for collisions with the cube (player)
- if (enemy.position.distanceTo(player.position) < 0.6) {
- // Cube hit by enemy, respawn with a random new origin
- respawnEnemySphere(enemy);
- score--; // Decrement score
- updateScoreboard();
- }
- }
- });
- // Check for collisions between enemy projectiles and player
- enemySpheres.forEach((enemy) => {
- enemy.projectiles.forEach((projectile) => {
- if (projectile.visible && player.position.distanceTo(projectile.position) < 0.5) {
- // Player hit by enemy projectile
- projectile.visible = false; // Hide the projectile
- score--; // Decrement score
- updateScoreboard();
- }
- });
- });
- renderer.render(scene, camera);
- }
- animate();
- // Function to move homing missiles towards their targets
- function moveHomingMissiles() {
- homingMissiles.forEach((missile) => {
- if (missile.visible && missile.target) {
- const direction = missile.target.position.clone().sub(missile.position).normalize();
- missile.position.add(direction.multiplyScalar(0.1)); // Adjust missile speed
- if (missile.position.distanceTo(missile.target.position) < 0.2) {
- missile.visible = false; // Hide the missile upon reaching the target
- missile.target.visible = false; // Hide the target enemy sphere
- }
- }
- });
- }
- // Function to move enemy spheres and dodge projectiles
- function moveEnemySpheres() {
- enemySpheres.forEach((enemy) => {
- if (enemy.visible) {
- homingMissiles.forEach((missile) => {
- if (missile.visible && missile.target === enemy) {
- const distance = enemy.position.distanceTo(missile.position);
- if (distance < 2) { // If missile is close to the enemy
- const dodgeDirection = enemy.position.clone().sub(missile.position).normalize();
- enemy.position.add(dodgeDirection.multiplyScalar(0.05)); // Adjust dodge speed
- }
- }
- });
- }
- });
- }
- // Automatically shoot homing missiles at a set interval
- setInterval(shootHomingMissiles, 3000); // Shoot every 3 seconds (slower)
- // Function to shoot AI projectiles continuously
- function shootAIProjectilesContinuous() {
- setInterval(shootAIProjectiles, 5000); // Adjust interval as needed (milliseconds)
- }
- // Function to make enemy spheres dodge projectiles
- function dodgeProjectiles() {
- enemySpheres.forEach((enemy) => {
- if (enemy.visible) {
- projectiles.forEach((projectile) => {
- if (projectile.visible) {
- const distance = enemy.position.distanceTo(projectile.position);
- if (distance < 1.49) { // Adjust this distance as needed
- const dodgeDirection = enemy.position.clone().sub(projectile.position).normalize();
- enemy.position.add(dodgeDirection.multiplyScalar(0.019)); // Adjust dodge speed as needed
- }
- }
- });
- }
- });
- }
- // Function to make the AI cube shoot projectiles towards the player
- function shootAIProjectiles() {
- const direction = player.position.clone().sub(aiCube.position).normalize();
- const availableProjectile = aiProjectiles.find(proj => !proj.visible);
- if (availableProjectile) {
- availableProjectile.position.copy(aiCube.position);
- availableProjectile.direction = direction;
- availableProjectile.visible = true;
- }
- }
- // Call the function to shoot AI projectiles continuously
- shootAIProjectilesContinuous();
- // Listen for spacebar press to shoot projectiles
- document.addEventListener('keydown', (event) => {
- if (event.key === ' ') { // Spacebar
- shootProjectiles();
- playSound(); // Play sound on spacebar press
- }
- });
- let canShoot = true;
- function shootProjectiles() {
- if (canShoot) {
- canShoot = false;
- for (let i = 0; i < maxProjectiles; i++) {
- const projectile = projectiles[i];
- if (!projectile.visible) {
- projectile.position.copy(player.position); // Set projectile position to player position
- projectile.visible = true; // Show the projectile
- projectile.direction = new THREE.Vector3(0, 0, -1); // Set projectile direction
- break; // Break out of loop after shooting one projectile
- }
- }
- setTimeout(() => {
- canShoot = true;
- }, 10); // Reload cooldown (milliseconds)
- }
- }
- // Check if a sphere is visible on the screen
- function isSphereVisible(sphere) {
- const frustum = new THREE.Frustum();
- const cameraViewProjectionMatrix = new THREE.Matrix4();
- camera.updateMatrixWorld(); // make sure the camera matrix is updated
- camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
- cameraViewProjectionMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
- frustum.setFromProjectionMatrix(cameraViewProjectionMatrix);
- return frustum.intersectsObject(sphere);
- }
- // Respawn enemy sphere with a random new origin
- function respawnEnemySphere(enemy) {
- const distanceFactor = Math.random() >= 0.5 ? 2 : 1; // Randomly choose between 1x or 2x
- const newOrigin = new THREE.Vector3(
- Math.random() * 10 - 5,
- Math.random() * 5,
- -10 - Math.random() * 10
- ).addScaledVector(new THREE.Vector3(0, 0, -1), 10 * distanceFactor);
- if (enemy) {
- enemy.position.copy(newOrigin);
- enemy.visible = true;
- activeEnemySpheres++;
- }
- }
- // Update scoreboard
- function updateScoreboard() {
- scoreDisplay.textContent = `Score: ${score}`;
- }
- // Function to play sound
- function playSound() {
- const context = new AudioContext();
- const oscillator = context.createOscillator();
- oscillator.connect(context.destination);
- oscillator.type = 'sine';
- oscillator.frequency.setValueAtTime(1000, context.currentTime); // Set frequency
- oscillator.start();
- setTimeout(() => {
- oscillator.stop();
- }, 100); // Stop after 100 milliseconds
- }
- // TensorFlow.js integration
- const model = tf.sequential();
- model.add(tf.layers.dense({units: 64, inputShape: [3], activation: 'relu'}));
- model.add(tf.layers.dense({units: 64, activation: 'relu'}));
- model.add(tf.layers.dense({units: 2, activation: 'softmax'}));
- model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
- // Prepare data for training (very basic, just for demonstration)
- const trainingData = [];
- const outputData = [];
- for (let i = 0; i < 1000; i++) {
- const x1 = Math.random();
- const x2 = Math.random();
- const y = x1 + x2 > 1 ? 1 : 0; // Sum greater than 1 => 1, otherwise 0
- trainingData.push([x1, x2, 1]); // Third input (1) to simulate the bias
- outputData.push([y, 1 - y]); // One-hot encoded labels
- }
- // Convert data to tensors
- const xs = tf.tensor2d(trainingData);
- const ys = tf.tensor2d(outputData);
- // Train the model
- model.fit(xs, ys, {epochs: 10}).then(() => {
- // Model training complete
- console.log('Model training complete');
- });
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement