Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon
19. November 2015

 

I remember using Allegro wayyyyyy back in the day in the early 1990s.  It was one of few graphics libraries available for DOS based machines (even though it started life as an Atari library) and certainly one of the only free game libraries available.  Amazingly enough Allegro is still under active development.  Anyways enough reminiscing…  today Allegro.js was released, an HTML5 library inspired by Allegro.  For a brand new library there is already an impressive amount of documentation and reference material available.  One of the hallmarks of the Allegro library was it was brutally simple to use and Allegro.js seems to have carried on that tradition.  Here is an example Allegro app:

 

// bitmap oobjects
var logo,ball;

// sample object
var bounce;

// size and speed of the ball
var size=64,speed=5;

// positon of the ball
var cx=100,cy=100;

// velocity of the ball
var vx=speed,vy=speed;

// drawing function
function draw()
{
   // draw allegro logo background
   stretch_blit(logo,canvas,0,0,logo.w,logo.h,0,0,SCREEN_W,SCREEN_H);
   
   // draws the ball resized to size*size, centered
   // stretch it a bit vertically according to velocity
   stretch_sprite(canvas,ball,cx-size/2,cy-size/2,size,size+abs(vy));
}

// update game logic
function update()
{
   // did the ball bounce off the wall this turn?
   var bounced=false;

   
   // if the ball is going to collide with screen bounds
   // after applying velocity, if so, reverse velocity
   // and remember that it bonced
   if (cx+vx>SCREEN_W-size/2) {vx=-speed;bounced=true;}
   if (cy+vy>SCREEN_H-size/2) {vy=-speed*3;bounced=true;}
   if (cx+vx<size/2) {vx=speed;bounced=true;}
   if (cy+vy<size/2) {vy=speed;bounced=true;}
      
   // move the ball
   cx+=vx;
   cy+=vy;
   
   // if it bounced, play a sound
   if (bounced) play_sample(bounce);
   
   // add gravity
   vy+=.3;
}

// entry point of our example
function main()
{
   // enable debugging to console element
   enable_debug("debug");
   
   // init all subsystems, put allegro in canvas with id="canvas_id"
   // make the dimesnions 640x480
   allegro_init_all("canvas_id", 640, 480);
   
   // load ball image
   ball = load_bmp("data/planet.png");
   
   // load background image
   logo = load_bmp("data/allegro.png");
   
   // load the bounce sound
   bounce = load_sample("data/bounce.mp3");

   // make sure everything has loaded
   ready(function(){
      
      // repeat this game loop
      loop(function(){
         
         // clear screen
         clear_to_color(canvas, makecol(255, 255, 255));

         // update game logic
         update();

         // render everything
         draw();
   
      // all this happens 60 times per second
      }, BPS_TO_TIMER(60));
   });
   
   // the end
   return 0;
}
// make sure that main() gets called as soon as the wesbite has loaded
END_OF_MAIN();

 

If this looks interesting to you be sure to check out Allegro.js.  It looks like a cool library, based on another cool library, just waiting for a community to form around it.

GameDev News, Programming ,

19. November 2015

 

Just a quick note to announce a new series I have started, The GameDev Toolbox.

Toolbox

 

The series is intended to bring exposure to a wide variety of tools used in game development.  This includes graphic creation packages, IDEs, audio tools, design tools and more.  Basically if it isn’t a library, framework or game engine and it’s used for game development we will probably take a look at it.

These are not reviews, nor are they tutorials.  They are meant as a quick introduction and overview and nothing more.  For now the series is video only, but I will be creating a text based version in the near future.  There is a playlist for the series available here.

It currently consists of:

 

This video shows the premise of the series:

Art, Design, General, Programming

15. November 2015

 

We already have motion controls, audio control and of course tactile control, what about controlling a game with your emotions?  It sounds far fetched but it really isn’t, in fact it’s here today.  Just about every single modern gaming device has a front facing camera available in some form or another.  Well, Microsoft Research lab Microsoft Project Oxford just announced the release of the emotion tool which enables you to detect emotions on a persons face.

 

Basically you send it a picture and it returns the probability of various emotions.  For example, I sent it this image here and it returned the following results:

image

 

Basically you feed it an image in URL form and optionally a rectangle selecting the face, and it returns a JSON result with the probability of each emotion.  In this case Microsoft determine with 99.99% likelihood that this baby is sad, with a 0.001% chance that it’s angry instead.  I fed it a handful of pictures and it did a remarkably accurate job.

 

You can use it as a REST API now ( or just play with the playground ) right here.  Otherwise the SDK can be downloaded here.

 

So the tech is actually here already and works pretty well.  The question remains… would gamers embrace having a camera constantly scanning their emotions?  I actually can think of a few genres or tools where they might.  How many “you mad bro?” apps can we expect to flood the market now? If nothing else, it’s a fun tool to play around with on a Sunday afternoon!

Programming, Totally Off Topic

14. November 2015

 

CastleDB is a light weight database written in Haxe with data composed of sheets.  It makes storing structured data extremely simple, much like working with an Excel spreadsheet and much simpler than a traditional database.  The resulting data is stored in JSON making it easily used in almost any game engine or programming language.   Most interestingly you can treat 2D game levels just like any other data using the newly built in level editor.

 

There is an HD video version of this guide available here.  It covers mostly the same details as this tutorial but goes into a bit more depth of using the level editor.

 

Let’s first take a look at the database side of things.  Even without the level editing abilities, games are often in need of simple database services.  Simply download and extract the archive for your appropriate platform:

image

 

Then run cdb.exe.  The interface looks like this:

image

 

Start by creating a new sheet by clicking Create a sheet.  This is comparable to creating a new table in a database.

image

 

Simply name your sheet and click Create.

 

Next we add some columns to our newly created sheet, same basic process.

image

 

Next pick the column type.

image

 

Optionally tick Required if the field cant be left empty.

image

 

You could select List and link to another database creating complex relationships.  Now we can populate a a database using the “New Line” command.  Select a type like Sprite (Image) and the appropriate dialog is displayed.

image

 

Now save the cdb file somewhere and you can access the data with code relatively easily.  First create a source file with the following contents, the black magic that links your cdb file to haxe code.

package com.gamefromscratch.castledemo.db;
private typedef Init = haxe.macro.MacroType < [cdb.Module.build("new.cdb")] > ;

 

And now you can consume it like:

package com.gamefromscratch.castledemo;

import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.Lib;
import haxe.Resource;

import com.gamefromscratch.castledemo.db.MyData;
class Main 
{
	
	static function main() 
	{
		
		#if js
		MyData.load(null);
		#else
		MyData.load(haxe.Resource.getString("new.cdb"));
		#end
		trace(MyData.myDB.get(Lich).HitPoints);
	}
	
}

 

Pretty simple over all.  Now what was that about a level editor?

 

Well… remember back when you created the first sheet?  You may remember a little checkbox “Create Level”.

image

 

Well this creates a table just like any other with some prepopulated values:

image

 

Width and Height are the number of cells that compose your level, the rest will be populated shortly.  Notice the Edit button that appears now?  Click it.

image

TADA!  Level editor.

The level editor can work in tiles or objects, let’s start with a single object layer for our background image.  Click the New Layer button at the top right.

image

Name it then click create.  Now click the File… button and we will select our background tiles.

image

 

Your image will now appear ready for painting, like so:

image

 

In Tile mode, simply select the tile, or tiles you wish to paint with like so:

image

 

Now back on your layer make sure you are in Tiles mode:

image

 

And paint away:

GIF

 

You can also work in object mode, which allows you to place sets of tiles without being confined to the grid.  First, define a set of tiles as an object:

GIF2

 

Now you can switch your level to object mode and draw using the created objects instead.

 

Now perhaps coolest of all, you can also instance data easily enough.  For example, we could add and place NPCs on our map, first we extend the map sheet to have an addition field, a List called npc, like so:

image

The List contains a reference to our monster table for example, x,y coordinates and an id.  Now if you head back to your map, you will see you’ve got an additional layer created:

image

 

Which you can now use to place NPCs or other data in your world.  You could do the same thing for collision data, whatever you wish.

This is only scratching the surface of what the level editor can do, there is even auto-tiling support built in.  Be sure to watch the video version for a more in-depth idea of the level editors capabilities.  Then when you are all done, it’s ultimately just data that you’ve been working with.

 

