我正在开发一款游戏,玩家获得初始投资(由投资者随机提供).这成为他们在产品上花费的预算.我正在try 编写代码,以便当他们购买一种产品(他们可以购买多个相同的产品)时,通过扣除成本将其反映在预算中.我一直收到预算不足的错误,当有足够的钱时,我不确定为什么.
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Investment Game</title>
</head>
<body>
<h1>Welcome to the Investment Game</h1>
<p>Your budget is: $<span id="budget">...</span></p>
<h2>Products:</h2>
<ul id="products">
</ul>
<script>
// Get the initial budget and product list when the page loads
fetch('GetInitialData.php').then(response => response.json()).then(data => {
document.getElementById('budget').innerText = data.budget;
const productsElement = document.getElementById('products');
data.products.forEach(product => {
const listItem = document.createElement('li');
listItem.innerHTML = `${product.name} ($${product.price})
<button onclick="buyProduct('${product.name}', ${product.price})">Buy</button>`;
productsElement.appendChild(listItem);
});
});
// Function to buy a product
function buyProduct(name, price) {
fetch('BuyProduct.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({productName: name, price: price}),
})
.then(response => response.json())
.then(data => {
if(data.success) {
document.getElementById('budget').innerText = data.newBudget;
} else {
alert(data.message);
}
})
.catch(error => console.error('Error:', error));
}
</script>
</body>
</html>
BuyProduct.php
<?php
session_start();
$inputData = json_decode(file_get_contents('php://input'), true);
$productName = $inputData['productName'];
$price = $inputData['price'];
// Check if user has enough budget
if($_SESSION['budget'] >= $price) {
$_SESSION['budget'] -= $price;
echo json_encode(array("success" => true, "newBudget" => $_SESSION['budget']));
} else {
echo json_encode(array("success" => false, "message" => "Insufficient budget"));
}
?>
GetInitialData.php
<?php
session_start();
$investors = array(
"Fred" => 24000,
"Barney" => 32000
);
// Assign a random investor's budget to session if not already set
if (!isset($_SESSION['budget'])) {
$randomInvestor = array_rand($investors);
$_SESSION['budget'] = $investors[$randomInvestor];
}
// Example product list
$products = array(
array("name" => "Product 1", "price" => 100),
array("name" => "Product 2", "price" => 150)
);
// Return initial data as JSON
echo json_encode(array("budget" => $_SESSION['budget'], "products" => $products));
?>