Skip to content

14 search results for "my free tileset"

JavaFX, how to create a rpg like game

JavaFX 1.0 is out and there are tons of new cool features, specially for game development.trans

I’ll show in this tutorial how to create a very simple demo that shows how to load imtrages, handle sprites, collisions and keyboard events that you can use to create a game with a old school rpg like vision.

For the background scenario I’m using the house that I drew and we’ll call as house.png.

That we load as a Image and place into a ImageView.

ImageView{
   image: Image {url: "{__DIR__}house.png"}
}

For the character I’m using the last character I drew, the nerdy guy.

To make the animation easier, I spited it into 9 pieces:

down0.png, down1.png and down2.png

left0.png, left1.png and left2.png

right0.png, right1.png and righ2.png

up0.png, up1.png and up2.png

All images I’m using should be in the same directory of source code.

Let’s start loading the scenario and a single character sprite.

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.image.*;

Stage {
   title: "RPG-like demo", width: 424, height: 412
   visible: true
   scene: Scene{
      content: [
         ImageView{
         image: Image {url: "{__DIR__}house.png"} },
         ImageView{
            x: 320 y: 80
            image: Image {url: "{__DIR__}down1.png"}
         }
      ]
   }
}

Saved as Game.fx you can compile and run with in your terminal:

$ javafxc Game.fx

$ javafx Game

Hint: You can use NetBeans 6.5 JavaFX plugin to easier the JavaFX development.

To put animation on the character we load all sprites into four lists. Each list for each direction.

// sprites
def up    = for(i in [0..2]) { Image {url: "{__DIR__}up{i}.png"    } }
def right = for(i in [0..2]) { Image {url: "{__DIR__}right{i}.png" } }
def down  = for(i in [0..2]) { Image {url: "{__DIR__}down{i}.png"  } }
def left  = for(i in [0..2]) { Image {url: "{__DIR__}left{i}.png"  } }

And create vars to store the character position and frame of animation.

var frame = 0;
var posx = 320;
var posy = 80;

Also store the house background.

// house background
def house = ImageView{ image: Image {url: "{__DIR__}house.png"} };

I create booleans to store some key states and at each interval of time I see how they are and do something about. You can handle keyboard event with less code but I like this way because keep visual and game logics a little bit more separated.

// keyboard
var    upkey = false;
var rightkey = false;
var  downkey = false;
var  leftkey = false;

// player
var player = ImageView{
   x: bind posx y: bind posy
   image: Image {url: "{__DIR__}down1.png"}
   onKeyPressed: function(e:KeyEvent){
      if (e.code == KeyCode.VK_DOWN) {
      downkey = true;
      } else if (e.code == KeyCode.VK_UP) {
         upkey = true;
      }else if (e.code == KeyCode.VK_LEFT) {
         leftkey = true;
      }else if (e.code == KeyCode.VK_RIGHT) {
         rightkey = true;
      }
   } // onKeyPressed

   onKeyReleased: function(e: KeyEvent){
      if (e.code == KeyCode.VK_DOWN) {
         downkey = false;
      } else if (e.code == KeyCode.VK_UP) {
         upkey = false;
      }else if (e.code == KeyCode.VK_LEFT) {
         leftkey = false;
      }else if (e.code == KeyCode.VK_RIGHT) {
         rightkey = false;
      }
   } // onKeyReleased
}

See a video of the game working so far:

[youtube]Xv5z-9LGuOc[/youtube]

Now we will add collisions. In a previous post I showed some math behind bounding box game collisions. The good news are that you no longer need to worry about that. There are a lot of API improvements in JavaFX 1.0 that do all the hard work for you, specially the new classes on javafx.geometry package, Rectangle2D and Point2D.

We create rectangles that represent the obstacles in the house.

// collidable obstacles
def obstacles = [
	Rectangle { x:   0 y:   0 width:  32 height: 382 stroke: Color.RED },
	Rectangle { x:   0 y:   0 width: 414 height:  64 stroke: Color.RED },
	Rectangle { x: 384 y:   0 width:  32 height: 382 stroke: Color.RED },
	Rectangle { x:   0 y: 192 width: 128 height:  64 stroke: Color.RED },
	Rectangle { x: 192 y: 192 width:  64 height:  64 stroke: Color.RED },
	Rectangle { x: 224 y:   0 width:  32 height: 288 stroke: Color.RED },
	Rectangle { x: 288 y: 128 width:  96 height:  64 stroke: Color.RED },
	Rectangle { x:   0 y: 352 width: 128 height:  32 stroke: Color.RED },
	Rectangle { x: 192 y: 352 width: 192 height:  32 stroke: Color.RED },
	Rectangle { x: 224 y: 320 width:  32 height:  32 stroke: Color.RED },
	Rectangle { x:  32 y:  64 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  64 y:  64 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  96 y:  64 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 128 y:  64 width: 64 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 192 y:  32 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  64 y: 128 width: 64 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  32 y: 250 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  64 y: 250 width: 64 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 200 y: 255 width: 20 height: 20 stroke: Color.YELLOW },
	Rectangle { x: 200 y: 170 width: 20 height: 20 stroke: Color.YELLOW },
	Rectangle { x: 257 y:  32 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 288 y:  32 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 320 y: 192 width: 64 height: 64 stroke: Color.YELLOW },
	Rectangle { x: 352 y: 295 width: 32 height: 60 stroke: Color.YELLOW },
	Rectangle { x:  32 y: 327 width: 64 height: 23 stroke: Color.YELLOW },
];

We just have to change a little bit the game logics in order to handle collisions.

We define a bounding box around the player, it’s a rectangle from (4, 25) at the player coordinates system and with width 19 and height 10. The idea is to prospect where the player will be in the next step, see if it’s bouding box don’t collide with any obstacle and so pass it to the real game position.

// game logics
var gamelogics = Timeline {
   repeatCount: Timeline.INDEFINITE
   keyFrames: KeyFrame {
      time : 1s/8
      action: function() {
         var nextposx = posx;
         var nextposy = posy;
         if(downkey) {
            nextposy += 5;
            player.image = down[++frame mod 3];
         }
         if(upkey) {
            nextposy -= 5;
            player.image = up[++frame mod 3];
         }
         if(rightkey) {
            nextposx += 5;
            player.image = right[++frame mod 3];
         }
         if(leftkey) {
            nextposx -= 5;
            player.image = left[++frame mod 3];
         }
         for(obst in obstacles) {
            if(obst.boundsInLocal.intersects(nextposx + 4, nextposy + 25, 19, 10)) {
               return;
            }
         }
         posx = nextposx;
         posy = nextposy;
      }
   }
}

This is enough to do the trick but I also added a way to smoothly show the obstacles when pressing the space key.

[youtube]k-MHh6irvwE[/youtube]

Here is the complete source code.

package Game; 

import javafx.stage.Stage;
import javafx.scene.*;
import javafx.scene.image.*;
import javafx.scene.input.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.animation.*;

var frame = 0;
var posx = 320;
var posy = 80;

// sprites
def up    = for(i in [0..2]) { Image {url: "{__DIR__}up{i}.png"    } }
def right = for(i in [0..2]) { Image {url: "{__DIR__}right{i}.png" } }
def down  = for(i in [0..2]) { Image {url: "{__DIR__}down{i}.png"  } }
def left  = for(i in [0..2]) { Image {url: "{__DIR__}left{i}.png"  } }

// house background
def house = ImageView{ image: Image {url: "{__DIR__}house.png"} };

// keyboard
var    upkey = false;
var rightkey = false;
var  downkey = false;
var  leftkey = false;

