mirror of
https://github.com/hajimehoshi/ebiten.git
synced 2024-12-27 04:08:53 +01:00
0300be7d9e
This is not a strict rule, but it is preferrable to use input functions in Update rather than Draw.
101 lines
2.3 KiB
Go
101 lines
2.3 KiB
Go
// Copyright 2015 Hajime Hoshi
|
|
//
|
|
// 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.
|
|
|
|
// +build example
|
|
|
|
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"image"
|
|
_ "image/png"
|
|
"log"
|
|
"strings"
|
|
|
|
"github.com/hajimehoshi/ebiten/v2"
|
|
"github.com/hajimehoshi/ebiten/v2/ebitenutil"
|
|
"github.com/hajimehoshi/ebiten/v2/examples/keyboard/keyboard"
|
|
rkeyboard "github.com/hajimehoshi/ebiten/v2/examples/resources/images/keyboard"
|
|
"github.com/hajimehoshi/ebiten/v2/inpututil"
|
|
)
|
|
|
|
const (
|
|
screenWidth = 320
|
|
screenHeight = 240
|
|
)
|
|
|
|
var keyboardImage *ebiten.Image
|
|
|
|
func init() {
|
|
img, _, err := image.Decode(bytes.NewReader(rkeyboard.Keyboard_png))
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
keyboardImage = ebiten.NewImageFromImage(img)
|
|
}
|
|
|
|
type Game struct {
|
|
keys []ebiten.Key
|
|
}
|
|
|
|
func (g *Game) Update() error {
|
|
g.keys = inpututil.PressedKeys()
|
|
return nil
|
|
}
|
|
|
|
func (g *Game) Draw(screen *ebiten.Image) {
|
|
const (
|
|
offsetX = 24
|
|
offsetY = 40
|
|
)
|
|
|
|
// Draw the base (grayed) keyboard image.
|
|
op := &ebiten.DrawImageOptions{}
|
|
op.GeoM.Translate(offsetX, offsetY)
|
|
op.ColorM.Scale(0.5, 0.5, 0.5, 1)
|
|
screen.DrawImage(keyboardImage, op)
|
|
|
|
// Draw the highlighted keys.
|
|
op = &ebiten.DrawImageOptions{}
|
|
for _, p := range g.keys {
|
|
op.GeoM.Reset()
|
|
r, ok := keyboard.KeyRect(p)
|
|
if !ok {
|
|
continue
|
|
}
|
|
op.GeoM.Translate(float64(r.Min.X), float64(r.Min.Y))
|
|
op.GeoM.Translate(offsetX, offsetY)
|
|
screen.DrawImage(keyboardImage.SubImage(r).(*ebiten.Image), op)
|
|
}
|
|
|
|
keyStrs := []string{}
|
|
for _, p := range g.keys {
|
|
keyStrs = append(keyStrs, p.String())
|
|
}
|
|
ebitenutil.DebugPrint(screen, strings.Join(keyStrs, ", "))
|
|
}
|
|
|
|
func (g *Game) Layout(outsideWidth, outsideHeight int) (int, int) {
|
|
return screenWidth, screenHeight
|
|
}
|
|
|
|
func main() {
|
|
ebiten.SetWindowSize(screenWidth*2, screenHeight*2)
|
|
ebiten.SetWindowTitle("Keyboard (Ebiten Demo)")
|
|
if err := ebiten.RunGame(&Game{}); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|