level.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2021 The Ebiten Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "fmt"
  17. "math/rand/v2"
  18. )
  19. // Level represents a Game level.
  20. type Level struct {
  21. w, h int
  22. tiles [][]*Tile // (Y,X) array of tiles
  23. tileSize int
  24. }
  25. // Tile returns the tile at the provided coordinates, or nil.
  26. func (l *Level) Tile(x, y int) *Tile {
  27. if x >= 0 && y >= 0 && x < l.w && y < l.h {
  28. return l.tiles[y][x]
  29. }
  30. return nil
  31. }
  32. // Size returns the size of the Level.
  33. func (l *Level) Size() (width, height int) {
  34. return l.w, l.h
  35. }
  36. // NewLevel returns a new randomly generated Level.
  37. func NewLevel() (*Level, error) {
  38. // Create a 108x108 Level.
  39. l := &Level{
  40. w: 108,
  41. h: 108,
  42. tileSize: 64,
  43. }
  44. // Load embedded SpriteSheet.
  45. ss, err := LoadSpriteSheet(l.tileSize)
  46. if err != nil {
  47. return nil, fmt.Errorf("failed to load embedded spritesheet: %s", err)
  48. }
  49. // Fill each tile with one or more sprites randomly.
  50. l.tiles = make([][]*Tile, l.h)
  51. for y := 0; y < l.h; y++ {
  52. l.tiles[y] = make([]*Tile, l.w)
  53. for x := 0; x < l.w; x++ {
  54. t := &Tile{}
  55. isBorderSpace := x == 0 || y == 0 || x == l.w-1 || y == l.h-1
  56. val := rand.IntN(1000)
  57. switch {
  58. case isBorderSpace || val < 275:
  59. t.AddSprite(ss.Wall)
  60. case val < 285:
  61. t.AddSprite(ss.Statue)
  62. case val < 288:
  63. t.AddSprite(ss.Crown)
  64. case val < 289:
  65. t.AddSprite(ss.Floor)
  66. t.AddSprite(ss.Tube)
  67. case val < 290:
  68. t.AddSprite(ss.Portal)
  69. default:
  70. t.AddSprite(ss.Floor)
  71. }
  72. l.tiles[y][x] = t
  73. }
  74. }
  75. return l, nil
  76. }