// player
var player = ImageView{
   x: bind posx y: bind posy image: down[1]
   onKeyPressed: function(e:KeyEvent){
      if (e.code == KeyCode.VK_DOWN) {
         downkey = true;
      } else if (e.code == KeyCode.VK_UP) {
         upkey = true;
      }else if (e.code == KeyCode.VK_LEFT) {
         leftkey = true;
      }else if (e.code == KeyCode.VK_RIGHT) {
         rightkey = true;
      }

		if(e.code == KeyCode.VK_SPACE){
         if(fade==0.0){
         	fadein.playFromStart();
			}
			if(fade==1.0){
				fadeout.playFromStart();
			}
		}
   } // onKeyPressed

   onKeyReleased: function(e: KeyEvent){
      if (e.code == KeyCode.VK_DOWN) {
         downkey = false;
      } else if (e.code == KeyCode.VK_UP) {
         upkey = false;
      }else if (e.code == KeyCode.VK_LEFT) {
         leftkey = false;
      }else if (e.code == KeyCode.VK_RIGHT) {
         rightkey = false;
      }
   } // onKeyReleased
}

// collidable obstacles
def obstacles = [
	Rectangle { x:   0 y:   0 width:  32 height: 382 stroke: Color.RED },
	Rectangle { x:   0 y:   0 width: 414 height:  64 stroke: Color.RED },
	Rectangle { x: 384 y:   0 width:  32 height: 382 stroke: Color.RED },
	Rectangle { x:   0 y: 192 width: 128 height:  64 stroke: Color.RED },
	Rectangle { x: 192 y: 192 width:  64 height:  64 stroke: Color.RED },
	Rectangle { x: 224 y:   0 width:  32 height: 288 stroke: Color.RED },
	Rectangle { x: 288 y: 128 width:  96 height:  64 stroke: Color.RED },
	Rectangle { x:   0 y: 352 width: 128 height:  32 stroke: Color.RED },
	Rectangle { x: 192 y: 352 width: 192 height:  32 stroke: Color.RED },
	Rectangle { x: 224 y: 320 width:  32 height:  32 stroke: Color.RED },
	Rectangle { x:  32 y:  64 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  64 y:  64 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  96 y:  64 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 128 y:  64 width: 64 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 192 y:  32 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  64 y: 128 width: 64 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  32 y: 250 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  64 y: 250 width: 64 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 200 y: 255 width: 20 height: 20 stroke: Color.YELLOW },
	Rectangle { x: 200 y: 170 width: 20 height: 20 stroke: Color.YELLOW },
	Rectangle { x: 257 y:  32 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 288 y:  32 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 320 y: 192 width: 64 height: 64 stroke: Color.YELLOW },
	Rectangle { x: 352 y: 295 width: 32 height: 60 stroke: Color.YELLOW },
	Rectangle { x:  32 y: 327 width: 64 height: 23 stroke: Color.YELLOW },
];

// game logics
var gamelogics = Timeline {
   repeatCount: Timeline.INDEFINITE
   keyFrames: KeyFrame {
      time : 1s/8
      action: function() {
         var nextposx = posx;
         var nextposy = posy;
         if(downkey) {
            nextposy += 5;
            player.image = down[++frame mod 3];
         }
         if(upkey) {
            nextposy -= 5;
            player.image = up[++frame mod 3];
         }
         if(rightkey) {
            nextposx += 5;
            player.image = right[++frame mod 3];
         }
         if(leftkey) {
            nextposx -= 5;
            player.image = left[++frame mod 3];
         }
         for(obst in obstacles) {
            if(obst.boundsInLocal.intersects(nextposx + 4, nextposy + 25, 19, 10)) {
               return;
            }
         }
         posx = nextposx;
         posy = nextposy;
      }
   }
}

gamelogics.play();

// obstacles view
var fade = 0.0;

