A tiny farm. Walk around the island, plant turnips and watch them grow. Pick the ripe ones into a tower on the farmer's head, then carry it up the steps to the house to sell. It plays with a keyboard, a handheld's buttons or taps, and a help button says what to do and shows the controls for whichever the player uses.
It starts from a new project: see Getting started. The Inspector shows sizes in pixels and code uses meters, with 16 pixels to the meter by default: see Units.
Get the art and the island
The art is Simple Cozy - Farm Asset Pack by Aibyzz. Download the free version and unpack it. Deki does not include it, because its licence does not allow sharing the files. You can use it in your own games, commercial ones too.
The island is a Tiled map, ready to use, in first-game-files.zip. The zip also holds the map's eight tilesets, the HUD's icons and panel and the monogram pixel font. The ground is painted on tile layers, steps included, and everything that stands on it, from the fences to the house, is a tile object on the scenery layer. So is the top of the raised ground's back edge, a second time, so it can be drawn over the farmer and cover her feet when she walks behind it. The tiles are whole blocks whose sides the next tiles hide, so the edge is made of strips 8 pixels tall from the same sheet: the raised_edge_back and raised_edge_front tilesets cut it that way, each drawing its strip that far above its point, so every strip stands on its tile's front corner. The front corner's cliff is there too, as the left half of its tile, from the raised_edge_corner tileset, and the rest of that tile's top as a quarter from raised_edge_quarter.
The collision layer is for the game, not to be seen. It says what is in the way, drawn over the pictures: an ellipse round the foot of each rock, bush, log and tree, and a line along each fence's posts. Three rectangles there have a class: Steps marks where the steps climb, the house's Wall keeps the farmer out of the house, and Door is the ground in front of the door, where turnips are sold. Tiled has no levels, so whatever stands on the raised ground has a custom property, level, set to 1.
Open View → Package Manager and install Tiled Map Editor Integration.
Unpack the zip into your project's assets folder. It makes the folders tilemaps, hud and fonts there.
From the art pack, copy Farm/Free ver.png, Farm/Objects.png and Farm/House.png into assets/tilemaps. The tilesets look for them there.
Drag Player/FPlayer 1 idle.png and Player/FPlayer 1 walking.png onto the Asset Browser.
Select monogram in the Asset Browser and set its Hinting Mode to Mono (1-bit, no AA). A pixel font then draws crisp, with no smoothed edges, like the art around it. It is drawn for size 16: one of its pixels to one on the screen.
The scene
The island is bigger than the screen, so the camera follows the farmer.
Delete Sky.
On Camera, set Clear Color to #BDE8F0 and turn on Pixel Perfect. The art is then scaled by whole numbers only, so on a screen bigger than the game every pixel of it is the same size.
Make an empty object called Map at 0, 8. Add a Tilemap Component and set its Tilemap to farm. Then add a Tilemap Object Spawner, set its Tilemap to farm, Sort Base to 1000 and Sort Per Meter to 16, one order for each pixel row. The spawner is what turns the scenery layer into sprites when the game starts.
Make an empty object called Tap Area, drag it onto Camera and add an Input Collider with Width 640 and Height 480. It covers the screen, and a wider one too, so every tap or click lands on it.
Make two empty objects, Farm and Farmer. Set the Farmer's position to 40, -16 and add a Sprite Component to it. Leave its Sprite empty: the code sets it.
The farm
The map holds the island, so this script is only the game: where the soil is, how the turnips grow, the score, where the farmer can walk and the way from one spot to another. Create a script called Farm.
src/Farm.h:
#pragma once
#include <deki/Engine.h>
#include <deki/assets/AssetRef.h>
#include <deki/providers/Buffer.h>
#include <deki/reflection/ObjectRef.h>
#include <cmath>
#include "SpriteBatchComponent.h"
#include "SpriteComponent.h"
#include "Tilemap.h"
#include "TextComponent.h"
DEKI_CATEGORY("Game")
DEKI_DESCRIPTION("Grows the turnips, counts the ones sold and says where the farmer can walk.")
class Farm : public Deki::Component
{
public:
DEKI_EXPORT
Deki::AssetRef<Deki2D::Sprite> farmSheet;
DEKI_EXPORT
Deki::AssetRef<DekiTiledMap::Tilemap> map;
DEKI_EXPORT
Deki::ObjectRef<Deki2D::TextComponent> scoreText;
DEKI_EXPORT
float secondsPerStage = 2.0f;
void Start() override;
void Update() override;
// How high the ground is at this point, given as if it were on the lower
// ground: 0 there, 1 on the raised ground and in between on the steps.
// -1 where no one can stand. With a clearance, in squares, whatever is in
// the way is that much bigger: for planning a walk that is not to graze it.
float GroundHeight(float x, float y, float clearance = 0.0f) const;
// Finds the way from one point to the spot nearest another that can be
// reached, round whatever is in between. False when there is none.
The soil and the turnips are pieces of two Sprite Batch components. Add places a rectangle of the sheet, so nothing needs cutting up first, and returns the piece's number. SetFrameRect and SetVisible change that piece later. Twenty patches are two objects where they would be forty, which a small device feels, and each piece still sorts on its own: the farmer walks in front of one turnip and behind the next.
A column and a row name a square on the island: columns run down and to the right, rows down and to the left. WorldX and WorldY turn them into a position, and ColumnAt and RowAt do the reverse. ReadMap reads the collision layer's shapes once, with FindProperty for each one's level, and leaves the tile objects, the pictures, to the spawner. GroundHeight says how high the ground is at a point: 0 on the lower ground, 1 on the raised ground and in between on the steps. It keeps the farmer on the island and out of everything on her level: a Wall over its whole area, a rock or a tree inside its ellipse, a fence along its line. Her feet have a width, kFeetHalfWidth to each side across the screen, and all of it has to stand on the same ground: so no part of her is inside the cliff or a wall, and on the raised ground she stops before her feet hang over its edge. Behind the raised ground she walks right up to its back wall, where its edge covers her feet, so she looks to stand below it.
A tap can be on the other side of a fence, so the farm finds the way round. FindWays works out once, at the start, which squares can be walked between: CanWalk tries the straight line from the middle of one to the middle of the next with GroundHeight, so whatever stops the farmer stops the way too, and the steps are the only way up. Flood then spreads from one square to all it can reach, a square further each round, and every square learns how many squares away it is. FindWay floods twice: from the farmer, to find the square nearest the tap that she can reach at all, and from that square, so that walking to any square with a smaller number leads there. Squares are joined only to the four beside them: one that meets a square at a corner is straight up, down, left or right of it on the screen, and she never walks that way. NextPoint hands the way out a point at a time: the goal itself when the way there is clear, otherwise the middle of a square. It starts from the best square around her and looks on along the way, a square nearer the goal each time, for as long as she could still get there with a little room to spare. So she walks in long lines and turns only where something is in the way. Every point goes through AlongTheSquares, which lays a line the keys could not walk as two they can, one along each way of the squares, and only counts the way clear when nothing is in the way of either. So a tapped walk, with a mouse or a finger, moves in the same whole-pixel steps and faces the same four ways as the keys.
UseSoil plants on an empty patch and picks a ripe turnip, when the farmer says she has room for one more. The count on screen is of turnips sold: IsAtDoor says when she stands on the map's Door area, and Sell counts one.
DrawOrder is what makes the farmer walk behind the trees and in front of the turnips: lower on the screen draws on top. It matches the spawner's Sort Base and Sort Per Meter, so the farmer and the scenery sort together. The spawner sorts a tile object by its point. The house's point is inside its walls, and its tileset's Tile Offset draws the picture from there. A fence, a log or the house is wider than one point, though: part of it can be lower on the screen than her feet while she stands behind it. DrawOrderAt sorts her against its line, or against the house's walls, instead: in front of all of it or behind all of it, by which side she is on. In the corner of two fences she is in front of one and behind the other, and in front wins for the post they share. The pieces of the raised ground's edge are sorted the same way, by where she is: they cover her only while she is on the lower ground behind it, and anywhere else, on top of it or in front of its cliff, she draws over them. Beside a corner, of the cliff or of the house, she counts as behind it until all her width is past, so her side comes out from behind the corner instead of jumping in front of it.
The farmer
Create a script called Farmer.
src/Farmer.h:
#pragma once
#include <deki/Engine.h>
#include <deki/assets/AssetRef.h>
#include <deki/reflection/ObjectRef.h>
#include "CameraComponent.h"
#include "Farm.h"
#include "InputCollider.h"
#include "SpriteBatchComponent.h"
#include "SpriteComponent.h"
DEKI_CATEGORY("Game")
DEKI_DESCRIPTION("Walks with the arrow keys or to a tapped spot, runs while B is held, and carries the turnips she "
Arrows and Space are the keyboard. A handheld's D-pad arrives as the arrows too, and its A button as Enter, so Update takes Enter as well as Space: see Input. She runs while B is held: the B key, or a handheld's B button, which arrives as Esc. A trackball, like the LilyGO T-Deck's, arrives as arrows pressed for a single frame at each step of the ball. Steered lets a press that short carry on for a moment, so rolling the ball is one walk and not a row of single steps. A key that is held stops when it is let go.
A tap, a click or a touch lands on the Tap Area. Start adds a listener to its onPointerDown, which gets the spot in world meters, and WalkTo asks the farm for the way there. Update then walks straight to each point the farm hands out, through the gate or up the steps when that is the way, and uses the soil if the tap was on it. A tap on a fence or inside the house takes her as near as she can get.
The farmer remembers how high she has climbed. Ground more than half a level higher or lower than her is refused, so the cliff stops her and only the steps take her up. Walked into the corner of something, she slips round it: when the way is clear up to half a square to one side, she glides that way, half a step forward and half to the side, instead of stopping. So a corner by a pixel does not catch her, and she slides straight along a slanted edge rather than zigzagging.
The sheet has eight rows and four frames in each: she faces left, right, down and up in the first four rows, and the four diagonals in the rest. RowFacing picks the row for the way she is going, and going along the island's squares is a diagonal. A turn waits a twentieth of a second, so one frame's step aside does not flick her round. She walks along the island's squares, the way the ground is laid: Up goes up-right, Right down-right, Down down-left and Left up-left. Two held together are a corner of the pad, and point one of those ways on the screen as a stick does: Up and Right go up-right, Right and Down down-right, Down and Left down-left, Left and Up up-left. Each of those is two pixels across for one up or down, so every way is the same length and she walks at one pace. She steps every frame, by as much as Speed says, so the screen moves a little each frame and never a lot every other. m_X and m_Ground keep exactly where she is, and WholePixel picks the pixel she is shown on, so any Speed walks as evenly as pixels allow: two frames' steps are never more than a pixel apart. At 3.75 every step is the same, one pixel across every frame and one up or down every other, the stairs a slanted line is drawn in, and at 7.5 two across and one up. Frames are not all as long, so the pace goes by a frame's usual length, and one that is all but a whole number of half pixels a frame is made exactly that. The camera stays on her: she is always in the middle of the screen and the map moves under her, a step of the map for each step of hers. A handheld's stick walks the same ways as the keys: pushed up-right or straight up she goes up-right, down-right or straight right down-right, and so on round, so each way has a quarter of the circle and the same push always goes the same way. Near the edge of a quarter it keeps the way it had. DekiInput::GetStick reads it, from the handheld or a gamepad, and the Play view passes a gamepad's on. The frame comes from a clock that counts with the ground she covers, not with time, so her feet do not slide when Speed changes, and she stands when something is in her way.
The tower is one more sprite batch: eight ripe turnips, of which only the ones she carries are shown. Use adds one each time UseSoil picks, and drops it onto the tower from above. CarryTower places them above her head every frame. The lean is a spring: it is pulled back from the way she walks, so the tower lags when she sets off, bends further the higher it goes, and swings past upright a few times when she stops. It leans over the ground, as she walks: walking up the island it tips towards you, down it tips away, and on the screen a lean up or down is half as long as one across, as the squares are. Each turnip also hops with her steps, a little after the one below it. In front of the door CarryTower takes one off the top every eighth of a second and sells it.
The HUD
The HUD goes under the camera, and a Screen Anchor keeps each part of it at a corner of the screen, whatever the screen's size. Every panel is the same small picture, raised-panel, from the zip. It is a Procedural Sprite: the editor draws it from the numbers in its Inspector, here a face with an outline and a darker band along the bottom, which gives it the raised look of the keys. A Sprite Component in Nine Slice mode stretches its middle to any size and keeps its corners.
Positions and sizes are in pixels, as the Inspector shows them. Set every Text Component's Font to monogram, Align to Left, Vertical Align to Cap Center and Color to #6B4024. The score uses Pixel Scale 2, which doubles every pixel of the font and keeps it crisp. "Order" is the Sorting Order.
The turnip counter sits in the top left corner. Make an empty object called Counter under Camera. Its position is set by the anchor.
Under it. Score is the Hello text: rename it and drag it onto Counter.
Object
Position
Add
Turnip Icon
-16, 3
Sprite Component: turnip, order 1992
Score (Hello, renamed)
13, 0
Text Component: 0, Font Size 16, Pixel Scale 2, 32 × 28, order 1992
The help sits behind a button in the top right corner. Make an empty object called Help Button under Tap Area: an object under another gets a tap before it, so a tap on the button does not also send the farmer there.
Text Component: ?, AlignCenter, Font Size 16, Pixel Scale 2, 28 × 28, order 1992
The popup goes under the button too, for the same reason: while it is open it gets every tap first. Make an empty object called Help under Help Button.
Under it, every one with order 1994. Set Align to Center on these Text Components:
Object
Position
Add
Title
0, 54
Text Component: How to play, Font Size 16, Pixel Scale 2, 232 × 28
Plant Line
0, 30
Text Component: Plant turnips on the soil., Font Size 16, 232 × 14
Pick Line
0, 16
Text Component: Pick the ripe ones: they stack up., Font Size 16, 232 × 14
Sell Line
0, 2
Text Component: Sell the tower at the house door., Font Size 16, 232 × 14
Close Line
0, -58
Text Component: Tab, Y or a tap closes this., Font Size 16, 232 × 14
The controls are three rows in the same place, one for each way to play, and a script shows the one that matches. Each row is its first icon, with the rest under it. These labels keep AlignLeft.
Object
Position
Add
Keys Hint
-82, -30
Sprite Component: arrow-keys
Under it:
Object
Position
Add
Walk Label
39, 0
Text Component: Walk, Font Size 16, 26 × 36
Space Key
78, 0
Sprite Component: space-key
Use Label
139, 0
Text Component: Plant, pick, Font Size 16, 66 × 36
Object
Position
Add
Buttons Hint
-68, -30
Sprite Component: d-pad
Under it:
Object
Position
Add
Walk Label
31, 0
Text Component: Walk, Font Size 16, 26 × 36
A Button
55, 0
Sprite Component: a-button
Use Label
101, 0
Text Component: Plant, pick, Font Size 16, 66 × 36
Object
Position
Add
Tap Hint
-63, -30
Sprite Component: tap
Under it:
Object
Position
Add
Tap Label
74, 0
Text Component: Tap to walk and farm, Font Size 16, 120 × 36
Create a script called Help, and add the Help component to Help Button.
src/Help.h:
#pragma once
#include <deki/Engine.h>
#include <deki/reflection/ObjectRef.h>
#include "InputCollider.h"
DEKI_CATEGORY("Game")
DEKI_DESCRIPTION("Opens the help when its button is tapped or Tab is pressed. A tap or Tab closes it.")
class Help : public Deki::Component
{
public:
DEKI_EXPORT
Deki::ObjectRef<DekiInput::InputCollider> popup;
~Help() override;
void Start() override;
private:
void Show(bool shown);
size_t m_Listener = 0;
};
src/Help.cpp:
#include "Help.h"
#include "DekiInput.h"
#include "Keys.h"
void Help::Start()
{
Show(false);
// A tap on the button opens the help. Its collider covers the screen and
// it is under the button, so while it is open it gets every tap first:
// any tap closes it, and none reaches the farm behind.
Start hides the popup and listens to the two colliders: a tap on the button opens the help, and any tap while it is open closes it. Tab does both from a keyboard, and from a handheld, where it is the Y button. The destructor stops listening to the keys, or the callback would be called on a component that is gone.
Create a script called ControlsHint, and add the Controls Hint component to Help Button as well: the button is always there, so it hears every key and tap, also while the popup is closed.
src/ControlsHint.h:
#pragma once
#include <deki/Engine.h>
#include <deki/reflection/ObjectRef.h>
#include "SpriteComponent.h"
DEKI_CATEGORY("Game")
DEKI_DESCRIPTION("Shows the controls for what the player last used: the keyboard, a handheld's buttons or taps.")
for (Deki::ObjectRef<Deki2D::SpriteComponent>* each : { &keysHint, &buttonsHint, &tapHint })
{
each->GetObject()->SetActive(each == &hint);
}
}
Start picks the row from the inputs the device has: GetInput("Miyoo") finds the Miyoo Mini's buttons, and DekiDisplayTouch is a touchscreen. After that it follows the player. Every input event names what sent it, so a key from the Miyoo shows the buttons, any other key shows the keyboard, and a pointer going down, which is a tap or a click, shows the tap row.
Connect it
Add the Farm component to the Farm object and fill in its fields.
Farm's fields in the Inspector
Field
Set it to
Farm Sheet
Free ver
Map
farm
Score Text
The Score object
Add the Farmer component to the Farmer object. Set Farm to the Farm object, Camera to the Camera object, Tap Area to the Tap Area object, Idle Sheet to FPlayer 1 idle and Walk Sheet to FPlayer 1 walking.
On Help Button, set the Help's Popup to the Help object, and the Controls Hint's Keys Hint, Buttons Hint and Tap Hint to the three rows.
Save with Ctrl+S and press Run.
Take it further
Change the pace.Seconds Per Stage on the Farm is how fast turnips grow, Speed on the Farmer is how fast she walks and Run Speed how fast she runs, and kMostCarried in Farmer.cpp is how tall the tower gets. The constants beside it set how much the tower leans, swings and hops.
Rearrange the island. Open farm.tmj in Tiled to paint the ground or move things on the scenery layer, and their shapes on the collision layer with them. Deki picks up the map when you save it.
Restyle the HUD. Select raised-panel in the Asset Browser and change its colors, Border Radius or Depth. Every panel follows.
Change the farmer. The pack also has MPlayer 1 idle and MPlayer 1 walking, with the same layout.
Build more. The pack's paid version adds water, waterfalls and fruit trees.
Put it on a device. Follow the last part of Getting started. In Project Settings → Rendering, turn on Redraw Changes: the camera stays on whole pixels, so each frame moves the last one and draws only the edge it uncovers and what changed. Then use the Speed tools to see what a frame costs there.