Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "errors"
- "log"
- "math/rand"
- "time"
- "github.com/hajimehoshi/ebiten"
- "github.com/hajimehoshi/ebiten/ebitenutil"
- )
- const (
- SCREEN_WIDTH = 320
- SCREEN_HEIGHT = 240
- SCALE_FACTOR = 2
- APP_TITLE = "Draw Items"
- )
- var image *ebiten.Image
- var sprites Sprites
- var random = rand.New(rand.NewSource(time.Now().UnixNano()))
- type Sprite struct {
- img *ebiten.Image
- x int
- y int
- }
- func NewSprite(image *ebiten.Image, x int, y int) (*Sprite, error) {
- s := new(Sprite)
- s.img = image
- err := s.SetX(x)
- if err != nil {
- return s, err
- }
- err = s.SetY(y)
- if err != nil {
- return s, err
- }
- return s, nil
- }
- func (s *Sprite) SetX(x int) error {
- w, _ := s.img.Size()
- if x < 0 || x > SCREEN_WIDTH-w {
- return errors.New("Invalid x value")
- }
- s.x = x
- return nil
- }
- func (s *Sprite) SetY(y int) error {
- _, h := s.img.Size()
- if y < 0 || y > SCREEN_HEIGHT-h {
- return errors.New("Invalid y value")
- }
- s.y = y
- return nil
- }
- type Sprites struct {
- sprites []*Sprite
- }
- // Mandatory method for ImageParts interface
- func (s *Sprites) Len() int {
- return len(s.sprites)
- }
- // Mandatory method for ImageParts interface
- func (s *Sprites) Dst(i int) (x0, y0, x1, y1 int) {
- if s.Len() <= i {
- return 0, 0, 0, 0
- }
- ss := s.sprites[i]
- w, h := ss.img.Size()
- return ss.x, ss.y, ss.x + w, ss.y + h
- }
- // Mandatory method for ImageParts interface
- func (s *Sprites) Src(i int) (x0, y0, x1, y1 int) {
- if s.Len() <= i {
- return 0, 0, 0, 0
- }
- ss := s.sprites[i]
- w, h := ss.img.Size()
- return 0, 0, w, h
- }
- func (s *Sprites) Append(ss *Sprite) {
- s.sprites = append(s.sprites, ss)
- }
- func (s *Sprites) Init() error {
- numOfBottles := random.Intn(7) + 4
- w, h := image.Size()
- for i := 0; i < numOfBottles; i++ {
- x := random.Intn(SCREEN_WIDTH - w)
- y := random.Intn(SCREEN_HEIGHT - h)
- ss, err := NewSprite(image, x, y)
- if err != nil {
- return err
- }
- s.Append(ss)
- }
- return nil
- }
- func (s *Sprites) Update(screen *ebiten.Image) error {
- // Shared DrawImageOptions obj for Sprites
- op := &ebiten.DrawImageOptions{
- ImageParts: s,
- }
- // In this program, all bottle images share the same image file
- if err := screen.DrawImage(image, op); err != nil {
- return err
- }
- return nil
- }
- func init() {
- var err error
- image, _, err = ebitenutil.NewImageFromFile("beerBottle.png",
- ebiten.FilterNearest)
- if err != nil {
- log.Fatal(err)
- }
- sprites = Sprites{}
- if err = sprites.Init(); err != nil {
- log.Fatal(err)
- }
- }
- func update(screen *ebiten.Image) error {
- if err := sprites.Update(screen); err != nil {
- return err
- }
- return nil
- }
- func main() {
- ebiten.Run(update, SCREEN_WIDTH, SCREEN_HEIGHT, SCALE_FACTOR, APP_TITLE)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement