Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
335 changes: 156 additions & 179 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,182 +1,159 @@
const { MongoClient } = require("mongodb");

async function run() {
// TODO:
// Replace the placeholder connection string below with your
// Altas cluster specifics. Be sure it includes
// a valid username and password! Note that in a production environment,
// you do not want to store your password in plain-text here.
const uri =
"mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&w=majority";

// The MongoClient is the object that references the connection to our
// datastore (Atlas, for example)
const client = new MongoClient(uri);

// The connect() method does not attempt a connection; instead it instructs
// the driver to connect using the settings provided when a connection
// is required.
await client.connect();

// Provide the name of the database and collection you want to use.
// If the database and/or collection do not exist, the driver and Atlas
// will create them automatically when you first write data.
const dbName = "myDatabase";
const collectionName = "recipes";

// Create references to the database and collection in order to run
// operations on them.
const database = client.db(dbName);
const collection = database.collection(collectionName);

/*
* *** INSERT DOCUMENTS ***
*
* You can insert individual documents using collection.insert().
* In this example, we're going to create four documents and then
* insert them all in one call with collection.insertMany().
*/

const recipes = [
{
name: "elotes",
ingredients: [
"corn",
"mayonnaise",
"cotija cheese",
"sour cream",
"lime",
],
prepTimeInMinutes: 35,
},
{
name: "loco moco",
ingredients: [
"ground beef",
"butter",
"onion",
"egg",
"bread bun",
"mushrooms",
],
prepTimeInMinutes: 54,
},
{
name: "patatas bravas",
ingredients: [
"potato",
"tomato",
"olive oil",
"onion",
"garlic",
"paprika",
],
prepTimeInMinutes: 80,
},
{
name: "fried rice",
ingredients: [
"rice",
"soy sauce",
"egg",
"onion",
"pea",
"carrot",
"sesame oil",
],
prepTimeInMinutes: 40,
},
];

try {
const insertManyResult = await collection.insertMany(recipes);
console.log(`${insertManyResult.insertedCount} documents successfully inserted.\n`);
} catch (err) {
console.error(`Something went wrong trying to insert the new documents: ${err}\n`);
}

/*
* *** FIND DOCUMENTS ***
*
* Now that we have data in Atlas, we can read it. To retrieve all of
* the data in a collection, we call Find() with an empty filter.
* The Builders class is very helpful when building complex
* filters, and is used here to show its most basic use.
*/

const findQuery = { prepTimeInMinutes: { $lt: 45 } };

try {
const cursor = await collection.find(findQuery).sort({ name: 1 });
await cursor.forEach(recipe => {
console.log(`${recipe.name} has ${recipe.ingredients.length} ingredients and takes ${recipe.prepTimeInMinutes} minutes to make.`);
});
// add a linebreak
console.log();
} catch (err) {
console.error(`Something went wrong trying to find the documents: ${err}\n`);
}

// We can also find a single document. Let's find the first document
// that has the string "potato" in the ingredients list.
const findOneQuery = { ingredients: "potato" };

try {
const findOneResult = await collection.findOne(findOneQuery);
if (findOneResult === null) {
console.log("Couldn't find any recipes that contain 'potato' as an ingredient.\n");
const html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>🐍 Alzaeem Tech AI - Snake Game</title>
<style>
body {
background: radial-gradient(circle at center, #0a0a0a, #000);
color: #00ffcc;
font-family: 'Poppins', sans-serif;
text-align: center;
margin: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
canvas {
background: #111;
box-shadow: 0 0 25px #00ffcc;
border-radius: 12px;
}
h1 {
color: #00ffff;
text-shadow: 0 0 20px #00ffff;
font-size: 2em;
}
.controls {
margin-top: 20px;
}
button {
background: #00ffcc;
color: #000;
border: none;
padding: 10px 20px;
margin: 6px;
border-radius: 8px;
cursor: pointer;
font-weight: bold;
transition: 0.3s;
}
button:hover {
background: #00ffaa;
}
#score {
margin: 10px;
font-size: 1.3em;
}
</style>
</head>
<body>
<h1>🤖 Alzaeem Tech AI Snake Game</h1>
<canvas id="game" width="400" height="400"></canvas>
<div id="score">Score: 0</div>
<div class="controls">
<button onclick="changeDir('UP')">⬆️</button><br>
<button onclick="changeDir('LEFT')">⬅️</button>
<button onclick="changeDir('DOWN')">⬇️</button>
<button onclick="changeDir('RIGHT')">➡️</button><br>
<button onclick="startGame()">🚀 Start</button>
</div>

<script>
let canvas = document.getElementById('game');
let ctx = canvas.getContext('2d');
let box = 20;
let snake = [{x: 9 * box, y: 10 * box}];
let food = {x: Math.floor(Math.random()*19+1)*box, y: Math.floor(Math.random()*19+1)*box};
let score = 0;
let d;
let game;
let speed = 150;

document.addEventListener('keydown', dir);

function dir(event){
if(event.keyCode == 37 && d != "RIGHT") d = "LEFT";
else if(event.keyCode == 38 && d != "DOWN") d = "UP";
else if(event.keyCode == 39 && d != "LEFT") d = "RIGHT";
else if(event.keyCode == 40 && d != "UP") d = "DOWN";
}

function changeDir(direction){
if(direction == "LEFT" && d != "RIGHT") d = "LEFT";
else if(direction == "UP" && d != "DOWN") d = "UP";
else if(direction == "RIGHT" && d != "LEFT") d = "RIGHT";
else if(direction == "DOWN" && d != "UP") d = "DOWN";
}

function draw(){
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, 400, 400);

for(let i = 0; i < snake.length; i++){
ctx.fillStyle = (i == 0) ? "#00ffcc" : "#00ffaa";
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = "#000";
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}

ctx.fillStyle = "red";
ctx.fillRect(food.x, food.y, box, box);

let snakeX = snake[0].x;
let snakeY = snake[0].y;

if(d == "LEFT") snakeX -= box;
if(d == "UP") snakeY -= box;
if(d == "RIGHT") snakeX += box;
if(d == "DOWN") snakeY += box;

if(snakeX == food.x && snakeY == food.y){
score++;
document.getElementById('score').innerText = "Score: " + score;
food = {x: Math.floor(Math.random()*19+1)*box, y: Math.floor(Math.random()*19+1)*box};
} else {
console.log(`Found a recipe with 'potato' as an ingredient:\n${JSON.stringify(findOneResult)}\n`);
snake.pop();
}

let newHead = {x: snakeX, y: snakeY};

if(snakeX < 0 || snakeY < 0 || snakeX >= 400 || snakeY >= 400 || collision(newHead, snake)){
clearInterval(game);
alert('Game Over! Score: ' + score);
return;
}
} catch (err) {
console.error(`Something went wrong trying to find one document: ${err}\n`);
}

/*
* *** UPDATE A DOCUMENT ***
*
* You can update a single document or multiple documents in a single call.
*
* Here we update the PrepTimeInMinutes value on the document we
* just found.
*/
const updateDoc = { $set: { prepTimeInMinutes: 72 } };

// The following updateOptions document specifies that we want the *updated*
// document to be returned. By default, we get the document as it was *before*
// the update.
const updateOptions = { returnOriginal: false };

try {
const updateResult = await collection.findOneAndUpdate(
findOneQuery,
updateDoc,
updateOptions,
);
console.log(`Here is the updated document:\n${JSON.stringify(updateResult.value)}\n`);
} catch (err) {
console.error(`Something went wrong trying to update one document: ${err}\n`);
}

/* *** DELETE DOCUMENTS ***
*
* As with other CRUD methods, you can delete a single document
* or all documents that match a specified filter. To delete all
* of the documents in a collection, pass an empty filter to
* the DeleteMany() method. In this example, we'll delete two of
* the recipes.
*/


const deleteQuery = { name: { $in: ["elotes", "fried rice"] } };
try {
const deleteResult = await collection.deleteMany(deleteQuery);
console.log(`Deleted ${deleteResult.deletedCount} documents\n`);
} catch (err) {
console.error(`Something went wrong trying to delete documents: ${err}\n`);
}

// Make sure to call close() on your client to perform cleanup operations
await client.close();

snake.unshift(newHead);
}

function collision(head, array){
for(let i = 0; i < array.length; i++){
if(head.x == array[i].x && head.y == array[i].y){
return true;
}
}
return false;
}

function startGame(){
clearInterval(game);
snake = [{x: 9 * box, y: 10 * box}];
d = undefined;
score = 0;
document.getElementById('score').innerText = "Score: 0";
game = setInterval(draw, speed);
}
run().catch(console.dir);
</script>
</body>
</html>
`;

module.exports = (req, res) => {
res.setHeader("Content-Type", "text/html");
res.end(html);
};