MetaData, Class, For Loops
The objective of this article is to enhance your knowledge and understanding of MetaData, Class Definitions, and For-Loops.
MetaData: In this article, MetaData contains information about the sprite, including its name, source URL, and orientation details such as the number of rows and columns, header size, padding, and jagged rows.
Class: In this context, the canvas and drawing operations are initialized and stored in a class. These are used to output the sprite sheet image and individual frames within the sprite sheet.
- constructor: Initializes the canvas, context, and sprite image.
- draw() method: Uses nested for-loops to iterate through the sprite sheet and draw each frame independently on the canvas. It calculates the source and destination coordinates for each frame, taking into account the header and padding.
Introduction to For Loops
For Loops are commonly used to iterate over data structures, including JavaScript Arrays and Objects.
Below is an example of a conventional for loop that iterates over an array of names and displays each name in a paragraph (<p>
) tag within a designated HTML div.
%%html
<!-- HTML output div -->
<div id="forConventional"></div>
<script>
var names = ['turtle', 'fish', 'frog', 'penguin'];
// Conventional for loop with index used to access elements
for (let i = 0; i < names.length; i++) {
// Create a p tag for each name and add it to the forConventional div
const p = document.createElement('p');
p.innerHTML = names[i];
document.getElementById('forConventional').appendChild(p);
}
</script>
ForEach Loop
The ForEach loop is another way to iterate over data structures, such as JavaScript Arrays and Objects. Below is an example of a ForEach loop that iterates over an array of coding adventures and displays each adventure in a paragraph (<p>
) tag within a designated HTML div.
%%html
<!-- HTML output div -->
<div id="forEach"></div>
<script>
var codingAdventures = ['GitHub', 'Terminal', 'Jupyter', 'JavaScript'];
// ForEach loop to iterate over the array
for (let adventure of codingAdventures) {
// Create a p tag for each adventure and add it to the forEach div
const p = document.createElement('p');
p.innerHTML = adventure;
document.getElementById('forEach').appendChild(p);
}
</script>
2D array
There is a data structure called arrays in arrays or 2D arrays. The data structure helps organize the data efficiently and access it using nested loops. Each row in the 2D array will represent a category (e.g., GitHub, Terminal), and each column will contain an array of questions and answers for that category.
%%html
<div id="questionsAnswers"></div>
<script>
// 2D array of questions and answers with titles
var qaArray = [
[
'GitHub',
[
{ question: 'What is a repository?', answer: 'A repository is a storage space where your project lives.' },
{ question: 'How do you create a branch?', answer: 'You can create a branch by using the command git checkout -b branchName.' },
{ question: 'How do you merge branches?', answer: 'You can merge branches by using the command git merge branchName.' },
{ question: 'How do you push changes to GitHub?', answer: 'You can push changes to GitHub by using the command git push origin branchName.' }
]
],
[
'Terminal',
[
{ question: 'What is the command to list hidden files in a directory?', answer: 'The command to list files in a directory is ls -a.' },
{ question: 'What is the command to change directories?', answer: 'The command to change directories is cd.' },
{ question: 'What is the command to create a new directory?', answer: 'The command to create a new directory is mkdir.' },
{ question: 'What is the command to remove a directory?', answer: 'The command to remove a directory is rm -rf.' }
]
],
[
'Jupyter Notebook',
[
{ question: 'How do you setup a markdown cell?', answer: 'You setup a markdown cell by selecting the cell type dropdown and selecting markdown.' },
{ question: 'How do you setup a code cell?', answer: 'You setup a code cell by selecting the cell type dropdown and selecting code.' },
{ question: 'What kernel do you select to run JavaScript code?', answer: 'You select the Python kernel to run JavaScript code.' },
{ question: 'How do you see JavaScript console output?', answer: 'You see JavaScript console output by using the console.log() method.' }
]
],
[
'JavaScript',
[
{ question: 'What is JavaScript?', answer: 'JavaScript is a programming language that enables you to create interactive web pages.' },
{ question: 'What is a variable?', answer: 'A variable is a container that stores data.' },
{ question: 'What is a function?', answer: 'A function is a block of code that performs a specific task.' },
{ question: 'What is a loop?', answer: 'A loop is a programming structure that repeats a sequence of instructions.' }
]
]
];
// Nested for loops to display questions and answers with titles
for (let category of qaArray) {
// Create an h2 tag for each category title
const h2 = document.createElement('h2');
h2.innerHTML = category[0]; // index 0 is the title of the category
document.getElementById('questionsAnswers').appendChild(h2);
// Iterate through each question and answer in the category
for (let qa of category[1]) { // index 1 is the array of questions and answers
// Create a p tag for each question and answer
const p = document.createElement('p');
p.innerHTML = `<strong>Q:</strong> ${qa.question} <br> <strong>A:</strong> ${qa.answer}`;
document.getElementById('questionsAnswers').appendChild(p);
}
}
</script>
-
GitHub
- Q: What is a repository?
A: A repository is a storage space where your project lives. - Q: How do you create a branch?
A: You can create a branch by using the commandgit checkout -b branchName
. - Q: How do you merge branches?
A: You can merge branches by using the commandgit merge branchName
. - Q: How do you push changes to GitHub?
A: You can push changes to GitHub by using the commandgit push origin branchName
.
- Q: What is a repository?
-
Terminal
- Q: What is the command to list hidden files in a directory?
A: The command to list files in a directory isls -a
. - Q: What is the command to change directories?
A: The command to change directories iscd
. - Q: What is the command to create a new directory?
A: The command to create a new directory ismkdir
. - Q: What is the command to remove a directory?
A: The command to remove a directory isrm -rf
.
- Q: What is the command to list hidden files in a directory?
-
Jupyter Notebook
- Q: How do you set up a markdown cell?
A: You set up a markdown cell by selecting the cell type dropdown and selecting markdown. - Q: How do you set up a code cell?
A: You set up a code cell by selecting the cell type dropdown and selecting code. - Q: What kernel do you select to run JavaScript code?
A: You select the Python kernel to run JavaScript code. - Q: How do you see JavaScript console output?
A: You see JavaScript console output by using theconsole.log()
method.
- Q: How do you set up a markdown cell?
-
JavaScript
- Q: What is JavaScript?
A: JavaScript is a programming language that enables you to create interactive web pages. - Q: What is a variable?
A: A variable is a container that stores data. - Q: What is a function?
A: A function is a block of code that performs a specific task. - Q: What is a loop?
A: A loop is a programming structure that repeats a sequence of instructions.
- Q: What is JavaScript?
Hack #1: Apply Your Own Game Idea
Create new code cells to implement some of the sprite interactions or features you have ideated for your game. This exercise is crucial if you plan to have interactions with a Non-Player Character (NPC).
Challenge: Use the concepts of 2D arrays and nested loops to create and display interactions or features for your game. Think about how you can organize and manage different elements, such as NPC dialog, questions, and receiving answers.
Sprite Files
Transition to Sprite Files
Now that we have a solid understanding of data structures and loops, we will transition to working with Sprite Files. This section will help you understand how to manage and display sprite images, which are essential for creating animations in your game.
Sprite Files
Sprite files are essentially a 2D table of sprite images. They contain 2D columnar sequences of pictures that aid in creating animation.
Display Sprite File
The next code block shows a sprite file. This can be helpful in understanding the properties of your sprite. It contains console.log
output that shows the sprite properties.
Here are some terms that you will see in the next code block:
- MetaData: Data that describes the file
- name: A friendly identifier naming the file
- src: The location of the file
- drawImage: A function call that, when used with five parameters, outputs the entirety of the file
- class: A coding structure that contains a constructor, data, and method (draw) to read and output a file
%%html
<style>
#gameCanvas {
border: 4px solid rgb(102, 4, 4); /* Red border for the canvas */
}
</style>
<canvas id="gameCanvas" width="521" height="967"></canvas>
<script>
function defineAndDrawImage() {
/**
* Function to define the sprite metadata for Tux the penguin
* @returns {Object} spriteMetaData - The metadata for the Tux sprite
*/
function TuxSpriteMetaData() {
// NPC sprite data (Tux the penguin)
const spriteMetaData = {
name: 'tux',
src: "./tux.png",
};
return spriteMetaData;
}
/**
* Class to handle the canvas data and drawing of the image file
*/
class CanvasDrawImage {
constructor(spriteMetaData) {
this.INIT_POSITION = { x: 0, y: 0 };
this.spriteMetaData = spriteMetaData;
this.canvas = document.getElementById('gameCanvas');
this.ctx = this.canvas.getContext('2d');
this.spriteImage = new Image();
this.spriteImage.src = spriteMetaData.src;
this.spriteImage.onload = () => this.draw(); // Ensure draw is called after image is loaded
}
// Method to draw the sprite on the canvas
draw() {
// This is the size of the sprite file, calculated from the PNG file
const width = this.spriteImage.width;
const height = this.spriteImage.height;
console.log(`Drawing sprite: ${this.spriteMetaData.name}`);
console.log(`Sprite Dimensions: ${width}x${height}`);
this.ctx.drawImage(this.spriteImage, 0, 0, width, height);
}
}
const tux = new CanvasDrawImage(TuxSpriteMetaData());
}
// Call the function to define the class and draw the sprite
defineAndDrawImage();
</script>
Display Frames in Sprite File
The next code block contains logic to extract frames within the sprite sheet. This is a more practical game enhancement compared to the previous example.
Here are terms to describe key elements in the code:
- MetaData: Contains information about the sprite file, including its name, source URL, and orientation details.
- orientation: Describes the layout of the sprite in the PNG file.
- header: Size of the area of description above the sprite.
- pad: Size of the area between the sprites.
- jagged: Indicates that each row can contain a different number of sprites.
- orientation: Describes the layout of the sprite in the PNG file.
- drawImage: In the 9-property format, it provides the ability to scale the source into the destination.
- class: Continues using the constructor and draw methods for source and output; adds math to abstract each frame independently.
- for-loops: Demonstrates nested for loops to process each frame within the 2D sprite sheet.
%%html
<style>
#gameCanvasUnique {
border: 4px solid rgb(4, 102, 33); /* Green border for the canvas */
}
</style>
<canvas id="gameCanvasUnique" width="521" height="967"></canvas>
<script>
// Outer function is required by Jupyter Notebook to avoid conflicts
function defineAndDrawSprite() {
/**
* Function to define the sprite metadata for Tux the penguin
* @returns {Object} spriteMetaData - The metadata for the Tux sprite
*/
function TuxSpriteMetaData() {
// NPC sprite data (Tux the penguin)
const spriteMetaData = {
name: 'tux',
src: "./tux.png",
orientation: {
rows: 10,
columns: 8,
header: 16,
pad: 2,
jagged: [1, 2, 1, 1, 1, 1, 1, 7, 8, 4]
},
};
return spriteMetaData;
}
/**
* Class to handle the canvas data and drawing of the sprite
*/
class CanvasData {
constructor(spriteMetaData) {
this.spriteMetaData = spriteMetaData;
this.INIT_POSITION = { x: 0, y: 0 };
this.canvas = document.getElementById('gameCanvasUnique');
this.ctx = this.canvas.getContext('2d');
this.spriteImage = new Image();
this.spriteImage.src = spriteMetaData.src;
this.spriteImage.onload = () => this.draw(); // Ensure draw is called after image is loaded
}
// Method to draw each sprite individually
draw() {
// This is the size of the sprite file, calculated from the PNG file
const sheetWidth = this.spriteImage.width;
const sheetHeight = this.spriteImage.height;
// This meta data describes the sprite sheet
const rows = this.spriteMetaData.orientation.rows;
const cols = this.spriteMetaData.orientation.columns;
const jagged = this.spriteMetaData.orientation.jagged || null;
const header = this.spriteMetaData.orientation.header || 0;
const pad = this.spriteMetaData.orientation.pad || 0;
// This is the initial output position on the canvas
const x = this.INIT_POSITION.x;
const y = this.INIT_POSITION.y;
// Calculate the dimensions of each individual sprite
const spriteWidth = sheetWidth / cols;
const spriteHeight = (sheetHeight - header * rows) / rows;
console.log(`Sprite Sheet Dimensions: ${sheetWidth}x${sheetHeight}`);
console.log(`Individual Sprite Dimensions: ${spriteWidth}x${spriteHeight}`);
console.log(`Rows: ${rows}, Columns: ${cols}`);
// Nested for loop to draw 2-dimensional sprite sheet
for (let row = 0; row < rows; row++) {
const columnsInRow = jagged ? jagged[row] || cols : cols;
for (let col = 0; col < columnsInRow; col++) {
const srcX = col * spriteWidth;
const srcY = row * (spriteHeight + header) - (pad * row);
const destX = x + col * spriteWidth;
const destY = y + row * spriteHeight;
const destWidth = spriteWidth;
const destHeight = spriteHeight;
console.log(`Drawing row: ${row}, column: ${col}`);
console.log(`Source: (${srcX}, ${srcY}, ${spriteWidth}, ${spriteHeight})`);
console.log(`Destination: (${destX}, ${destY}, ${destWidth}, ${destHeight})`);
this.ctx.drawImage(
this.spriteImage,
srcX, srcY + header, spriteWidth, spriteHeight, // Source rectangle
destX, destY, destWidth, destHeight // Destination rectangle
);
}
}
}
}
// Setup to Tux sprite
const tux = new CanvasData(TuxSpriteMetaData());
}
defineAndDrawSprite();
</script>
Hack #2: Display Individual Sprites
Create new code cell(s) to display individual sprites from a sprite sheet. This sprite sheet will potentially be used in your game.
Challenge: Use the concepts of 2D arrays, nested loops, and sprite metadata to extract and display individual sprites. Think about how you can manage and display different frames or animations for your game characters or objects.
Hack #1 Work:
%%html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NPC Interaction</title>
</head>
<body>
<h1>NPC Interaction</h1>
<div id="npcDialog"></div>
<script>
// 2D array for NPC dialog and responses
var npcDialog = [
['NPC: Hello there, traveler!',
['1: Ask about the village.', '2: Ask about the quest.', '3: Say goodbye.']
],
['NPC: The village is peaceful but beware of the forest beyond.',
['1: Ask about the quest.', '2: Say goodbye.']
],
['NPC: There is a dragon that needs to be defeated. Brave enough?',
['1: Accept the quest.', '2: Decline and say goodbye.']
],
['NPC: Goodbye and good luck on your journey!', []]
];
// Function to display NPC dialog and options
function displayDialog(step) {
const dialogDiv = document.getElementById('npcDialog');
dialogDiv.innerHTML = ''; // Clear previous dialog
// Create a paragraph for the NPC dialog
const pDialog = document.createElement('p');
pDialog.innerHTML = npcDialog[step][0];
dialogDiv.appendChild(pDialog);
// Loop through and display the available responses
for (let i = 0; i < npcDialog[step][1].length; i++) {
const pResponse = document.createElement('p');
pResponse.innerHTML = npcDialog[step][1][i];
pResponse.style.cursor = 'pointer'; // Make it look clickable
// Add a click event listener for each response
pResponse.addEventListener('click', function() {
if (npcDialog[step][1][i].includes('goodbye')) {
alert('NPC: Farewell, brave traveler!');
} else if (npcDialog[step][1][i].includes('village')) {
displayDialog(1);
} else if (npcDialog[step][1][i].includes('quest')) {
displayDialog(2);
} else if (npcDialog[step][1][i].includes('Accept')) {
alert('NPC: May fortune favor you!');
displayDialog(3);
} else {
displayDialog(3);
}
});
dialogDiv.appendChild(pResponse);
}
}
// Start the dialog
displayDialog(0);
</script>
</body>
</html>
NPC Interaction
Hack #2 Work:
%%html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sprite Sheet Example</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<h1>Display Individual Sprites</h1>
<canvas id="spriteCanvas" width="300" height="300"></canvas>
<script>
// Load the sprite sheet image
const spriteSheet = new Image();
spriteSheet.src = 'your-sprite-sheet-url.png'; // Replace with your sprite sheet URL
const canvas = document.getElementById('spriteCanvas');
const context = canvas.getContext('2d');
// Define sprite properties
const spriteWidth = 64; // Width of each sprite frame
const spriteHeight = 64; // Height of each sprite frame
const spriteColumns = 4; // Number of columns in the sprite sheet
const spriteRows = 4; // Number of rows in the sprite sheet
// Select the sprite you want to display (row, column index)
let currentSpriteRow = 1; // Change to select different row
let currentSpriteCol = 2; // Change to select different column
// Function to display a sprite at a specific row and column
function displaySprite(row, col) {
// Clear the canvas
context.clearRect(0, 0, canvas.width, canvas.height);
// Calculate the x and y coordinates for the sprite in the sprite sheet
const sx = col * spriteWidth;
const sy = row * spriteHeight;
// Draw the sprite on the canvas (source coordinates, width, and height)
context.drawImage(spriteSheet, sx, sy, spriteWidth, spriteHeight, 0, 0, spriteWidth, spriteHeight);
}
// When the sprite sheet image loads, display the selected sprite
spriteSheet.onload = function() {
displaySprite(currentSpriteRow, currentSpriteCol);
};
</script>
</body>
</html>