Dylan  Iqbal

Dylan Iqbal


Build a Space Game: Draw Hero and Monsters to Canvas

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 on MDN.

Here's how it's typically declared, as part of the page's body:

<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

Image from MDN

To draw on the canvas element you will need to go through the following steps:

  1. Get a reference to the Canvas element.
  2. Get a reference on the Context element that sits on the canvas element.
  3. Perform a drawing operation using the context element.

Code for the above steps usually looks like so:

// 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.

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.

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

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:

function loadAsset(path) {
  return new Promise((resolve) => {
    const img = new Image();
    img.src = path;
    img.onload = () => {
      // image loaded and ready to be used

// 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:

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

5*5 monster

Monster ship

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:

-| 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.

Start your project by navigating to the your_work folder:

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

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.

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!

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);

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:

const MONSTER_TOTAL = 5;
const START_X = (canvas.width - MONSTER_WIDTH) / 2;

then, create a loop to draw the array of monsters onto the screen:

for (let x = START_X; x < STOP_X; x += 98) {
    for (let y = 0; y < 50 * 5; y += 50) {
      ctx.drawImage(enemyImg, x, y);


The finished result should look like so:

Black screen with a hero and 5*5 monsters


Please try solving it yourself first but if you get stuck, have a look at a solution


You've learned about drawing with the 2D-focused Canvas API; take a look at the WebGL API, and try to draw a 3D object.

Post-Lecture Quiz

Post-lecture quiz

Review & Self Study

Learn more about the Canvas API by reading about it.


Play with the Canvas API

Originally published at https://github.com/microsoft/Web-Dev-For-Beginners/blob/main/6-space-game/2-drawing-to-canvas/README.md 

#gamedev #html #canvas



What is GEEK

Buddha Community

Build a Space Game: Draw Hero and Monsters to Canvas
lakshya world

lakshya world


How to Create a Successful Gaming App?

How to create a game app is a comprehensive guide, explaining the entire process of creating and publishing games for iOS and Android. Covering all the essential information a budding game developer needs to know.


Read More - https://www.brsoftech.com/blog/how-to-create-a-game-app/


#game-engine  #game-development  #game  #games  #gaming 

Tamale  Moses

Tamale Moses


Playground Games and Turn 10 Studios respectively improved time on Visual Studio 2019

The C++ team at Visual Studio has delivered substantial build and link time improvements throughout Visual Studio 2019. This blog is Part 2 of a series of blogs showcasing real-world results of our efforts. See how the Gears 5 team benefited from iteration build time improvements in Part 1.

#c++ #performance #build throughput #build time #compile time #game development #games #gaming #iteration time #linker #video games

Dylan  Iqbal

Dylan Iqbal


Matplotlib Cheat Sheet: Plotting in Python

This Matplotlib cheat sheet introduces you to the basics that you need to plot your data with Python and includes code samples.

Data visualization and storytelling with your data are essential skills that every data scientist needs to communicate insights gained from analyses effectively to any audience out there. 

For most beginners, the first package that they use to get in touch with data visualization and storytelling is, naturally, Matplotlib: it is a Python 2D plotting library that enables users to make publication-quality figures. But, what might be even more convincing is the fact that other packages, such as Pandas, intend to build more plotting integration with Matplotlib as time goes on.

However, what might slow down beginners is the fact that this package is pretty extensive. There is so much that you can do with it and it might be hard to still keep a structure when you're learning how to work with Matplotlib.   

DataCamp has created a Matplotlib cheat sheet for those who might already know how to use the package to their advantage to make beautiful plots in Python, but that still want to keep a one-page reference handy. Of course, for those who don't know how to work with Matplotlib, this might be the extra push be convinced and to finally get started with data visualization in Python. 

You'll see that this cheat sheet presents you with the six basic steps that you can go through to make beautiful plots. 

Check out the infographic by clicking on the button below:

Python Matplotlib cheat sheet

With this handy reference, you'll familiarize yourself in no time with the basics of Matplotlib: you'll learn how you can prepare your data, create a new plot, use some basic plotting routines to your advantage, add customizations to your plots, and save, show and close the plots that you make.

What might have looked difficult before will definitely be more clear once you start using this cheat sheet! Use it in combination with the Matplotlib Gallery, the documentation.


Matplotlib is a Python 2D plotting library which produces publication-quality figures in a variety of hardcopy formats and interactive environments across platforms.

Prepare the Data 

1D Data 

>>> import numpy as np
>>> x = np.linspace(0, 10, 100)
>>> y = np.cos(x)
>>> z = np.sin(x)

2D Data or Images 

>>> data = 2 * np.random.random((10, 10))
>>> data2 = 3 * np.random.random((10, 10))
>>> Y, X = np.mgrid[-3:3:100j, -3:3:100j]
>>> U = 1 X** 2 + Y
>>> V = 1 + X Y**2
>>> from matplotlib.cbook import get_sample_data
>>> img = np.load(get_sample_data('axes_grid/bivariate_normal.npy'))

Create Plot

>>> import matplotlib.pyplot as plt


>>> fig = plt.figure()
>>> fig2 = plt.figure(figsize=plt.figaspect(2.0))


>>> fig.add_axes()
>>> ax1 = fig.add_subplot(221) #row-col-num
>>> ax3 = fig.add_subplot(212)
>>> fig3, axes = plt.subplots(nrows=2,ncols=2)
>>> fig4, axes2 = plt.subplots(ncols=3)

Save Plot 

>>> plt.savefig('foo.png') #Save figures
>>> plt.savefig('foo.png',  transparent=True) #Save transparent figures

Show Plot

>>> plt.show()

Plotting Routines 

1D Data 

>>> fig, ax = plt.subplots()
>>> lines = ax.plot(x,y) #Draw points with lines or markers connecting them
>>> ax.scatter(x,y) #Draw unconnected points, scaled or colored
>>> axes[0,0].bar([1,2,3],[3,4,5]) #Plot vertical rectangles (constant width)
>>> axes[1,0].barh([0.5,1,2.5],[0,1,2]) #Plot horiontal rectangles (constant height)
>>> axes[1,1].axhline(0.45) #Draw a horizontal line across axes
>>> axes[0,1].axvline(0.65) #Draw a vertical line across axes
>>> ax.fill(x,y,color='blue') #Draw filled polygons
>>> ax.fill_between(x,y,color='yellow') #Fill between y values and 0

2D Data 

>>> fig, ax = plt.subplots()
>>> im = ax.imshow(img, #Colormapped or RGB arrays
      cmap= 'gist_earth', 
      interpolation= 'nearest',
>>> axes2[0].pcolor(data2) #Pseudocolor plot of 2D array
>>> axes2[0].pcolormesh(data) #Pseudocolor plot of 2D array
>>> CS = plt.contour(Y,X,U) #Plot contours
>>> axes2[2].contourf(data1) #Plot filled contours
>>> axes2[2]= ax.clabel(CS) #Label a contour plot

Vector Fields 

>>> axes[0,1].arrow(0,0,0.5,0.5) #Add an arrow to the axes
>>> axes[1,1].quiver(y,z) #Plot a 2D field of arrows
>>> axes[0,1].streamplot(X,Y,U,V) #Plot a 2D field of arrows

Data Distributions 

>>> ax1.hist(y) #Plot a histogram
>>> ax3.boxplot(y) #Make a box and whisker plot
>>> ax3.violinplot(z)  #Make a violin plot

Plot Anatomy & Workflow 

Plot Anatomy 




The basic steps to creating plots with matplotlib are:

1 Prepare Data
2 Create Plot
3 Plot
4 Customized Plot
5 Save Plot
6 Show Plot

>>> import matplotlib.pyplot as plt
>>> x = [1,2,3,4]  #Step 1
>>> y = [10,20,25,30] 
>>> fig = plt.figure() #Step 2
>>> ax = fig.add_subplot(111) #Step 3
>>> ax.plot(x, y, color= 'lightblue', linewidth=3)  #Step 3, 4
>>> ax.scatter([2,4,6],
          color= 'darkgreen',
          marker= '^' )
>>> ax.set_xlim(1, 6.5)
>>> plt.savefig('foo.png' ) #Step 5
>>> plt.show() #Step 6

Close and Clear 

>>> plt.cla()  #Clear an axis
>>> plt.clf(). #Clear the entire figure
>>> plt.close(). #Close a window

Plotting Customize Plot 

Colors, Color Bars & Color Maps 

>>> plt.plot(x, x, x, x**2, x, x** 3)
>>> ax.plot(x, y, alpha = 0.4)
>>> ax.plot(x, y, c= 'k')
>>> fig.colorbar(im, orientation= 'horizontal')
>>> im = ax.imshow(img,
            cmap= 'seismic' )


>>> fig, ax = plt.subplots()
>>> ax.scatter(x,y,marker= ".")
>>> ax.plot(x,y,marker= "o")


>>> plt.plot(x,y,linewidth=4.0)
>>> plt.plot(x,y,ls= 'solid') 
>>> plt.plot(x,y,ls= '--') 
>>> plt.plot(x,y,'--' ,x**2,y**2,'-.' ) 
>>> plt.setp(lines,color= 'r',linewidth=4.0)

Text & Annotations 

>>> ax.text(1,
           'Example Graph', 
            style= 'italic' )
>>> ax.annotate("Sine", 
xy=(8, 0),
xycoords= 'data', 
xytext=(10.5, 0),
textcoords= 'data', 
arrowprops=dict(arrowstyle= "->", 


>>> plt.title(r '$sigma_i=15$', fontsize=20)

Limits, Legends and Layouts 

Limits & Autoscaling 

>>> ax.margins(x=0.0,y=0.1) #Add padding to a plot
>>> ax.axis('equal')  #Set the aspect ratio of the plot to 1
>>> ax.set(xlim=[0,10.5],ylim=[-1.5,1.5])  #Set limits for x-and y-axis
>>> ax.set_xlim(0,10.5) #Set limits for x-axis


>>> ax.set(title= 'An Example Axes',  #Set a title and x-and y-axis labels
            ylabel= 'Y-Axis', 
            xlabel= 'X-Axis')
>>> ax.legend(loc= 'best')  #No overlapping plot elements


>>> ax.xaxis.set(ticks=range(1,5),  #Manually set x-ticks
             ticklabels=[3,100, 12,"foo" ])
>>> ax.tick_params(axis= 'y', #Make y-ticks longer and go in and out
             direction= 'inout', 

Subplot Spacing 

>>> fig3.subplots_adjust(wspace=0.5,   #Adjust the spacing between subplots
>>> fig.tight_layout() #Fit subplot(s) in to the figure area

Axis Spines 

>>> ax1.spines[ 'top'].set_visible(False) #Make the top axis line for a plot invisible
>>> ax1.spines['bottom' ].set_position(( 'outward',10))  #Move the bottom axis line outward

Have this Cheat Sheet at your fingertips

Original article source at https://www.datacamp.com

#matplotlib #cheatsheet #python

Autumn  Blick

Autumn Blick


Game Development with .NET

We’ve launched a new Game Development with .NET section on our site. It’s designed for current .NET developers to explore all the choices available to them when developing games. It’s also designed for new developers trying to learn how to use .NET by making games. We’ve also launched a new game development Learn portal for .NET filled with tutorials, videos, and documentation provided by Microsoft and others in the .NET game development community. Finally, we launched a step-by-step Unity get-started tutorial that will get you started with Unity and writing C## scripts for it in no time. We are excited to show you what .NET has to offer to you when making games. .NET is also part of Microsoft Game Stack, a comprehensive suite of tools and services just for game development.

A picture of a game controller

.NET for game developers

.NET is cross-platform. With .NET you can target over 25+ different platforms with a single code base. You can make games for, but not limited to, Windows, macOS, Linux, Android, iOS, Xbox, PlayStation, Nintendo, and mixed reality devices.

C## is the most popular programming language in game development. The wider .NET community is also big. There is no lack of expertise and support you can find from individuals and user groups, locally or online.

.NET does not just cover building your game. You can also use it to build your game’s website with ASP.NET, your mobile app using Xamarin, and even do remote rendering with Microsoft Azure. Your skills will transfer across the entire game development pipeline.

logos of some gaming platforms supported by .NET

Available game engines

The first step to developing games in .NET is to choose a game engine. You can think of engines as the frameworks and tools you use for developing your game. There are many game engines that use .NET and they differ widely. Some of the engines are commercial and some are completely royalty free and open source. I am excited to see some of them planning to adopt .NET 5 soon. Just choose the engine that better works for you and your game. Would you like to read a blog post to help you learn about .NET game engines, and which one would be best for you?

#.net #.net core #azure #c# #game development #azure #cryengine #game developers #game development #game development with .net #game engines #games #monogame #playfab #stride #unity #visual studio #waveengine

Sival Alethea

Sival Alethea


Learn Python by Building Five Games - Full Course. DO NOT MISS!!!

Learn Python in this full tutorial course for beginners. This course takes a project-based approach. We have collected five great Python game tutorials together so you can learn Python while building five games. If you learn best by doing, this is the course for you.
⭐️ Course Contents ⭐️
⌨️ (0:01:18) Pong
⌨️ (0:45:36) Snake
⌨️ (1:34:57) Connect Four
⌨️ (2:42:36) Tetris
⌨️ (4:22:12) Online Multiplayer Game
📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=XGf2GcyHPhc&list=PLWKjhJtqVAbnqBxcdjVGgT3uVR10bzTEB&index=4
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#python #games #learn python by building five game #project-based approach #game in python #learn python by building five games - full course