In this tutorial we will be building a simple Rock, Paper, Scissors game using the ViewBits Randomizer API. This game features different buttons for choosing a player move, and uses the random generator API to produce a random computer move.
You will learn the basics of how to make an API call using different variables and displaying the result using simple HTML and JavaScript. We will also create a score counter to track wins, losses, and draws.
The API will do most of the heavy lifting, all we need to do is supply the user move and display the results. Lets get started:
1. HTML Structure
The first step in this project will be to create the game board, which will include the game title, the control buttons, the results display, and a score counter.
HTML
<div class="game-container">
<h1>Rock Paper Scissors</h1>
<button class="button rock" id="rockBtn">Rock</button>
<button class="button paper" id="paperBtn">Paper</button>
<button class="button scissors" id="scissorsBtn">Scissors</button>
<div class="result" id="result"></div>
<div class="score" id="score">Wins: 0 | Losses: 0 | Draws: 0</div>
</div>
2. CSS Styles
Next, we will add some CSS to give the game board some style. We will use flex box to center the game board on the screen and add some colors to the control buttons.
CSS
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
.game-container {
text-align: center;
background: white;
border-radius: 8px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
padding: 20px;
width: 90%;
max-width: 400px;
}
.button {
padding: 10px 20px;
margin: 10px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
}
.rock { background-color: #f44336; color: white; }
.paper { background-color: #3f51b5; color: white; }
.scissors { background-color: #4caf50; color: white; }
.result {
margin-top: 20px;
font-size: 24px;
font-weight: bold;
}
.score {
margin-top: 10px;
font-size: 18px;
}
3. JavaScript
Now we will add the game functionality using Javascript. This game works by leveraging the ViewBits Randomizer API, which handles all of the decision logic on the backend.
All we need to do is supply the user move (R, P, or S) with our call, and the API will compare the user move to the CPU generated move and provide a result.
i. Track scores and Button Events
We will be tracking the game scores using the variables wins, losses, and draws. We will also add event listeners for each button and will pass the variable r, p, or s to the Play Function.
JavaScript
// Create variables to track scores
let wins = 0;
let losses = 0;
let draws = 0;
// Add event for each control button
document.getElementById('rockBtn').addEventListener('click',() => {play('r')});
document.getElementById('paperBtn').addEventListener('click',() => {play('p')});
document.getElementById('scissorsBtn').addEventListener('click',() => {play('s')});
ii. Play Function
The play function sends the user selected move to the API and handles the response. It also disables the control buttons to prevent additional moves from being made while the game is in progress.
Important: To avoid CORS limitations in JavaScript, you must either include an API key with your call or use a CURL function on the backend. Learn how to protect your API key and create your own ViewBits API wrapper using this guide.
JavaScript
async function play(userMove)
{
// Disable buttons to prevent further moves
toggleButtons(false);
// Call the ViewBits API
// Use backend wrapper on your site to hide API key (see docs)
// const response = await fetch(`api.viewbits.php?dataset=randomizer&mode=rps&move=${userMove}`);
// Direct API call (for testing only)
const apiKey = 'YOUR_KEY';
const response = await fetch(`https://api.viewbits.com/v1/randomizer/?mode=rps&move=${userMove}&key=${apiKey}`);
const data = await response.json();
// Run additional game functions
displayResult(data);
updateScore(data.result);
resetGame();
}
iii. Display Result Function
This function takes the API data, creates the feedback text, and places it in the DOM. This function can be expanded to show images or other visual cues.
JavaScript
function displayResult(data)
{
const resultElement = document.getElementById('result');
resultElement.textContent = `You chose ${data.userMove}, Computer chose ${data.compMove}. ${data.result}`;
}
iv. Update Score Function
This function takes the API data and increments the score counter based on whether the game resulted in a win, loss, or draw. The scores are then updated in the DOM.
JavaScript
function updateScore(result)
{
if(result === "You win!"){ wins++;}
else if(result === "Computer wins!"){ losses++; }
else{ draws++; }
document.getElementById('score').textContent = `Wins: ${wins} | Losses: ${losses} | Draws: ${draws}`;
}
v. Reset Game
The reset game function clears the feedback text and enables the control buttons to allow a move to be made for the next round.
JavaScript
function resetGame()
{
setTimeout(() =>
{
document.getElementById('result').textContent = ''; // Clear the result text
toggleButtons(true); // Re-enable buttons after the timer
}, 2000);
}
vi. Toggle Buttons
This function will temporarily disable the control buttons while a game is in progress to prevent additional API calls. It works by scanning the page for any control buttons and disables or enables them based on the parameter. We will also change the button style to add visual feedback.
JavaScript
function toggleButtons(enable)
{
const buttons = document.querySelectorAll('.button');
buttons.forEach(button =>
{
button.disabled = !enable; // Disable or enable based on the parameter
button.style.opacity = enable ? '1' : '0.5'; // Change opacity for visual feedback
});
}
4. Completed Game
That’s it! With this combination of HTML, CSS, and Javascript, you should now be able to play Rock, Paper, Scissors. The complete code example is included below:
Rock Paper Scissors Game Example
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
.game-container {
text-align: center;
background: white;
border-radius: 8px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
padding: 20px;
width: 90%;
max-width: 400px;
}
.button {
padding: 10px 20px;
margin: 10px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
}
.rock { background-color: #f44336; color: white; }
.paper { background-color: #3f51b5; color: white; }
.scissors { background-color: #4caf50; color: white; }
.result {
margin-top: 20px;
font-size: 24px;
font-weight: bold;
}
.score {
margin-top: 10px;
font-size: 18px;
}
</style>
<div class="game-container">
<h1>Rock Paper Scissors</h1>
<button class="button rock" id="rockBtn">Rock</button>
<button class="button paper" id="paperBtn">Paper</button>
<button class="button scissors" id="scissorsBtn">Scissors</button>
<div class="result" id="result"></div>
<div class="score" id="score">Wins: 0 | Losses: 0 | Draws: 0</div>
</div>
<script type="text/javascript">
// Create variables to track scores
let wins = 0;
let losses = 0;
let draws = 0;
// Add event for each control button
document.getElementById('rockBtn').addEventListener('click',() => {play('r')});
document.getElementById('paperBtn').addEventListener('click',() => {play('p')});
document.getElementById('scissorsBtn').addEventListener('click',() => {play('s')});
// The main API call function
// Sends user move and displays the API result
async function play(userMove)
{
// Disable buttons to prevent further moves
toggleButtons(false);
// Call the ViewBits API
// Use backend wrapper on your site to hide API key (see docs)
// const response = await fetch(`api.viewbits.php?dataset=randomizer&mode=rps&move=${userMove}`);
// Direct API call (for testing only)
const apiKey = 'YOUR_KEY';
const response = await fetch(`https://api.viewbits.com/v1/randomizer/?mode=rps&move=${userMove}&key=${apiKey}`);
const data = await response.json();
// Run additional game functions
displayResult(data);
updateScore(data.result);
resetGame();
}
// Display the round result on the game board
function displayResult(data)
{
const resultElement = document.getElementById('result');
resultElement.textContent = `You chose ${data.userMove}, Computer chose ${data.compMove}. ${data.result}`;
}
function updateScore(result)
{
if(result === "You win!"){ wins++;}
else if(result === "Computer wins!"){ losses++; }
else{ draws++; }
document.getElementById('score').textContent = `Wins: ${wins} | Losses: ${losses} | Draws: ${draws}`;
}
function resetGame()
{
setTimeout(() =>
{
document.getElementById('result').textContent = ''; // Clear the result text
toggleButtons(true); // Re-enable buttons after the timer
}, 2000);
}
function toggleButtons(enable)
{
const buttons = document.querySelectorAll('.button');
buttons.forEach(button =>
{
button.disabled = !enable; // Disable or enable based on the parameter
button.style.opacity = enable ? '1' : '0.5'; // Change opacity for visual feedback
});
}
</script>
5. Live Example
You can view a live working example of the game here: https://api.viewbits.com/examples/rock-paper-scissors-game.html