var obstacleslayer = Group {
   opacity: bind fade
   content: [
      Rectangle { x:0 y:0 width:500 height: 500 fill: Color.BLACK },
      obstacles,
      Rectangle {
        x: bind posx + 4 y: bind posy + 25 width: 19 height: 10
        fill: Color.LIME
      }
   ]
}

var fadein = Timeline {
	keyFrames: [
   	at (0s) {fade => 0.0}
   	at (1s) {fade => 1.0}
   ]
}

var fadeout = Timeline {
	keyFrames: [
   	at (0s) {fade => 1.0}
   	at (1s) {fade => 0.0}
   ]
}

// game stage
Stage {
	title: "RPG-like demo", width: 424, height: 412
	visible: true
	scene: Scene{
      fill: Color.BLACK
		content: [house, player, obstacleslayer]
	}
}

Play Through Java Web Start

or click here to play via applet, inside your browser.

update: The applet version and Java Web Start versions should be working now.  The applet version on Linux seems to be having problems with the keyboard handling, use the Java Web Start version while I’m trying to fix it.

Downloads:

Tiled TMX Map Loader for Pygame

I’m using the Tiled Map Editor for a while, I even wrote that tutorial about it. It’s a general purpose tile map editor, written in Java but now migrating to C++ with Qt, that can be easily used with my set of free pixelart tiles.

map editor tiles tileset game deveopment

A map done with Tiled is stored in a file with TMX extension. It’s just a XML file, easy to understand.

As I’m creating a map loader for my owns purposes, the procedure I’m doing here works we need some simplifications. I’m handling orthogonal maps only. I’m not supporting tile properties as well. I also don’t want to handle base64 and zlib encoding in this version, so in the Tiled editor, go at the menu Edit → Preferences and in the Saving tab unmark the options “Use binary encoding” and “Compress Layer Data (gzip)”, like this:

Tiled Preferences Window

When saving a map it will produce a TMX file like this:




 
  
  
 
 
  
 
 
  
   
   
    ...
   
   
  
 

For processing it on Python I’m using the event oriented SAX approach for XML. So I create a ContentHandler that handles events the start and end of XML elements. In the first element, map, I know enough to create a Pygame surface with the correct size. I’m also storing the map properties so I can use it later for add some logics or effects on the map. After that we create a instance of the Tileset class from where we will get the each tile by an gid number. Each layer has it’s a bunch of gids in the correct order. So it’s enough information to mount and draw a map.

# Author: Silveira Neto
# License: GPLv3
import sys, pygame
from pygame.locals import *
from pygame import Rect
from xml import sax

class Tileset:
    def __init__(self, file, tile_width, tile_height):
        image = pygame.image.load(file).convert_alpha()
        if not image:
            print "Error creating new Tileset: file %s not found" % file
        self.tile_width = tile_width
        self.tile_height = tile_height
        self.tiles = []
        for line in xrange(image.get_height()/self.tile_height):
            for column in xrange(image.get_width()/self.tile_width):
                pos = Rect(
                        column*self.tile_width,
                        line*self.tile_height,
                        self.tile_width,
                        self.tile_height )
                self.tiles.append(image.subsurface(pos))

    def get_tile(self, gid):
        return self.tiles[gid]