Now the downside is, there is no level loader when you are done.  So whatever engine or game you are importing the result into, it’s still just data.  It’s going to be your responsibility to display it all on screen.

 

The Video

Programming

5. November 2015

 

In this tutorial we are going to look at playing back music in our SFML game.  We will look at streaming an ogg file from disk.  We will also quickly look at the basics of handling time in SFML as we add fast forward and rewind abilities to our music playback.

 

There is an HD version of this tutorial here.

 

Playing music files is different from playing audio files and we will deal with this in a separate tutorial.  Music files are designed to be streamed from disk, not resident in memory.  SFML supports the following file formats:

  • ogg
  • wav
  • flac
  • aiff
  • au
  • raw
  • paf
  • svx
  • nist
  • voc
  • ircam
  • w64
  • mat4
  • mat5
  • pvf
  • htk
  • sds
  • avr
  • sd2
  • caf
  • wve
  • mpc2k
  • rf64

 

You will notice a very noticeable exception from that list, the mp3 format. That is because the mp3 format is encumbered by a number of patents and should be avoided to protect yourself from potential licensing fees.  Fortunately the ogg format offers similar file sizes and similar audio quality as the mp3 format without the licensing pitfalls.  If you require to covert formats the free software Audacity is an excellent and easy choice.

 

The major difference between sound effect and music is the sound effect stays resident in memory, while a Music file is streamed from disk.  Both classes still possess a great deal of common behaviour.  In fact if you look at the inheritance tree you will see that they have a common base class.

 

image

 

Now lets finally create some code showing how to actually play and control music files.

 

// Demonstrate that the hills are alive with the sound of music
#include "SFML/Graphics.hpp"
#include "SFML/Audio.hpp"
#include <iostream>

int main(int argc, char ** argv){
  sf::RenderWindow renderWindow(sf::VideoMode(640, 480), "Demo Game");

  sf::Event event;
  sf::Music music;
  music.openFromFile("audio/goats_typicalamerican.ogg");
  music.setVolume(50);

  music.play();

  while (renderWindow.isOpen()){
    while (renderWindow.pollEvent(event)){
      if (event.type == sf::Event::EventType::Closed)
        renderWindow.close();


      if (event.type == sf::Event::EventType::KeyPressed){

        // Up and down to control volume
        if (event.key.code == sf::Keyboard::Key::Down)
          music.setVolume(music.getVolume() - 10);
        if (event.key.code == sf::Keyboard::Key::Up)
          music.setVolume(music.getVolume() + 10);
        

        // Left and right to control tracking position
        if (event.key.code == sf::Keyboard::Key::Right){
          auto newPos = music.getPlayingOffset() + sf::seconds(5);
          music.setPlayingOffset(sf::Time(newPos));
        }
          
        if (event.key.code == sf::Keyboard::Key::Left){
          auto newPos = music.getPlayingOffset() - sf::seconds(5);
          if (newPos.asSeconds() <= 0.0f) newPos = sf::seconds(0);
          music.setPlayingOffset(sf::Time(newPos));
        }

        std::cout << "Current volume is :" << music.getVolume() << " position is: " 
          << music.getPlayingOffset().asSeconds() << std::endl;
      }
    }

    renderWindow.clear();
    renderWindow.display();
  }
}

 

You’ll notice that loading a music file is pretty much identical to loading any other asset in SFML.  Keep in mind the Music class actually owns the underlying data of the music that is played so it is not a light weight class so be careful when they are created.  However since the Music file is played from disk instead of from memory, it is safe to allocated multiple concurrent Music files, such as one per song played, without being hugely wasteful.

 

The code itself is fairly self explanitory.  You can set the volume directly on a music file that is being played, you can control music playback using vcr style play/pause/stop() controls.  You can also control the position of the sound using a combination of getPlayingOffset() and setPlayingOffset().  As you can see there are also time operators built into SFML such as sf::seconds() or sf::milliseconds() making time based math extremely simple.

 

There is a great deal more you can do with audio files, but we will cover that in the sound effects tutorial.

 

The Video

 

Programming , ,

Month List

Popular Comments