Skip to content

Commit

Permalink
added a market ratelimiter and also started coding a selling blook fe…
Browse files Browse the repository at this point in the history
…ature
  • Loading branch information
IzumiiHD committed Oct 3, 2024
1 parent 8fa8202 commit f0db07b
Show file tree
Hide file tree
Showing 9 changed files with 104 additions and 127 deletions.
Binary file added public/img/blooks/logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file removed public/img/emojis/Berry.png
Binary file not shown.
Binary file removed public/img/emojis/CurryEater.png
Binary file not shown.
Binary file removed public/img/emojis/ItsTornadoYT.png
Binary file not shown.
Binary file removed public/img/emojis/IzumiiHD.png
Binary file not shown.
Binary file removed public/img/emojis/Xotic.gif
Binary file not shown.
108 changes: 25 additions & 83 deletions public/javascript/pixels.js
Original file line number Diff line number Diff line change
Expand Up @@ -219,88 +219,30 @@ document.addEventListener('DOMContentLoaded', function() {
});
});

const modal = document.getElementById("sellModal");
const closeBtn = document.getElementsByClassName("close")[0];
const confirmSellBtn = document.getElementById("confirmSell");
const cancelSellBtn = document.getElementById("cancelSell");
const modalPixelImage = document.getElementById("modalPixelImage");
const modalPixelName = document.getElementById("modalPixelName");
const modalPixelRarity = document.getElementById("modalPixelRarity");

function openModal(name, imageSrc, rarity) {
modalPixelImage.src = imageSrc.includes("http")
? imageSrc
: "https://pixelit.replit.app/img/blooks/" + imageSrc;
modalPixelImage.style.display = "block";
modalPixelName.textContent = name;
if (rarity === 'uncommon') {
modalPixelRarity.innerHTML = `<span style='color: 4bc22e;'>${rarity.charAt(0).toUpperCase() + rarity.slice(1)}</span>`;
} else if (rarity === 'rare') {
modalPixelRarity.innerHTML = `<span style='color: blue;'>${rarity.charAt(0).toUpperCase() + rarity.slice(1)}</span>`;
} else if (rarity === 'epic') {
modalPixelRarity.innerHTML = `<span style='color: #be0000;'>${rarity.charAt(0).toUpperCase() + rarity.slice(1)}</span>`;
} else if (rarity === 'legendary') {
modalPixelRarity.innerHTML = `<span style='color: #ff910f;'>${rarity.charAt(0).toUpperCase() + rarity.slice(1)}</span>`;
} else if (rarity === 'chroma') {
modalPixelRarity.innerHTML = `<span style='color: #00ccff;'>${rarity.charAt(0).toUpperCase() + rarity.slice(1)}</span>`;
} else if (rarity === 'mystical') {
modalPixelRarity.innerHTML = `<span style='color: #9935dd;'>${rarity.charAt(0).toUpperCase() + rarity.slice(1)}</span>`;
} else {
modalPixelRarity.textContent = rarity.charAt(0).toUpperCase() + rarity.slice(1);
}
modal.style.display = "block";
}

function closeModal() {
modal.style.display = "none";
}

closeBtn.onclick = closeModal;

window.onclick = function(event) {
if (event.target == modal) {
closeModal();
sellButton.onclick = () => {
const name = document.querySelector('.blook-details h3').textContent;
const confirmation = confirm(`Are you sure you want to sell ${name}?`);

if (confirmation) {
fetch("/sellBlook", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ name: name }),
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert(data.message);
location.reload();
} else {
alert("Failed to sell blook: " + data.message);
}
})
.catch(error => {
console.error("Error:", error);
alert("An error occurred while trying to sell the blook.");
});
}
}

cancelSellBtn.onclick = closeModal;

confirmSellBtn.onclick = function() {
const name = modalPixelName.textContent;
fetch('/sellBlook', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name }),
})
.then(response => response.json())
.then(data => {
alert(data.message);
closeModal();
fetch("/user")
.then(response => response.json())
.then(data => {
const packs = data.packs;
generatePacksHTML(packs);
});
})
.catch(error => {
console.error('Error selling blook:', error);
alert('An error occurred while selling the blook');
});
};

sellButton.onclick = () => {
const name = blookName.textContent;
const imageSrc = blookImage.src.includes("/blooks/")
? blookImage.src
: "https://pixelit.replit.app/img/blooks/" + blookImage.src;
const rarity = blookRarity.textContent;

const modalContent = document.getElementById('modal-content');
modalContent.querySelector('.modal-name').textContent = name;
modalContent.querySelector('.modal-image').src = imageSrc;
modalContent.querySelector('.modal-rarity').textContent = rarity;
document.getElementById('modal').style.display = 'block';
};
26 changes: 0 additions & 26 deletions public/site/pixels.html
Original file line number Diff line number Diff line change
Expand Up @@ -109,32 +109,6 @@ <h3 id="blook-owned"></h3>
<button id="sell-blook" class="button-style" onmouseover="this.classList.add('button-hover-scale');" onmouseout="this.classList.remove('button-hover-scale');">
Sell Pixel <i class="fa-solid fa-dollar-sign"></i>
</button>
</button>
</div>
<div id="sellModal" class="modal">
<div class="modal-content">
<span class="close">&times;</span>
<h2>Sell Pixel</h2>
<h3>Are you sure you want to sell this Pixel?</h3>
<div class="pixel-info">
<img id="modalPixelImage" src="" alt="Pixel Image">
<div class="pixel-details">
<p id="modalPixelName"></p>
<p id="modalPixelRarity"></p>
</div>
</div>
<div class="button-group">
<button id="confirmSell">Yes</button>