class TMXHandler(sax.ContentHandler):
    def __init__(self):
        self.width = 0
        self.height = 0
        self.tile_width = 0
        self.tile_height = 0
        self.columns = 0
        self.lines  = 0
        self.properties = {}
        self.image = None
        self.tileset = None

    def startElement(self, name, attrs):
        # get most general map informations and create a surface
        if name == 'map':
            self.columns = int(attrs.get('width', None))
            self.lines  = int(attrs.get('height', None))
            self.tile_width = int(attrs.get('tilewidth', None))
            self.tile_height = int(attrs.get('tileheight', None))
            self.width = self.columns * self.tile_width
            self.height = self.lines * self.tile_height
            self.image = pygame.Surface([self.width, self.height]).convert()
        # create a tileset
        elif name=="image":
            source = attrs.get('source', None)
            self.tileset = Tileset(source, self.tile_width, self.tile_height)
        # store additional properties.
        elif name == 'property':
            self.properties[attrs.get('name', None)] = attrs.get('value', None)
        # starting counting
        elif name == 'layer':
            self.line = 0
            self.column = 0
        # get information of each tile and put on the surface using the tileset
        elif name == 'tile':
            gid = int(attrs.get('gid', None)) - 1
            if gid <0: gid = 0
            tile = self.tileset.get_tile(gid)
            pos = (self.column*self.tile_width, self.line*self.tile_height)
            self.image.blit(tile, pos)

            self.column += 1
            if(self.column>=self.columns):
                self.column = 0
                self.line += 1

    # just for debugging
    def endDocument(self):
        print self.width, self.height, self.tile_width, self.tile_height
        print self.properties
        print self.image

def main():
    if(len(sys.argv)!=2):
        print 'Usage:\n\t{0} filename'.format(sys.argv[0])
        sys.exit(2)
    pygame.init()
    screen = pygame.display.set_mode((800, 480))
    parser = sax.make_parser()
    tmxhandler = TMXHandler()
    parser.setContentHandler(tmxhandler)
    parser.parse(sys.argv[1])
    while 1:
        for event in pygame.event.get():
            if event.type == QUIT:
                return
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                return
        screen.fill((255,255,255))
        screen.blit(tmxhandler.image, (0,0))
        pygame.display.flip()
        pygame.time.delay(1000/60)

if __name__ == "__main__": main()

Here is the result for opening a four layers map file:

netbeans python openning map

That’s it. You can get this code and adapt for your game because next versions will be a lot more coupled for my own purposes and not so general.

Download:packagemaploader.tar.bz2 It’s the Netbeans 6.7 (Python EA 2) project file but that can be opened or used with another IDE or without one. Also contains the village.tmx map and the tileset.

JavaFX, Simple Tile Set

Tile sets are a very simple way to draw scenarios with repeated elements. From simple to complex ones using a very low footprint.

First step, load the png file that stores the tileset into a Image. The file tiles.png shoud be in the same directory of the source code. I adjusted some tiles from those tile set I’ve blogged here before into a grid of 10×10 tiles.

Set of tiles, example

var tileset = Image {
   url: "{__DIR__}tiles.png"
}

Notice that each tile have 32 of height and 32 of width. We will assume this and use theses numbers when performing calculations to find a single tile in our tile set.

def w = 32;
def h = 32;

To display a Image in the screen we use a ImageView node. A ImageView can have a viewport property to create crop or zoom effect. A viewport is just a Rectangle2D, a object with position (minX and minY), height and width. If we want to display the first tile in the tileset we do

first tile

ImageView {
   image: tileset
   viewport: Rectangle2D{
      minX: 0, minY: 0, height: 32, width: 32
   }
}

Notice that the minX determines the column and minY the row in the tileset. The first row is 0*32, the second row is 1*32 and so on. If we want to display the tile at the second line and third column of the tileset we do

another_tile

ImageView {
   image: tileset
   viewport: Rectangle2D{
      minX: 2 * 32 , minY: 1*32, height: 32, width: 32
   }
}

Those properties in a Rectangle2D are for init and read only. So I created a list with all Rectangles I can need for use as a viewport.

def viewports = for (row in [0..9]) {
   for (col in [0..9]) {
       Rectangle2D{
           minX: col * w, minY: row * h, height: w, width: h
       }
   }
}

The scenario map is stored in another list. The first element of the list is 7, that is, the first tile in the scenario is the 7th tile from the tile set.

