folder names

This commit is contained in:
Jen Looper
2020-11-09 22:51:04 -05:00
parent 33e5d5f777
commit 1d81829ac1
367 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
*Complete this quiz after the lesson by checking one answer per question.*
1. You can perform drawing operations directly on the Canvas
- [ ] true
- [ ] false
2. You listen to the `onload` event to know when an image has loaded asynchronously
- [ ] true
- [ ] false
3. You draw images onto a screen with an operation called
- [ ] paintImage()
- [ ] drawImage()
- [ ] draw()

View File

@@ -0,0 +1,18 @@
*A warm-up quiz about game development*
Complete this quiz in class
1. The Canvas element is what you use to draw on a screen
- [ ] true
- [ ] false
2. You can only draw simple geometric shapes
- [ ] true
- [ ] false
3. The point 0,0 is in the bottom left
- [ ] true
- [ ] false

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 WebDev-For-Beginners
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,212 @@
# Build a Space Game Part II: Draw Hero and Monsters to Canvas
## [Pre-lecture quiz](.github/pre-lecture-quiz.md)
## The Canvas
The canvas is an HTML element that by default has no content; it's a blank slate. You need to add to it by drawing on it.
✅ Read [more about the Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) on MDN.
Here's how it's typically declared, as part of the page's body:
```html
<canvas id="myCanvas" width="200" height="100"></canvas>
```
Above we are setting the `id`, `width` and `height`.
- `id`: set this so you can obtain a reference when you need to interact with it.
- `width`: this is the width of the element.
- `height`: this is the height of the element.
## Drawing simple geometry
The Canvas is using a cartesian coordinate system to draw things. Thus it uses an x-axis and y-axis to express where something is located. The location `0,0` is the top left position and the bottom right is what you said to be the WIDTH and HEIGHT of the canvas.
![the canvas's grid](canvas_grid.png)
> Image from [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes)
To draw on the canvas element you will need to go through the following steps:
1. **Get a reference** to the Canvas element.
1. **Get a reference** on the Context element that sits on the canvas element.
1. **Perform a drawing operation** using the context element.
Code for the above steps usually looks like so:
```javascript
// draws a red rectangle
//1. get the canvas reference
canvas = document.getElementById("myCanvas");
//2. set the context to 2D to draw basic shapes
ctx = canvas.getContext("2d");
//3. fill it with the color red
ctx.fillStyle = 'red';
//4. and draw a rectangle with these parameters, setting location and size
ctx.fillRect(0,0, 200, 200) // x,y,width, height
```
✅ The Canvas API mostly focuses on 2D shapes, but you can also draw 3D elements to a web site; for this, you might use the [WebGL API](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API).
You can draw all sorts of things with the Canvas API like:
- **Geometrical shapes**, we've already showed how to draw a rectangle, but there is much more you can draw.
- **Text**, you can draw a text with any font and color you wish.
- **Images**, you can draw an image based off of an image asset like a .jpg or .png for example.
✅ Try it! You know how to draw a rectangle, can you draw a circle to a page? Take a look at some interesting Canvas drawings on CodePen. Here's a [particularly impressive example](https://codepen.io/dissimulate/pen/KrAwx).
## Load and draw an image asset
You load an image asset by creating an `Image` object and set its `src` property. Then you listen to the `load` event to know when it's ready to be used. The code looks like this:
### Load asset
```javascript
const img = new Image();
img.src = 'path/to/my/image.png';
img.onload = () => {
// image loaded and ready to be used
}
```
### Load asset pattern
It's recommended to wrap the above in a construct like so, so it's easier to use and you only try to manipulate it when it's fully loaded:
```javascript
async function loadAsset(path) {
return new Promise((resolve) => {
const img = new Image();
img.src = path;
img.onload = () => {
// image loaded and ready to be used
}
resolve(img);
})
}
// use like so
async function run() {
const heroImg = await loadAsset('hero.png')
const monsterImg = await loadAsset('monster.png')
}
```
To draw game assets to a screen, your code would look like this:
```javascript
async function run() {
const heroImg = await loadAsset('hero.png')
const monsterImg = await loadAsset('monster.png')
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
ctx.drawImage(heroImg, canvas.width/2,canvas.height/2);
ctx.drawImage(monsterImg, 0,0);
}
```
## Now it's time to start building your game
### What to build
You will build a web page with a Canvas element. It should render a black screen `1024*768`. We've provided you with two images:
- Hero ship
![Hero ship](solution/assets/player.png)
- 5*5 monster
![Monster ship](solution/assets/enemyShip.png)
### Recommended steps to start development
Locate the files that have been created for you in the `your-work` sub folder. It should contain the following:
```bash
-| assets
-| enemyShip.png
-| player.png
-| index.html
-| app.js
-| package.json
```
Open the copy of this folder in Visual Studio Code. You need to have a local development environment setup, preferably with Visual Studio Code with NPM and Node installed. If you don't have `npm` set up on your computer, [here's how to do that](https://www.npmjs.com/get-npm).
Start your project by navigating to the `your_work` folder:
```bash
cd your-work
npm start
```
The above will start a HTTP Server on address `http://localhost:5000`. Open up a browser and input that address. It's a blank page right now, but that will change
> Note: to see changes on your screen, refresh your browser.
### Add code
Add the needed code to `your-work/app.js` to solve the below
1. **Draw** a canvas with black background
> tip: add two lines under the appropriate TODO in `/app.js`, setting the `ctx` element to be black and the top/left coordinates to be at 0,0 and the height and width to equal that of the canvas.
2. **Load** textures
> tip: add the player and enemy images using `await loadTexture` and passing in the image path. You won't see them on the screen yet!
3. **Draw** hero in the center of the screen in the bottom half
> tip: use the `drawImage` API to draw heroImg to the screen, setting `canvas.width / 2 - 45` and `canvas.height - canvas.height / 4)`;
4. **Draw** 5*5 monsters
> tip: Now you can uncomment the code to draw enemies on the screen. Next, go to the `createEnemies` function and build it out.
First, set up some constants:
```javascript
const MONSTER_TOTAL = 5;
const MONSTER_WIDTH = MONSTER_TOTAL * 98;
const START_X = (canvas.width - MONSTER_WIDTH) / 2;
const STOP_X = START_X + MONSTER_WIDTH;
```
then, create a loop to draw the array of monsters onto the screen:
```javascript
for (let x = START_X; x < STOP_X; x += 98) {
for (let y = 0; y < 50 * 5; y += 50) {
ctx.drawImage(enemyImg, x, y);
}
}
```
## Result
The finished result should look like so:
![Black screen with a hero and 5*5 monsters](partI-solution.png)
## Solution
Please try solving it yourself first but if you get stuck, have a look at a [solution](solution/app.js)
---
## 🚀 Challenge
You've learned about drawing with the 2D-focused Canvas API; take a look at the [WebGL API](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API), and try to draw a 3D object.
## [Post-lecture quiz](.github/post-lecture-quiz.md)
## Review & Self Study
Learn more about the Canvas API by [reading about it](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API).
## Assignment
[Play with the Canvas API](assignment.md)

View File

@@ -0,0 +1,11 @@
# Play with the Canvas API
## Instructions
Pick one element of the Canvas API and create something interesting around it. Can you create a little galaxy of repeated stars? Can you create an interesting texture of colored lines? You can look at CodePen for inspiration (but don't copy)
## Rubric
| Criteria | Exemplary | Adequate | Needs Improvement |
| -------- | --------------------------------------------------------- | ----------------------------------- | --------------------- |
| | Code is submitted showing an interesting texture or shape | Code is submitted, but does not run | Code is not submitted |

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 357 KiB

View File

@@ -0,0 +1,34 @@
function loadTexture(path) {
return new Promise((resolve) => {
const img = new Image();
img.src = path;
img.onload = () => {
resolve(img);
}
})
}
function createEnemies(ctx, canvas, enemyImg) {
const MONSTER_TOTAL = 5;
const MONSTER_WIDTH = MONSTER_TOTAL * 98;
const START_X = (canvas.width - MONSTER_WIDTH) / 2;
const STOP_X = START_X + MONSTER_WIDTH;
for (let x = START_X; x < STOP_X; x += 98) {
for (let y = 0; y < 50 * 5; y += 50) {
ctx.drawImage(enemyImg, x, y);
}
}
}
window.onload = async() => {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
const heroImg = await loadTexture('assets/player.png')
const enemyImg = await loadTexture('assets/enemyShip.png')
ctx.fillStyle = 'black';
ctx.fillRect(0,0, canvas.width, canvas.height);
ctx.drawImage(heroImg, canvas.width/2 - 45, canvas.height - (canvas.height /4));
createEnemies(ctx, canvas, enemyImg);
};

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

View File

@@ -0,0 +1,6 @@
<html>
<body>
<canvas id ="canvas" width="1024" height="768"></canvas>
<script src="app.js"></script>
</body>
</html>

View File

@@ -0,0 +1,13 @@
{
"name": "solution",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "npx http-server -c-1 -p 5000",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}

View File

@@ -0,0 +1,212 @@
# Construye un juego espacial Parte II: Dibuja héroes y monstruos en el lienzo
![video](video-url)
## [Pre-lecture prueba](.github/pre-lecture-quiz.md)
## El lienzo
El lienzo es un elemento HTML que por defecto no tiene contenido; es una pizarra en blanco. Necesita agregarle dibujo sobre él.
✅ Lea [más sobre la API Canvas](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) en MDN.
Así es como se declara normalmente, como parte del cuerpo de la página:
```html
<canvas id="myCanvas" width="200" height="100"></canvas>
```
Arriba estamos configurando el `id`, `width` y `alto`.
- `id`: establezca esto para que pueda obtener una referencia cuando necesite interactuar con él.
- `width`: este es el ancho del elemento.
- `height`: esta es la altura del elemento.
## Dibujar geometría simple
Canvas utiliza un sistema de coordenadas cartesiano para dibujar cosas. Por lo tanto, usa un eje xy un eje y para expresar dónde se encuentra algo. La ubicación `0,0` es la posición superior izquierda y la inferior derecha es lo que dijiste que era el ANCHO y ALTO del lienzo.
! [cuadrícula del lienzo](canvas_grid.png)
> Imagen de [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes)
Para dibujar en el elemento de lienzo, deberá seguir los siguientes pasos:
1. **Obtenga una referencia** al elemento Canvas.
1. **Obtenga una referencia** en el elemento Context que se encuentra en el elemento canvas.
1. **Realice una operación de dibujo** utilizando el elemento de contexto.
El código para los pasos anteriores generalmente se ve así:
```javascript
// dibuja un rectángulo rojo
// 1. obtener la referencia del lienzo
canvas = document.getElementById("myCanvas");
// 2. establecer el contexto en 2D para dibujar formas básicas
ctx = canvas.getContext("2d");
// 3. rellénalo con el color rojo
ctx.fillStyle = 'red';
// 4. y dibuja un rectángulo con estos parámetros, configurando la ubicación y el tamaño
ctx.fillRect(0,0, 200, 200) // x, y, ancho, alto
```
✅ La API de Canvas se enfoca principalmente en formas 2D, pero también puede dibujar elementos 3D en un sitio web; para esto, puede usar la [API WebGL](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API).
Puede dibujar todo tipo de cosas con la API de Canvas como:
- **Formas geométricas**, ya mostramos cómo dibujar un rectángulo, pero hay mucho más que puedes dibujar.
- **Texto**, puede dibujar un texto con cualquier fuente y color que desee.
- **Imágenes**, puede dibujar una imagen basada en un activo de imagen como .jpg o .png, por ejemplo.
✅ ¡Pruébalo! Sabes cómo dibujar un rectángulo, ¿puedes dibujar un círculo en una página? Eche un vistazo a algunos dibujos de Canvas interesantes en CodePen. Aquí hay un [ejemplo particularmente impresionante] (https://codepen.io/dissimulate/pen/KrAwx).
## Cargar y dibujar un recurso de imagen
Usted carga un activo de imagen creando un objeto `Image` y estableciendo su propiedad `src`. Luego escuchas el evento `load` para saber cuándo está listo para usarse. El código se ve así:
### Cargar activo
```javascript
const img = new Image();
img.src = 'path/to/my/image.png';
img.onload = () => {
// image loaded and ready to be used
}
```
### Cargar patrón de activos
Se recomienda envolver lo anterior en una construcción así, para que sea más fácil de usar y solo intente manipularlo cuando esté completamente cargado:
```javascript
async function loadAsset(path) {
return new Promise((resolve) => {
const img = new Image();
img.src = path;
img.onload = () => {
// imagen cargada y lista para ser utilizada
}
resolve(img);
})
}
// usar así
async function run() {
const heroImg = await loadAsset('hero.png')
const monsterImg = await loadAsset('monster.png')
}
```
Para dibujar activos del juego en una pantalla, su código se vería así:
```javascript
async function run() {
const heroImg = await loadAsset('hero.png')
const monsterImg = await loadAsset('monster.png')
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
ctx.drawImage(heroImg, canvas.width/2,canvas.height/2);
ctx.drawImage(monsterImg, 0,0);
}
```
### Qué construir
Construirá una página web con un elemento Canvas. Debería representar una pantalla negra `1024*768`. Le proporcionamos dos imágenes:
- Barco héroe
![Barco héroe](solution/assets/player.png)
- Monstruo 5*5
![Monster ship](solution/assets/enemyShip.png)
### Pasos recomendados para iniciar el desarrollo
Busque los archivos que se han creado para usted en la subcarpeta `your-work`. Debe contener lo siguiente:
```bash
-| assets
-| enemyShip.png
-| player.png
-| index.html
-| app.js
-| package.json
```
Abra la copia de esta carpeta en Visual Studio Code. Debe tener una configuración de entorno de desarrollo local, preferiblemente con Visual Studio Code con NPM y Node instalados. Si no tiene `npm` configurado en su computadora, [aquí le explicamos cómo hacerlo](https://www.npmjs.com/get-npm).
Inicie su proyecto navegando a la carpeta `your_work`:
```bash
cd your-work
npm start
```
Lo anterior iniciará un servidor HTTP en la dirección `http: // localhost: 5000`. Abra un navegador e ingrese esa dirección. Es una página en blanco ahora mismo, pero eso cambiará
> Nota: para ver los cambios en su pantalla, actualice su navegador.
### Agregar código
Agregue el código necesario a `your-work/app.js` para resolver lo siguiente
1. **Dibuja** un lienzo con fondo negro
> consejo: agregue dos líneas debajo del TODO apropiado en `/app.js`, estableciendo el elemento `ctx` en negro y las coordenadas superior / izquierda en 0,0 y la altura y el ancho para que sean iguales a los del lienzo .
2. **Cargar** texturas
> consejo: agregue las imágenes del jugador y del enemigo usando `await loadTexture` y pasando la ruta de la imagen. ¡Todavía no los verá en la pantalla!
3. **Dibuja** héroe en el centro de la pantalla en la mitad inferior
> consejo: use la API `drawImage` para dibujar heroImg en la pantalla, configurando `canvas.width / 2 - 45` y `canvas.height - canvas.height / 4)`;
4. **Dibujar** 5 * 5 monstruos
> consejo: ahora puedes descomentar el código para dibujar enemigos en la pantalla. A continuación, vaya a la función `createEnemies` y constrúyala.
Primero, configure algunas constantes:
```javascript
const MONSTER_TOTAL = 5;
const MONSTER_WIDTH = MONSTER_TOTAL * 98;
const START_X = (canvas.width - MONSTER_WIDTH) / 2;
const STOP_X = START_X + MONSTER_WIDTH;
```
luego, crea un bucle para dibujar la matriz de monstruos en la pantalla:
```javascript
for (let x = START_X; x < STOP_X; x += 98) {
for (let y = 0; y < 50 * 5; y += 50) {
ctx.drawImage(enemyImg, x, y);
}
}
```
## Resultado
El resultado final debería verse así:
![Pantalla negra con un héroe y monstruos 5*5](partI-solution.png)
## Solución
Intente resolverlo usted mismo primero, pero si se atasca, eche un vistazo a una [solución](solution/app.js)
🚀 Desafío: ha aprendido a dibujar con la API Canvas enfocada en 2D; eche un vistazo a la [API WebGL](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API) e intente dibujar un objeto 3D.
## [Post-lecture prueba](.github/post-lecture-quiz.md)
## Revisión y autoestudio
Obtenga más información sobre la API de Canvas [leyendo sobre ella](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API).
**Tarea**: [Jugar con la API de Canvas](assignment.md)

View File

@@ -0,0 +1,11 @@
Juega con la API Canvas
## Instrucciones
Elija un elemento de la API de Canvas y cree algo interesante a su alrededor. ¿Puedes crear una pequeña galaxia de estrellas repetidas? ¿Puedes crear una textura interesante de líneas de colores? Puede buscar inspiración en CodePen (pero no copiar)
## Rúbrica
| Criterios | Ejemplar | Adecuado | Necesita mejorar |
| -------- | -------------------------------------------------- ------- | ----------------------------------- | --------------------- |
| | El código se envía mostrando una textura o forma interesante | Se envía el código, pero no se ejecuta | No se envía el código |

View File

@@ -0,0 +1,24 @@
function loadTexture(path) {
return new Promise((resolve) => {
const img = new Image();
img.src = path;
img.onload = () => {
resolve(img);
};
});
}
function createEnemies(ctx, canvas, enemyImg) {
// TODO draw enemies
}
window.onload = async () => {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
// TODO load textures
// TODO draw black background
// TODO draw hero
// TODO uncomment the next line when you add enemies to screen
//createEnemies(ctx, canvas, enemyImg);
};

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

View File

@@ -0,0 +1,6 @@
<html>
<body>
<canvas id ="canvas" width="1024" height="768"></canvas>
<script src="app.js"></script>
</body>
</html>

View File

@@ -0,0 +1,13 @@
{
"name": "solution",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "npx http-server -c-1 -p 5000",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}