<label for="sellAmount" style="font-size: 1.5em;">Amount:</label>
<input type="number" id="sellAmount" min="1" style="width: 50px; border-radius: 5px" />
<span></span>
<span id="totalBlooksOwned"></span>
<button id="cancelSell">No</button>
</div>
</div>
</div>
</center>
<script src="https://cdn.socket.io/4.7.5/socket.io.min.js"></script>
<script src="/javascript/pixels.js"></script>
</body>
Expand Down
97 changes: 79 additions & 18 deletions routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -327,65 +327,60 @@ router.get("/packs", async (req, res) => {
res.status(200).send(packs);
});

router.get("/openPack", async (req, res) => {
const packOpenLimiter = rateLimit({
windowMs: 1000,
max: 2,
message: "Too many pack openings, please try again later.",
handler: (req, res) => {
res.status(429).redirect('/site/index.html');
}
});

router.get("/openPack", packOpenLimiter, async (req, res) => {
const session = req.session;
if (session && session.loggedIn) {
//await client.connect();
//console.log("openpackreq");

const user = {
name: session.username,
};

const opack = req.query.pack;

// Retrieve user data from MongoDB
const person = await users.findOne({ username: user.name });
//console.log("Retrieved user data:", person); // Log retrieved user data

if (person === null) return;

// Validate password
/*if (!validatePassword(user.pass, person.password, person.salt)) {
console.log("False password");
return;
}*/

// Retrieve pack data from MongoDB
/*console.log(opack)
console.log(await packs.find().toArray())*/
const pack = await packs.findOne({ name: opack });
//console.log("Retrieved pack data:", pack); // Log retrieved pack data

if (pack === null) {
console.log("Invalid pack");
return;
}

if (person.tokens < pack.cost) return;

const blooks = pack.blooks;
let totalchance = 0;
for (const b of blooks) {
totalchance += Number(b.chance);
}
const randnum = rand(0, totalchance);
let currentchance = 0;

//console.log(pack);

//console.log("test", randnum, totalchance);

for (const b of blooks) {
const blook = b;
//console.log("Current blook:", blook); // Log current blook

if (
randnum >= currentchance &&
randnum <= currentchance + Number(blook.chance)
) {
//console.log("Selected blook:", blook); // Log selected blook

// Update user data in MongoDB
/*await users
.updateOne(
Expand Down Expand Up @@ -439,23 +434,22 @@ router.get("/openPack", async (req, res) => {
{ username: user.name },
{ $inc: { tokens: -pack.cost } },
);

console.log(
`${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`,
);

res.status(200).send({ pack: pack.name, blook: blook });
/*io.to(socket.id).emit("openPack", {
pack: pack.name,
blook: blook,
});*/
//const testuser = await users.findOne({ username: user.name });
//io.to(socket.id).emit("tokens", await testuser.tokens);

console.log(`${user.name} opened ${pack.name} and got ${blook.name}`);
}
currentchance += Number(blook.chance);
}
} else {
res.status(401).send("Unauthorized");
}
});

Expand Down Expand Up @@ -819,4 +813,71 @@ app.post('/webhook', express.raw({type: 'application/json'}), async (req, res) =
res.json({received: true});
});

const RARITY_SELL_PRICES = {
'uncommon': 5,
'rare': 20,
'epic': 75,
'legendary': 200,
'chroma': 300,
'mystical': 1000
};

router.post('/sellBlook', async (req, res) => {
const session = req.session;
if (!session.loggedIn) {
return res.status(401).json({ success: false, message: "You are not logged in" });
}

const { name: blookName } = req.body;

try {
const user = await users.findOne({ username: session.username });
if (!user) {
return res.status(404).json({ success: false, message: "User not found" });
}

let blookFound = false;
let sellValue = 0;

for (const pack of user.packs) {
const blookIndex = pack.blooks.findIndex(blook => blook.name === blookName);
if (blookIndex !== -1 && pack.blooks[blookIndex].owned > 0) {
blookFound = true;
const blook = pack.blooks[blookIndex];
sellValue = RARITY_SELL_PRICES[blook.rarity] || 0;
await users.updateOne(
{ username: session.username, "packs.name": pack.name, "packs.blooks.name": blookName },
{
$inc: {
tokens: sellValue,
[`packs.$[pack].blooks.$[blook].owned`]: -1
}
},
{
arrayFilters: [
{ "pack.name": pack.name },
{ "blook.name": blookName }
]
}
);

break;
}
}

if (!blookFound) {
return res.status(404).json({ success: false, message: "Blook not found in user's inventory" });
}

res.status(200).json({
success: true,
message: `Successfully sold ${blookName} for ${sellValue} tokens`
});

} catch (error) {
console.error("Error selling blook:", error);
res.status(500).json({ success: false, message: "Internal server error" });
}
});

module.exports = router;

0 comments on commit f0db07b

Please sign in to comment.