How to write game with Vue.js – Sokoban – Part 3 – Display game objects

In previous article we were talking about graphics tiles. Now we would like to display game objects. Sokoban contains just two types of objects: avatar and boxes.

We will store these game objects in a list and we will use the same CSS trick to display graphic for each object like in the previous article. We will load just one PNG and define class for each tile that should be displayed.

Let’s define one avatar and one box in js/game.js:

const store = new Vuex.Store({
    state: {
        ...,
        gameObjects: [
            {
                name: 'avatar',
                x: 1,
                y: 1
            },
            {
                name: 'box',
                x: 2,
                y: 2
            }
        ]
    }
});

The template for HTML in index.html will iterate over the list. It will set coordinates using top and left CSS attributes. Graphics will be mapped by class name.

<script type="text/x-template" id="playground-template">
    <div>
    ...
    <div v-for="(gameObject, index) in gameObjects"
            :class="['game-object game-object-' + gameObject.name]"
            :style="{ top: gameObject.y*64 + 'px', left: gameObject.x*64 + 'px'}">
    </div>
    </div>
</script>

The last remaining thing is to define picture mapping in css/game.css from tiles.png.

.game-object {
    width: 64px;
    height: 64px;
    position: absolute;
    background: url("../data/images/gfx64/tiles.png") -192px -192px;
}

.game-object-avatar {
    background: url("../data/images/gfx64/tiles.png") -192px 0;
}

.game-object-box {
    background: url("../data/images/gfx64/tiles.png") -128px 0;
}

The result should look like this:

The source code of this article is stored at Github branch article-03.

In the next article, we will add controls to player’s avatar so it could move around the scene.

You can find more HTML5 games at https://georgik.rocks/tag/games

Back to tutorial Sokoban in Vue.js

5. January 2019 at 19:11 - Development (Tags: , , , ). Both comments and pings are currently closed.

Comments are closed.