Home / Widgets / game_start
Duplicate Snippet

Embed Snippet on Your Site

game_start

Code Preview
html
<div id="gameState">
	<p>Round: <span id="round">1</span>/5</p>
	<p>Cash: $<span id="cash">5000</span></p>
	<p>Automobile Production: <span id="production">1000</span> units</p>
	<p>Industry Level: <span id="level">5</span></p>
</div>
	<button onclick="startGame()">Start New Game</button>
	<button onclick="saveGame()">Save Game</button>
	<button onclick="loadGame()">Load Game</button>
	<button onclick="restartGame()">Restart Game</button>
	<script>
	// Game state
	let gameData = {
	cash: 5000,
	level: 5,
	production: 1000,
	round: 1,
	};
	const apiUrl = '/wp-json/wp/v2/game_state';
    // Update the display
	function updateDisplay() {
	document.getElementById('round').textContent = gameData.round;
	document.getElementById('cash').textContent = gameData.cash;
	document.getElementById('production').textContent = gameData.production;
	document.getElementById('level').textContent = gameData.level;
	}
    // Start a new game
	function startGame() {
	gameData = {
	cash: 5000,
	level: 5,
	production: 1000,
	round: 1,
	};
	updateDisplay();
	alert('New game started!');
	}
    // Save the game
	async function saveGame() {
	const response = await fetch(apiUrl, {
	method: 'POST',
	headers: {
	'Content-Type': 'application/json',
	'X-WP-Nonce': '<?php echo wp_create_nonce('wp_rest'); ?>', // Add nonce for authentication
	},
	body: JSON.stringify({
	title: 'Game State',
	status: 'publish',
	fields: gameData,
	}),
	});
	const data = await response.json();
	alert('Game saved!');
	}
    // Load the game
	async function loadGame() {
	const response = await fetch(apiUrl);
	const data = await response.json();
	if (data.length > 0) {
	const latestGame = data[0];
	gameData = {
	cash: latestGame.acf.cash,
	level: latestGame.acf.level,
	production: latestGame.acf.production,
	round: latestGame.acf.round,
	};
	updateDisplay();
	alert('Game loaded!');
	} else {
	alert('No saved game found.');
	}
	}
    // Restart the game
	function restartGame() {
	startGame();
	alert('Game restarted!');
	}
    // Initialize the display
	updateDisplay();
  </script>

Comments

Add a Comment