var map = [
    7,  3,  3,  3,  3,  3,  3,  3,  3,  8,
   19, 26, 40, 41, 24, 13, 13, 23, 24, 19,
   19, 36, 50, 51, 34,  2,  2,  2, 34, 19,
   19,  2,  2,  2,  2,  2,  2,  2, 25, 19,
   19, 57, 58, 44, 45, 46,  2,  2, 35, 19,
   27,  3,  3,  6, 55, 56,  5,  3,  3, 38,
   19, 60, 13, 16, 47, 48, 15, 13, 61, 19,
   19, 70,  1, 33,  1,  1,  1,  1, 71, 19,
   19,  1,  1,  1,  1,  1,  1,  1, 49, 19,
   17,  9,  9,  9,  9,  9,  9,  9,  9, 18,
];

Finally to create a scenario with 100 tiles, 10 per row and with 10 rows, in a list called tiles. Each iteration of this loop creates a ImageView. Each ImageView will store a single tile. We get the tile number in the map list and so use it to index the viewports list.

var tiles =  for (row in [0..9]) {
   for (col in [0..9]) {
      ImageView {
         x: col * w, y: row * h,
         viewport: bind viewports[map[row * 10 + col]]
         image: tileset
      }
   }
}

Additionally I added two things to transform this program also in a (extremely)  simple map editor. At each ImageView I added a callback for onMouseClicked event. When you click on a tile, it changes its map position, ie, the tile. The next tile for the left button and the last tile for any other button.

onMouseClicked: function( e: MouseEvent ):Void {
   var amount = if(e.button == MouseButton.PRIMARY) { 1 } else { -1 };
   map[row * 10 + col] = (map[row * 10 + col] + amount) mod 100;
}

The other thing is to print the map list when the program is over. There is the full program:

package tileeditor;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.scene.CustomNode;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.geometry.Rectangle2D;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.MouseButton;

def w = 32;
def h = 32;

var map = [
    7,  3,  3,  3,  3,  3,  3,  3,  3,  8,
   19, 26, 40, 41, 24, 13, 13, 23, 24, 19,
   19, 36, 50, 51, 34,  2,  2,  2, 34, 19,
   19,  2,  2,  2,  2,  2,  2,  2, 25, 19,
   19, 57, 58, 44, 45, 46,  2,  2, 35, 19,
   27,  3,  3,  6, 55, 56,  5,  3,  3, 38,
   19, 60, 13, 16, 47, 48, 15, 13, 61, 19,
   19, 70,  1, 33,  1,  1,  1,  1, 71, 19,
   19,  1,  1,  1,  1,  1,  1,  1, 49, 19,
   17,  9,  9,  9,  9,  9,  9,  9,  9, 18,
];

var tileset = Image {
    url: "{__DIR__}tiles.png"
}

def viewports = for (row in [0..9]) {
   for (col in [0..9]) {
       Rectangle2D{
           minX: col * w, minY: row * h, height: w, width: h
       }
   }
}

var tiles =  for (row in [0..9]) {
   for (col in [0..9]) {
      ImageView {
         x: col * w, y: row * h,
         viewport: bind viewports[map[row * 10 + col]]
         image: tileset

         onMouseClicked: function( e: MouseEvent ):Void {
            var amount = if(e.button == MouseButton.PRIMARY) { 1 } else { -1 };
            map[row * 10 + col] = (map[row * 10 + col] + amount) mod 100;
         }
      }
   }
}

Stage {
    title: "JavaFX Simple Tile Editor"
    scene: Scene {
        content: [ tiles ]
    }
    onClose: function() {
        println(map);
    }
}

Here is the result for that map

tlemap javafx

And you can try it yourself in your browser. Play it online now.

Here is a video of it working

[youtube]lxuBEoItB5E[/youtube]

Downloads:

Possibilities

We are using just  a image that can handle 100 tiles, tiles.png with less than 30Kb. The map is also composed with 100 tiles. Each tile we can choose between 100 different tiles, so we can compose 10100 different maps (one googol10 ). Most of them are useless and without any sense, but some are cool. 🙂

Can't find what you're looking for? Try refining your search: