Skip to content

Instantly share code, notes, and snippets.

@SolarLune
Created March 10, 2024 07:38
Show Gist options
  • Save SolarLune/f8af2f0c750ba54ac3f3d8e02931421d to your computer and use it in GitHub Desktop.
Save SolarLune/f8af2f0c750ba54ac3f3d8e02931421d to your computer and use it in GitHub Desktop.
exampleTileMap.go
// Copyright 2018 The Ebiten Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"image"
"image/color"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/ebitenutil"
"github.com/hajimehoshi/ebiten/v2/inpututil"
)
type Game struct {
layers [][]int
Tilemap *ebiten.Image
}
func NewGame() *Game {
g := &Game{
layers: [][]int{
{
9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 0, 0, 0, 0, 0, 0, 0, 0, 9,
9, 0, 0, 0, 0, 0, 0, 0, 0, 9,
9, 0, 0, 0, 0, 0, 0, 0, 0, 9,
9, 0, 0, 0, 0, 0, 0, 0, 0, 9,
9, 0, 0, 0, 0, 0, 0, 0, 0, 9,
9, 0, 0, 0, 0, 0, 0, 0, 0, 9,
9, 0, 0, 0, 0, 0, 0, 0, 0, 9,
9, 0, 0, 0, 0, 0, 0, 0, 0, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
},
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 260, 0, 0, 0, 0, 0, 0,
},
},
}
tilemapImage, _, _ := ebitenutil.NewImageFromFile("monochrome_tilemap_packed.png")
g.Tilemap = tilemapImage
return g
}
const (
screenWidth = 160
screenHeight = 160
)
const (
tileSize = 16
)
func (g *Game) Update() error {
if inpututil.IsKeyJustPressed(ebiten.KeyF4) {
ebiten.SetFullscreen(!ebiten.IsFullscreen())
}
if inpututil.IsKeyJustPressed(ebiten.KeyEscape) {
return ebiten.Termination
}
return nil
}
func (g *Game) Draw(screen *ebiten.Image) {
screen.Fill(color.Black)
w := g.Tilemap.Bounds().Dx()
tileXCount := w / tileSize
const xCount = screenWidth / tileSize
for _, l := range g.layers {
for i, t := range l {
// Discard 0's so drawing second layers don't overwrite previous layers
if t == 0 {
continue
}
op := &ebiten.DrawImageOptions{}
op.GeoM.Translate(float64((i%xCount)*tileSize), float64((i/xCount)*tileSize))
sx := (t % tileXCount) * tileSize
sy := (t / tileXCount) * tileSize
screen.DrawImage(g.Tilemap.SubImage(image.Rect(sx, sy, sx+tileSize, sy+tileSize)).(*ebiten.Image), op)
}
}
}
func (g *Game) Layout(w, h int) (int, int) {
return screenWidth, screenHeight
}
func main() {
if err := ebiten.RunGame(NewGame()); err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment