Compare commits

...

48 Commits

Author SHA1 Message Date
365e9dbbbb Added solver & optimized state.
Positions are kept by index only.
2020-01-16 07:33:04 +01:00
8fc459e1d6 Added path finder & visualization (F5). 2020-01-15 21:49:01 +01:00
93be82bdbd Moved level state to soko package.
Renamed entity type character and egg to player and target respectively.
2020-01-15 21:25:32 +01:00
1e9d3e9089 Renamed Tile to TileType. 2020-01-15 19:51:57 +01:00
cb81ced655 Moved tile & entity type to separate code unit. 2020-01-15 19:06:06 +01:00
a4058df9c8 Moved level to separate package (soko).
Moved lineparser to gut package.
2020-01-15 19:03:52 +01:00
a19d33cb9f Changed behaviour of player after brick has been sunken.
- Previously the player would stop on the current tile even if the correct key was pressed. Now the movement continues without interruption.
2020-01-14 19:35:52 +01:00
041cdccc3f Changed behaviour of movement.
- Every movement key at any moment is valid if it is the only movement key pressed (when the previous move is finished).
2020-01-14 19:34:02 +01:00
cdb581d0f6 Added level pack selection. 2020-01-14 19:12:43 +01:00
0203539201 Can load more than a single level pack (but not play yet). 2020-01-14 18:53:15 +01:00
fd92207400 Changed structure of levels/packs. 2020-01-14 18:38:42 +01:00
46e3ac060a Changed Mkdir command to give more rights. 2019-12-31 13:38:10 +01:00
2b58bf1d7f Fixed bug where you weren't able to get past level select menu. 2019-12-31 12:22:57 +01:00
3dbb74ac77 Updated README. 2019-12-31 12:11:54 +01:00
cbf18822be Updated README. 2019-12-31 11:51:25 +01:00
c61f074465 Escape will go back to main menu in the level selection menu. 2019-12-31 11:43:42 +01:00
449873f6b8 Added title on main menu.
Changed "Apply" button into "OK" (settings menu).
2019-12-31 11:27:55 +01:00
4b393610e2 Fixed bug in rendering of console.
- All messages were rendered (outside bounds of the bitmap). Now only rendering (partially) visible messages.
2019-12-31 11:22:18 +01:00
30999c944a Updated dragon sprite & changed villain into an egg. 2019-12-31 11:21:31 +01:00
70ce0da074 Added README. 2019-12-29 23:34:28 +01:00
72aab5509e Added title. 2019-12-29 23:29:34 +01:00
88a02f0f9b Disabled initialization of audio. 2019-12-29 22:29:18 +01:00
03685f9a33 Changed order of apply/cancel in settings view.
Escape now exits settings directly.
2019-12-29 22:06:38 +01:00
6eed028d82 Added 2 levels. 2019-12-29 18:11:04 +01:00
3fb808ba78 Fixed bug where player isn't able walk when any animation is playing. 2019-12-29 17:29:33 +01:00
8d8753f008 Only keeping the last 1000 log messages in console. 2019-12-29 17:25:59 +01:00
d8c0f489aa Added particles on splash. 2019-12-29 17:25:41 +01:00
a4ab1a265e Added entityList.
Moved animations to separate code unit.
2019-12-29 15:32:01 +01:00
214d08f2b3 Add sinking animation for brick. 2019-12-29 14:49:54 +01:00
95bc1367c7 Added an icon. 2019-12-29 13:11:50 +01:00
63ffc04017 Changed perspective of tiles. 2019-12-29 12:53:12 +01:00
c4fc256c19 Added tool to warp tiles. 2019-12-29 12:52:37 +01:00
1f26980ba3 Added progress tracking. 2019-12-29 10:57:20 +01:00
8ef4e4ea3a Changed movement animation again.
Movement starts on KeyDownEvent instead of KeyCharEvent.
2019-12-29 10:15:32 +01:00
3488bb3767 Updated color of brick. 2019-12-29 10:01:57 +01:00
356b510286 Added win condition.
Renamed entities on disk & added missing sprites.
Moved entity and animations to separate code unit.
2019-12-29 10:01:34 +01:00
aa47e2cabb Added header font. 2019-12-29 09:59:14 +01:00
8d7ec272b6 Added margins control. 2019-12-29 09:53:43 +01:00
a08f961e80 Added support for level packs.
Added level selection.
2019-12-28 21:20:56 +01:00
5c30a4bc01 Increased move animation a little. 2019-12-28 19:36:48 +01:00
efea350ae9 Added second (bigger) level.
Level is automatically scaled to available space.
2019-12-28 18:40:40 +01:00
3d4df7e956 Removed terminal output by default. - Compiling with the tag "debug" will still show console output. 2019-12-28 17:09:19 +01:00
11e49d1249 Fixed Escape not working in the menu when playing the game. 2019-12-28 16:14:42 +01:00
11ab3fca0f Added settings in-game.
Added video settings.
Added and improved reusable controls.
Separated drawing of sprites.
Fixed bug that text was right aligned instead of left aligned.
2019-12-28 16:03:57 +01:00
27ad0453c3 Improved movement.
- Now listening on key-char event instead of key-down.
2019-12-28 00:02:54 +01:00
856069d5b2 !fixup 2019-12-27 23:53:34 +01:00
cc58dbd06f Some small visual fixes.
- Smaller font for menus/steps.
- Changed level a bit.
- Updated lava brick texture.
2019-12-27 23:44:57 +01:00
cc59236689 Added new tile graphics.
Added sprites for all textures.
Removed splash screen animation.
2019-12-27 22:54:00 +01:00
85 changed files with 3531 additions and 668 deletions

1
.gitignore vendored
View File

@ -8,3 +8,4 @@ rice-box.go
# Application # Application
cmd/krampus19/res/_sandbox/ cmd/krampus19/res/_sandbox/
cmd/krampus19/TODO

356
README.md Normal file
View File

@ -0,0 +1,356 @@
# Sokodragon
This game was made for RmBeer, his wishlist:
```
1) DRAGONS!!! HUNDREDS AND HUNDREDS, NO, THOUSANDS OF DRAGONS!!!!!! I LOVE DRAGONS AND I WANT SEE ALL!!!!! I WANT A DRAGON LIKE THE MAIN CHARACTER!!!!! \o/
2) Include morbid scenes, gores or bloody, where humans are destroyed as part of the game. ^^
3) Make a good story for the game! :D
4) That is an action game, strategy, or logical problem, can be any of the 3 or all the 3. I like games to think and solve, because they are more challenging. :) (no like puzzle with part of images and no like questions games)
It may be difficult to create 1000 dragons, I settle for one or some if it's difficult for you. :)
```
Safe to say I failed miserably to meet the requirements. The game features a single dragon and it is a puzzle game which satifies rules 1) and 4). The idea was to let the dragon have to get to a human/villain type (instead of the egg now) but drawing this was too challenging. Didn't think about a good story yet. Nevertheless: I hope you enjoy solving the 4 puzzles added.
## Building
Prerequisites:
- [Allegro](https://liballeg.org/) 5.2 (development libraries).
- [Go](https://golang.org/dl/) 1.12 or later.
- GCC.
- Git.
With all prequisites installed you can run:
```
go get -u opslag.de/schobers/krampus19/cmd/krampus19
```
The generated binary can be found in `$GOPATH/bin` and will depend on the dynamic runtimes and the resources found in `$GOPATH/src/opslag.de/schobers/krampus19/cmd/krampus19/res`.
### Sources
Can be found at https://opslag.de/schobers/krampus19 (Git repository).
### Embedding resources
```
go get -u github.com/GeertJohan/go.rice/rice
go get -u opslag.de/schobers/krampus19/cmd/krampus19
go generate opslag.de/schobers/krampus19/cmd/krampus19
go install opslag.de/schobers/krampus19/cmd/krampus19
```
Note that `go get` of the `rice` tool is only required once.
### Usefull flags
`go install` can be executed with the following flags (on Windows):
- `-tags "static"`: to link against Allegro statically.
- `-tags "console"`: to show the console output in stdout.
- `-ldflags "-s -w"`: to reduce the binary size.
Example:
```
go install -tags "static console" -ldflags "-s -w" opslag.de/schobers/krampus19/cmd/krampus19
```
## Settings
- Video settings are only taken into account when the game is restarted. The resolution only applies to fullscreen mode (the "Windowed" setting must be unchecked).
## Licenses
### Fira Mono font
Copyright (c) 2012-2013, The Mozilla Corporation and Telefonica S.A.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
### Open Sans font
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

View File

@ -14,6 +14,12 @@ type Button struct {
TextAlign allg5.HorizontalAlignment TextAlign allg5.HorizontalAlignment
} }
func NewButton(text string, onClick func()) *Button {
b := &Button{Text: text}
b.OnClick = onClick
return b
}
func (b *Button) DesiredSize(ctx *Context) geom.PointF32 { func (b *Button) DesiredSize(ctx *Context) geom.PointF32 {
font := ctx.Fonts.Get(b.Font) font := ctx.Fonts.Get(b.Font)
w := font.TextWidth(b.Text) w := font.TextWidth(b.Text)

23
alui/center.go Normal file
View File

@ -0,0 +1,23 @@
package alui
import (
"opslag.de/schobers/geom"
)
type center struct {
Proxy
}
func Center(control Control) Control {
return &center{Proxy: Proxy{Target: control}}
}
func (c *center) Layout(ctx *Context, bounds geom.RectangleF32) {
size := c.DesiredSize(ctx)
center := bounds.Center()
size.X = geom.Min32(size.X, bounds.Dx())
size.Y = geom.Min32(size.Y, bounds.Dy())
size = size.Mul(.5)
c.Proxy.Layout(ctx, geom.RectF32(center.X-size.X, center.Y-size.Y, center.X+size.X, center.Y+size.Y))
}

34
alui/column.go Normal file
View File

@ -0,0 +1,34 @@
package alui
import "opslag.de/schobers/geom"
type Column struct {
Proxy
panel *StackPanel
}
func NewColumn() *Column {
c := &Column{}
c.Init()
return c
}
func (c *Column) AddChild(child ...Control) {
c.panel.Children = append(c.panel.Children, child...)
}
func (c *Column) Init() {
c.panel = &StackPanel{Orientation: OrientationVertical}
c.Proxy.Target = c.panel
}
func (c *Column) Layout(ctx *Context, bounds geom.RectangleF32) {}
func (c *Column) Render(ctx *Context, bounds geom.RectangleF32) {
columnHeight := c.Proxy.DesiredSize(ctx).Y
width, center := bounds.Dx(), bounds.Center()
columnBounds := geom.RectF32(.25*width, center.Y-.5*columnHeight, .75*width, center.Y+.5*columnHeight)
c.Proxy.Layout(ctx, columnBounds)
c.Proxy.Render(ctx, columnBounds)
}

View File

@ -11,11 +11,8 @@ type Container struct {
Children []Control Children []Control
} }
func (c *Container) Handle(e allg5.Event) { func (c *Container) AddChild(child ...Control) {
c.ControlBase.Handle(e) c.Children = append(c.Children, child...)
for _, child := range c.Children {
child.Handle(e)
}
} }
func (c *Container) DesiredSize(ctx *Context) geom.PointF32 { func (c *Container) DesiredSize(ctx *Context) geom.PointF32 {
@ -36,6 +33,13 @@ func (c *Container) DesiredSize(ctx *Context) geom.PointF32 {
return size return size
} }
func (c *Container) Handle(e allg5.Event) {
c.ControlBase.Handle(e)
for _, child := range c.Children {
child.Handle(e)
}
}
func (c *Container) Layout(ctx *Context, bounds geom.RectangleF32) { func (c *Container) Layout(ctx *Context, bounds geom.RectangleF32) {
c.ControlBase.Layout(ctx, bounds) c.ControlBase.Layout(ctx, bounds)
for _, child := range c.Children { for _, child := range c.Children {

View File

@ -44,7 +44,7 @@ func (f *Fonts) DrawAlignFont(font *allg5.Font, left, top, right float32, color
font.Draw(right, top, color, allg5.AlignRight, text) font.Draw(right, top, color, allg5.AlignRight, text)
default: default:
left, top = geom.Round32(left), geom.Round32(top) left, top = geom.Round32(left), geom.Round32(top)
font.Draw(left, top, color, allg5.AlignRight, text) font.Draw(left, top, color, allg5.AlignLeft, text)
} }
} }

View File

@ -11,6 +11,7 @@ type Label struct {
ControlBase ControlBase
Text string Text string
TextAlign allg5.HorizontalAlignment
} }
func (l *Label) DesiredSize(ctx *Context) geom.PointF32 { func (l *Label) DesiredSize(ctx *Context) geom.PointF32 {
@ -29,5 +30,5 @@ func (l *Label) Render(ctx *Context, bounds geom.RectangleF32) {
if back != nil { if back != nil {
allg5.DrawFilledRectangle(bounds.Min.X, bounds.Min.Y, bounds.Max.X, bounds.Max.Y, *back) allg5.DrawFilledRectangle(bounds.Min.X, bounds.Min.Y, bounds.Max.X, bounds.Max.Y, *back)
} }
ctx.Fonts.Draw(l.Font, bounds.Min.X+4, bounds.Min.Y+4, *fore, l.Text) ctx.Fonts.DrawAlign(l.Font, bounds.Min.X+4, bounds.Min.Y+4, bounds.Max.X-4, *fore, l.TextAlign, l.Text)
} }

53
alui/margins.go Normal file
View File

@ -0,0 +1,53 @@
package alui
import (
"opslag.de/schobers/geom"
)
var _ Control = &Margins{}
type Margins struct {
Proxy
Top, Left, Bottom, Right float32
bounds geom.RectangleF32
}
func NewMargins(target Control, margins ...float32) *Margins {
m := &Margins{Proxy: Proxy{Target: target}}
switch len(margins) {
case 1:
m.Top, m.Left, m.Bottom, m.Right = margins[0], margins[0], margins[0], margins[0]
case 2:
m.Top, m.Left, m.Bottom, m.Right = margins[0], margins[1], margins[0], margins[1]
case 3:
m.Top, m.Left, m.Bottom, m.Right = margins[0], margins[1], margins[2], margins[1]
case 4:
m.Top, m.Left, m.Bottom, m.Right = margins[0], margins[1], margins[2], margins[3]
default:
panic("expected 1 (all same), 2 (vertical, horizontal), 3 (top, horizontal, bottom) or 4 margins (all separately specified)")
}
return m
}
func (m *Margins) Bounds() geom.RectangleF32 { return m.bounds }
func (m *Margins) DesiredSize(ctx *Context) geom.PointF32 {
return m.Proxy.DesiredSize(ctx).Add2D(m.Left+m.Right, m.Top+m.Bottom)
}
func (m *Margins) inset(bounds geom.RectangleF32) geom.RectangleF32 {
return geom.RectF32(bounds.Min.X+m.Left, bounds.Min.Y+m.Top, bounds.Max.X-m.Right, bounds.Max.Y-m.Bottom)
}
func (m *Margins) Layout(ctx *Context, bounds geom.RectangleF32) {
m.bounds = bounds
target := m.inset(bounds)
m.Proxy.Layout(ctx, target)
}
func (m *Margins) Render(ctx *Context, bounds geom.RectangleF32) {
target := m.inset(bounds)
m.Proxy.Render(ctx, target)
}

View File

@ -2,13 +2,13 @@ package alui
import ( import (
"opslag.de/schobers/allg5" "opslag.de/schobers/allg5"
"opslag.de/schobers/geom"
) )
type Menu struct { type Menu struct {
Proxy Column
OnEscape func()
panel *StackPanel
active int active int
buttons []*Button buttons []*Button
} }
@ -19,11 +19,6 @@ func NewMenu() *Menu {
return m return m
} }
func (m *Menu) Init() {
m.panel = &StackPanel{Orientation: OrientationVertical}
m.Proxy.Target = m.panel
}
func (m *Menu) Activate(i int) { func (m *Menu) Activate(i int) {
if len(m.buttons) == 0 || i < 0 { if len(m.buttons) == 0 || i < 0 {
return return
@ -42,17 +37,24 @@ func (m *Menu) Add(text string, onClick func()) {
button.Over = true button.Over = true
} }
m.buttons = append(m.buttons, button) m.buttons = append(m.buttons, button)
m.panel.Children = append(m.panel.Children, button) m.AddChild(button)
} }
func (m *Menu) Handle(e allg5.Event) { func (m *Menu) Handle(e allg5.Event) {
m.Proxy.Handle(e) m.Column.Handle(e)
if len(m.buttons) == 0 { if len(m.buttons) == 0 {
return return
} }
switch e := e.(type) { switch e := e.(type) {
case *allg5.KeyDownEvent:
switch e.KeyCode {
case allg5.KeyEscape:
if onEscape := m.OnEscape; onEscape != nil {
onEscape()
}
}
case *allg5.KeyCharEvent: case *allg5.KeyCharEvent:
switch e.KeyCode { switch e.KeyCode {
case allg5.KeyDown: case allg5.KeyDown:
@ -75,16 +77,6 @@ func (m *Menu) Handle(e allg5.Event) {
} }
} }
func (m *Menu) Layout(ctx *Context, bounds geom.RectangleF32) {}
func (m *Menu) Render(ctx *Context, bounds geom.RectangleF32) {
menuHeight := m.Proxy.DesiredSize(ctx).Y
width, center := bounds.Dx(), bounds.Center()
menuBounds := geom.RectF32(.25*width, center.Y-.5*menuHeight, .75*width, center.Y+.5*menuHeight)
m.Proxy.Layout(ctx, menuBounds)
m.Proxy.Render(ctx, menuBounds)
}
func (m *Menu) updateActiveButton(active int) { func (m *Menu) updateActiveButton(active int) {
m.active = active m.active = active
for i, btn := range m.buttons { for i, btn := range m.buttons {

View File

@ -31,14 +31,14 @@ func (p *Proxy) Handle(e allg5.Event) {
} }
} }
func (p *Proxy) Render(ctx *Context, bounds geom.RectangleF32) {
if p.Target != nil {
p.Target.Render(ctx, bounds)
}
}
func (p *Proxy) Layout(ctx *Context, bounds geom.RectangleF32) { func (p *Proxy) Layout(ctx *Context, bounds geom.RectangleF32) {
if p.Target != nil { if p.Target != nil {
p.Target.Layout(ctx, bounds) p.Target.Layout(ctx, bounds)
} }
} }
func (p *Proxy) Render(ctx *Context, bounds geom.RectangleF32) {
if p.Target != nil {
p.Target.Render(ctx, bounds)
}
}

View File

@ -13,10 +13,6 @@ type StackPanel struct {
Orientation Orientation Orientation Orientation
} }
func (s *StackPanel) Handle(e allg5.Event) {
s.Container.Handle(e)
}
func (s *StackPanel) asLength(p geom.PointF32) float32 { func (s *StackPanel) asLength(p geom.PointF32) float32 {
switch s.Orientation { switch s.Orientation {
case OrientationHorizontal: case OrientationHorizontal:
@ -75,6 +71,10 @@ func (s *StackPanel) DesiredSize(ctx *Context) geom.PointF32 {
return size return size
} }
func (s *StackPanel) Handle(e allg5.Event) {
s.Container.Handle(e)
}
func (s *StackPanel) Layout(ctx *Context, bounds geom.RectangleF32) { func (s *StackPanel) Layout(ctx *Context, bounds geom.RectangleF32) {
s.Container.Layout(ctx, bounds) s.Container.Layout(ctx, bounds)

127
cmd/krampus19/animations.go Normal file
View File

@ -0,0 +1,127 @@
package main
import (
"math"
"math/rand"
"time"
"opslag.de/schobers/geom"
)
type moveAnimation struct {
e *entity
from, to geom.Point
pos geom.PointF32
}
func newMoveAnimation(e *entity, from, to geom.Point) *moveAnimation {
ani := &moveAnimation{e: e, from: from, to: to, pos: from.ToF32()}
return ani
}
func (a *moveAnimation) Animate(start, now time.Duration) bool {
const duration = 210 * time.Millisecond
progress := float32((now-start)*1000/duration) * .001
from, to := a.from.ToF32(), a.to.ToF32()
if progress >= 1 {
a.e.scr.pos = to
return false
}
a.e.scr.pos = to.Sub(from).Mul(progress).Add(from)
return true
}
type sinkAnimation struct {
e *entity
}
func newSinkAnimation(e *entity) *sinkAnimation {
return &sinkAnimation{e: e}
}
func (a *sinkAnimation) Animate(start, now time.Duration) bool {
const duration = 70 * time.Millisecond
progress := float32((now-start)*1000/duration) * .001
if progress >= 1 {
a.e.scr.z = 80
return false
}
a.e.scr.z = progress * 80
return true
}
type splashAnimation struct {
particles []splashParticle
}
func newSplashAnimation(pos geom.Point) *splashAnimation {
pos32 := pos.ToF32()
a := &splashAnimation{}
n := rand.Intn(20) + 4
for i := 0; i < n; i++ {
angle := rand.Float32() * math.Pi * 2
a.particles = append(a.particles, splashParticle{
angle: angle,
origin: pos32.Add2D(.45*geom.Cos32(angle), .45*geom.Sin32(angle)), // [-0.45 .. 0.45]
speed: .5*math.Pi + 2*math.Pi*rand.Float32(), // [0.5*Pi .. 2.5*Pi)
height: .2 + .8*rand.Float32(), // [0.2 .. 1.0)
dist: .5 + .5*rand.Float32(), // [0.5 .. 1.0)
})
}
return a
}
func (a *splashAnimation) Animate(start, now time.Duration) bool {
const duration = 1670 * time.Millisecond
progress := float32((now-start)*1000/duration) * .001
var opaq float32 = 1
if progress > .6 {
if progress > 1 {
opaq = 0
} else {
opaq = 2.5 - 2.5*progress
}
}
for i, p := range a.particles {
progress := geom.Min32(math.Pi, progress*p.speed) / math.Pi
a.particles[i].part = particle{
opaq: opaq,
pos: p.origin.Add2D(progress*p.dist*geom.Cos32(p.angle), progress*p.dist*geom.Sin32(p.angle)),
z: 20 + p.height*-100*geom.Sin32(progress*math.Pi),
}
}
if progress > 1 {
return false
}
return true
}
type particle struct {
pos geom.PointF32
z float32
opaq float32
}
func splitParticles(y float32, particles []particle) (behind []particle, front []particle) {
for _, p := range particles {
if p.pos.Y > y {
front = append(front, p)
} else {
behind = append(behind, p)
}
}
return
}
type splashParticle struct {
origin geom.PointF32
angle float32
speed float32
height float32
dist float32
part particle
}

View File

@ -0,0 +1,315 @@
package main
import (
"fmt"
"log"
"opslag.de/schobers/krampus19/gut"
"opslag.de/schobers/geom"
"opslag.de/schobers/allg5"
"opslag.de/schobers/krampus19/alui"
)
const margin = 8
type displayModeControl struct {
alui.StackPanel
label alui.Label
modes []string
current int
}
func newDisplayModeControl(ctx *Context) *displayModeControl {
var modes []string
fmtDisplayMode := func(width, height int) string { return fmt.Sprintf("%d x %d", width, height) }
containsDisplayMode := func(mode string) bool {
for _, m := range modes {
if m == mode {
return true
}
}
return false
}
displayMode := ctx.Settings.Video.DisplayMode
if displayMode == "" {
displayMode = fmtDisplayMode(ctx.DisplaySize.X, ctx.DisplaySize.Y)
}
var current int
for _, m := range allg5.DisplayModes() {
mode := fmtDisplayMode(m.Width, m.Height)
if containsDisplayMode(mode) {
continue
}
if mode == displayMode {
current = len(modes)
}
modes = append(modes, mode)
}
c := &displayModeControl{modes: modes, current: current}
c.Orientation = alui.OrientationHorizontal
c.label.TextAlign = allg5.AlignCenter
c.selectMode(0)
c.AddChild(newSpriteButton(ctx, "ui", "angle-left", func() { c.selectMode(-1) }))
c.AddChild(&c.label)
c.AddChild(newSpriteButton(ctx, "ui", "angle-right", func() { c.selectMode(1) }))
return c
}
func (c *displayModeControl) selectMode(delta int) {
c.current = (c.current + delta + len(c.modes)) % len(c.modes)
c.label.Text = c.Mode()
}
func (c *displayModeControl) Mode() string { return c.modes[c.current] }
type checkBox struct {
alui.Button
ctx *Context
Selected bool
}
func newCheckBox(ctx *Context) *checkBox {
b := &checkBox{ctx: ctx}
b.OnClick = func() {
b.Selected = !b.Selected
}
return b
}
func (b *checkBox) DesiredSize(ctx *alui.Context) geom.PointF32 {
return b.ctx.SpriteDrawer.Size("ui", "check-square").Add2D(2*margin, 2*margin)
}
func (b *checkBox) Render(ctx *alui.Context, bounds geom.RectangleF32) {
tint := b.ctx.Palette.Primary
if b.Over {
tint = b.ctx.Palette.Dark
ctx.Cursor = allg5.MouseCursorLink
}
var part = "square"
if b.Selected {
part = "check-square"
}
b.ctx.SpriteDrawer.Draw("ui", part, bounds.Center(), DrawSpriteOptions{Tint: &tint})
}
type spriteButton struct {
alui.Button
ctx *Context
Sprite string
Part string
}
func newSpriteButton(ctx *Context, sprite, part string, onClick func()) *spriteButton {
b := &spriteButton{ctx: ctx, Sprite: sprite, Part: part}
b.OnClick = onClick
return b
}
func (b *spriteButton) DesiredSize(ctx *alui.Context) geom.PointF32 {
return b.ctx.SpriteDrawer.Size(b.Sprite, b.Part).Add2D(2*margin, 2*margin)
}
func (b *spriteButton) Render(ctx *alui.Context, bounds geom.RectangleF32) {
tint := b.ctx.Palette.Primary
if b.Over {
tint = b.ctx.Palette.Dark
ctx.Cursor = allg5.MouseCursorLink
}
b.ctx.SpriteDrawer.Draw(b.Sprite, b.Part, bounds.Center(), DrawSpriteOptions{Tint: &tint})
}
type selectKeyControl struct {
alui.Label
Key allg5.Key
WaitingForInput bool
}
func newSelectKeyControl(key allg5.Key) *selectKeyControl {
c := &selectKeyControl{Key: key}
c.TextAlign = allg5.AlignCenter
return c
}
func (c *selectKeyControl) Handle(e allg5.Event) {
c.Label.Handle(e)
switch e := e.(type) {
case *allg5.MouseButtonDownEvent:
if c.Over && e.Button == allg5.MouseButtonLeft {
c.WaitingForInput = true
}
case *allg5.KeyDownEvent:
if c.WaitingForInput {
if e.KeyCode != allg5.KeyEscape {
c.Key = e.KeyCode
}
c.WaitingForInput = false
}
}
}
func (c *selectKeyControl) Render(ctx *alui.Context, bounds geom.RectangleF32) {
if c.WaitingForInput {
c.Text = "_"
} else {
c.Text = gut.KeyToString(c.Key)
}
if c.Over {
ctx.Cursor = allg5.MouseCursorLink
}
c.Label.Render(ctx, bounds)
}
type settingsHeader struct {
alui.Label
}
func newSettingsHeader(label string) alui.Control {
header := &settingsHeader{}
header.Font = "header"
header.Text = label
return alui.NewMargins(header, 3*margin, 0, 2*margin)
}
type settingsRow struct {
alui.StackPanel
label *alui.Label
edit alui.Control
}
func newSettingRow(label string, edit alui.Control) *settingsRow {
row := &settingsRow{}
row.Orientation = alui.OrientationHorizontal
row.label = &alui.Label{Text: label}
row.edit = edit
row.Children = append(row.Children, row.label, row.edit)
return row
}
func (r *settingsRow) Layout(ctx *alui.Context, bounds geom.RectangleF32) {
label := bounds
label.Max.X = label.Min.X + .5*label.Dx()
r.label.Layout(ctx, label)
width := r.edit.DesiredSize(ctx).X
edit := bounds
if geom.IsNaN32(width) || width > label.Dx() {
edit.Min.X = label.Max.X
} else {
margin := (label.Dx() - width) * .5
edit.Min.X = label.Max.X + margin
edit.Max.X -= margin
}
r.edit.Layout(ctx, edit)
}
type wideButton struct {
alui.Button
}
func newWideButton(label string, onClick func()) *wideButton {
b := &wideButton{}
b.Text = label
b.TextAlign = allg5.AlignCenter
b.OnClick = onClick
return b
}
func (b *wideButton) DesiredSize(ctx *alui.Context) geom.PointF32 {
size := b.Button.DesiredSize(ctx)
size.X += 2 * margin
return size
}
type changeSettings struct {
alui.Column
ctx *Context
rows []*settingsRow
active int
}
func (s *changeSettings) addRow(row ...*settingsRow) {
for _, row := range row {
s.AddChild(row)
s.rows = append(s.rows, row)
}
}
func (s *changeSettings) Enter(ctx *Context) error {
s.Init()
s.ctx = ctx
keyLeft := newSelectKeyControl(s.ctx.Settings.Controls.MoveLeft)
keyUp := newSelectKeyControl(s.ctx.Settings.Controls.MoveUp)
keyRight := newSelectKeyControl(s.ctx.Settings.Controls.MoveRight)
keyDown := newSelectKeyControl(s.ctx.Settings.Controls.MoveDown)
s.AddChild(newSettingsHeader("Controls"))
s.addRow(
newSettingRow("Key left", keyLeft),
newSettingRow("Key up", keyUp),
newSettingRow("Key right", keyRight),
newSettingRow("Key down", keyDown),
)
s.AddChild(newSettingsHeader("Video"))
displayMode := newDisplayModeControl(ctx)
windowed := newCheckBox(ctx)
windowed.Selected = s.ctx.Settings.Video.Windowed
s.addRow(
newSettingRow("Windowed", windowed),
newSettingRow("Resolution (fullscreen)", displayMode),
)
buttons := &alui.StackPanel{Orientation: alui.OrientationHorizontal}
buttons.AddChild(
newWideButton("Cancel", func() { s.ctx.Navigation.ShowMainMenu() }),
newWideButton("OK", func() {
var controls = controls{MoveLeft: keyLeft.Key, MoveUp: keyUp.Key, MoveRight: keyRight.Key, MoveDown: keyDown.Key}
var video = video{Windowed: windowed.Selected, DisplayMode: displayMode.Mode()}
s.ctx.Settings = settings{Controls: controls, Video: video}
err := s.ctx.Settings.StoreDefault()
if err != nil {
log.Printf("User settings are not stored: %v", err)
} else {
log.Printf("Stored new settings.")
}
s.ctx.Navigation.ShowMainMenu()
}),
)
s.AddChild(alui.Center(buttons))
return nil
}
func (s *changeSettings) Handle(e allg5.Event) {
s.Column.Handle(e)
switch e := e.(type) {
case *allg5.KeyDownEvent:
switch e.KeyCode {
case allg5.KeyEscape:
s.ctx.Navigation.ShowMainMenu()
}
}
}
func (s *changeSettings) Leave() {
}

View File

@ -63,7 +63,7 @@ func (c *console) Render(ctx *alui.Context, bounds geom.RectangleF32) {
} }
messageTop := size.Y - totalHeight - c.offset messageTop := size.Y - totalHeight - c.offset
for _, m := range messages { for _, m := range messages {
if messageTop <= size.Y || (messageTop+lineHeight) >= 0 { if messageTop <= size.Y && (messageTop+lineHeight) >= 0 {
ctx.Fonts.DrawFont(font, 0, messageTop, ctx.Palette.Text, m) ctx.Fonts.DrawFont(font, 0, messageTop, ctx.Palette.Text, m)
} }
messageTop += lineHeight messageTop += lineHeight

View File

@ -3,6 +3,8 @@ package main
import ( import (
"time" "time"
"github.com/spf13/afero"
"opslag.de/schobers/geom"
"opslag.de/schobers/krampus19/alui" "opslag.de/schobers/krampus19/alui"
"opslag.de/schobers/allg5" "opslag.de/schobers/allg5"
@ -20,10 +22,14 @@ func newTexture(bmp *allg5.Bitmap) texture {
} }
type Context struct { type Context struct {
DisplaySize geom.Point
Resources vfs.CopyDir Resources vfs.CopyDir
ResourcesFs afero.Fs
Textures map[string]texture Textures map[string]texture
Levels map[string]level
Sprites map[string]sprite Sprites map[string]sprite
Levels *levelPacks
Progress progress
SpriteDrawer SpriteDrawer
Settings settings Settings settings
Palette *alui.Palette Palette *alui.Palette

21
cmd/krampus19/entity.go Normal file
View File

@ -0,0 +1,21 @@
package main
import (
"opslag.de/schobers/geom"
"opslag.de/schobers/krampus19/soko"
)
type entity struct {
id int
typ soko.EntityType
scr entityLoc
}
type entityLoc struct {
pos geom.PointF32
z float32
}
func newEntity(e soko.Entity, pos geom.Point) *entity {
return &entity{e.ID, e.Typ, entityLoc{pos.ToF32(), 0}}
}

View File

@ -0,0 +1,25 @@
package main
import "sort"
type entityMap map[int]*entity
func (m entityMap) RenderOrder() []*entity {
entities := make([]*entity, 0, len(m))
for _, e := range m {
entities = append(entities, e)
}
sort.Slice(entities, func(i, j int) bool {
var posI, posJ = entities[i].scr.pos, entities[j].scr.pos
if posI.Y == posJ.Y {
if posI.X == posJ.X {
return entities[i].id < entities[j].id
}
return posI.X < posJ.X
}
return posI.Y < posJ.Y
})
return entities
}

View File

@ -4,10 +4,16 @@ import (
"errors" "errors"
"fmt" "fmt"
"image/png" "image/png"
"io"
"log" "log"
"os"
"path/filepath"
"strings"
"github.com/spf13/afero"
"opslag.de/schobers/allg5" "opslag.de/schobers/allg5"
"opslag.de/schobers/fs/vfs" "opslag.de/schobers/fs/vfs"
"opslag.de/schobers/geom"
"opslag.de/schobers/krampus19/alui" "opslag.de/schobers/krampus19/alui"
"opslag.de/schobers/krampus19/gut" "opslag.de/schobers/krampus19/gut"
) )
@ -23,7 +29,7 @@ type game struct {
} }
func (g *game) initUI(disp *allg5.Display, cons *gut.Console, fps *gut.FPS) error { func (g *game) initUI(disp *allg5.Display, cons *gut.Console, fps *gut.FPS) error {
disp.SetWindowTitle("Krampushack '19 - Title TBD - by Tharro") disp.SetWindowTitle("Krampushack '19 - Sokodragon - by Tharro")
ui := alui.NewUI(disp, &g.main) ui := alui.NewUI(disp, &g.main)
ui.SetPalette(alui.Palette{ ui.SetPalette(alui.Palette{
Icon: allg5.NewColor(0x21, 0x21, 0x21), Icon: allg5.NewColor(0x21, 0x21, 0x21),
@ -59,7 +65,11 @@ func (g *game) loadBitmap(path, name string) error {
} }
func (g *game) loadFonts() error { func (g *game) loadFonts() error {
openSansPath, err := g.ctx.Resources.Retrieve("fonts/OpenSans-Regular.ttf") openSansRegularPath, err := g.ctx.Resources.Retrieve("fonts/OpenSans-Regular.ttf")
if err != nil {
return err
}
openSansBoldPath, err := g.ctx.Resources.Retrieve("fonts/OpenSans-Bold.ttf")
if err != nil { if err != nil {
return err return err
} }
@ -67,7 +77,11 @@ func (g *game) loadFonts() error {
if err != nil { if err != nil {
return err return err
} }
err = g.ui.Fonts().LoadFonts(alui.FontDescription{Path: openSansPath, Name: "default", Size: 36}) err = g.ui.Fonts().LoadFonts(alui.FontDescription{Path: openSansRegularPath, Name: "default", Size: 32})
if err != nil {
return err
}
err = g.ui.Fonts().LoadFonts(alui.FontDescription{Path: openSansBoldPath, Name: "header", Size: 32})
if err != nil { if err != nil {
return err return err
} }
@ -88,21 +102,57 @@ func (g *game) loadTextures(pathToName map[string]string) error {
return nil return nil
} }
func (g *game) loadLevels(names ...string) error { func (g *game) loadLevelPacks() error {
g.ctx.Levels = map[string]level{} g.ctx.Levels = newLevelPacks()
for _, name := range names {
fileName := fmt.Sprintf("levels/level%s.txt", name) var ids []string
const root = "levels"
err := afero.Walk(g.ctx.ResourcesFs, root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
return nil
}
name := filepath.Base(path)
if name == root {
return nil
}
if !strings.HasPrefix(name, "pack") {
return filepath.SkipDir
}
ids = append(ids, name[4:])
return filepath.SkipDir
})
if err != nil {
return err
}
for _, id := range ids {
err := g.loadLevelPack(id)
if err != nil {
return err
}
}
return nil
}
func (g *game) loadLevelPack(id string) error {
fileName := fmt.Sprintf("levels/pack%s/info.txt", id)
f, err := g.ctx.Resources.Open(fileName) f, err := g.ctx.Resources.Open(fileName)
if err != nil { if err != nil {
return err return err
} }
defer f.Close() defer f.Close()
level, err := loadLevelAsset(f) pack, err := parseLevelPackAsset(f, func(levelID string) (io.ReadCloser, error) {
fileName := fmt.Sprintf("levels/pack%s/level%s.txt", id, levelID)
return g.ctx.Resources.Open(fileName)
})
if err != nil { if err != nil {
return err return err
} }
g.ctx.Levels[name] = level g.ctx.Levels.Add(id, pack)
}
return nil return nil
} }
@ -136,27 +186,27 @@ func (g *game) loadSprites(names ...string) error {
func (g *game) loadAssets() error { func (g *game) loadAssets() error {
log.Println("Loading textures...") log.Println("Loading textures...")
err := g.loadTextures(map[string]string{ err := g.loadTextures(map[string]string{
"basic_tile.png": "basic_tile", "entity_brick.png": "brick",
"sunken_brick_tile.png": "sunken_brick_tile", "entity_dragon.png": "dragon",
"water_tile.png": "water_tile", "entity_egg.png": "egg",
"main_character.png": "main_character", "tile_lava_brick.png": "lava_brick",
"villain_character.png": "villain_character", "tile_magma.png": "magma",
"brick.png": "brick", "particles.png": "particles",
"crate.png": "crate", "ui.png": "ui",
}) })
if err != nil { if err != nil {
return err return err
} }
log.Printf("Loaded %d textures.\n", len(g.ctx.Textures)) log.Printf("Loaded %d textures.\n", len(g.ctx.Textures))
log.Println("Loading levels...") log.Println("Loading level packs...")
err = g.loadLevels("1") err = g.loadLevelPacks()
if err != nil { if err != nil {
return err return err
} }
log.Printf("Loaded %d levels.\n", len(g.ctx.Levels)) log.Printf("Loaded %d levels packs (%d levels).\n", g.ctx.Levels.Len(), g.ctx.Levels.LenLevels())
log.Println("Loading fonts...") log.Println("Loading fonts...")
err = g.loadFonts() err = g.loadFonts()
@ -166,10 +216,10 @@ func (g *game) loadAssets() error {
log.Printf("Loaded %d fonts.\n", g.ui.Fonts().Len()) log.Printf("Loaded %d fonts.\n", g.ui.Fonts().Len())
log.Println("Loading sprites") log.Println("Loading sprites")
// err = g.loadSprites("dragon") err = g.loadSprites("brick", "dragon", "egg", "lava_brick", "magma", "particles", "ui")
// if err != nil { if err != nil {
// return err return err
// } }
log.Printf("Loaded %d sprites.\n", len(g.ctx.Sprites)) log.Printf("Loaded %d sprites.\n", len(g.ctx.Sprites))
return nil return nil
} }
@ -179,9 +229,15 @@ func (g *game) Destroy() {
g.ctx.Destroy() g.ctx.Destroy()
} }
func (g *game) Init(disp *allg5.Display, res vfs.CopyDir, cons *gut.Console, fps *gut.FPS) error { func (g *game) Init(disp *allg5.Display, settings settings, res vfs.CopyDir, resFs afero.Fs, cons *gut.Console, fps *gut.FPS) error {
log.Print("Initializing game...") log.Print("Initializing game...")
g.ctx = &Context{Resources: res, Textures: map[string]texture{}, Settings: newDefaultSettings(), Navigation: navigation{game: g}} g.ctx = &Context{Resources: res, ResourcesFs: resFs, Textures: map[string]texture{}, Settings: settings, Navigation: navigation{game: g}}
g.ctx.DisplaySize = geom.Pt(disp.Width(), disp.Height())
g.ctx.SpriteDrawer.ctx = g.ctx
err := g.ctx.Progress.load()
if err != nil {
log.Printf("Unable to load previous progress.")
}
if err := g.initUI(disp, cons, fps); err != nil { if err := g.initUI(disp, cons, fps); err != nil {
return err return err
} }
@ -191,7 +247,7 @@ func (g *game) Init(disp *allg5.Display, res vfs.CopyDir, cons *gut.Console, fps
} }
log.Print("Loaded assets.") log.Print("Loaded assets.")
g.ctx.Navigation.showMainMenu() g.ctx.Navigation.ShowMainMenu()
return nil return nil
} }

50
cmd/krampus19/io.go Normal file
View File

@ -0,0 +1,50 @@
package main
import (
"encoding/json"
"os"
"path/filepath"
)
func decodeJSON(path string, v interface{}) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
err = json.NewDecoder(f).Decode(v)
if err != nil {
return err
}
return nil
}
func encodeJSON(path string, v interface{}) error {
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
return json.NewEncoder(f).Encode(v)
}
func userDir() (string, error) {
config, err := os.UserConfigDir()
if err != nil {
return "", err
}
dir := filepath.Join(config, "krampus19")
err = os.MkdirAll(dir, 0777)
if err != nil {
return "", err
}
return dir, nil
}
func userFile(name string) (string, error) {
dir, err := userDir()
if err != nil {
return "", err
}
return filepath.Join(dir, name), nil
}

View File

@ -1,6 +1,7 @@
package main package main
import ( import (
"fmt"
"io" "io"
"log" "log"
"time" "time"
@ -10,6 +11,7 @@ import (
"opslag.de/schobers/allg5" "opslag.de/schobers/allg5"
"opslag.de/schobers/fs/ricefs" "opslag.de/schobers/fs/ricefs"
"opslag.de/schobers/fs/vfs" "opslag.de/schobers/fs/vfs"
"opslag.de/schobers/geom"
"opslag.de/schobers/krampus19/gut" "opslag.de/schobers/krampus19/gut"
) )
@ -22,10 +24,15 @@ func main() {
} }
} }
func resources() (vfs.CopyDir, error) { func resources() (vfs.CopyDir, afero.Fs, error) {
var embeddedFs = ricefs.NewFs(rice.MustFindBox("res")) var embeddedFs = ricefs.NewFs(rice.MustFindBox("res"))
var osFs = afero.NewBasePathFs(afero.NewOsFs(), "./res") var osFs = afero.NewBasePathFs(afero.NewOsFs(), "./res")
return vfs.NewCopyDir(vfs.NewFallbackFs(osFs, embeddedFs)) var fs = vfs.NewFallbackFs(osFs, embeddedFs)
copy, err := vfs.NewCopyDir(fs)
if err != nil {
return nil, nil, err
}
return copy, fs, nil
} }
func run() error { func run() error {
@ -33,19 +40,64 @@ func run() error {
cons := &gut.Console{} cons := &gut.Console{}
log.SetOutput(io.MultiWriter(log.Writer(), cons)) log.SetOutput(io.MultiWriter(log.Writer(), cons))
log.Printf("Initializing Allegro") res, resFs, err := resources()
err := allg5.Init(allg5.InitAll) if err != nil {
return err
}
defer res.Destroy()
settings := newDefaultSettings()
err = settings.LoadDefault()
if err != nil {
log.Printf("Unable to load settings, falling back on defaults.")
}
err = settings.StoreDefault()
if err != nil {
log.Printf("Unable to store settings; err: %v", err)
}
log.Printf("Initializing Allegro.")
var init = allg5.InitAll
init.Audio = false
err = allg5.Init(init)
if err != nil { if err != nil {
return err return err
} }
log.Printf("Creating display") log.Printf("Creating display.")
disp, err := allg5.NewDisplay(1440, 900, allg5.NewDisplayOptions{Maximized: false, Windowed: true, Resizable: true, Vsync: true}) var size = geom.Pt(1280, 720)
dispOptions := allg5.NewDisplayOptions{Vsync: true, Fullscreen: true}
if settings.Video.Windowed {
dispOptions.Frameless = true
dispOptions.Windowed = true
} else {
dispOptions.Fullscreen = true
str := func(m allg5.DisplayMode) string { return fmt.Sprintf("%d x %d", m.Width, m.Height) }
for _, mode := range allg5.DisplayModes() {
if str(mode) == settings.Video.DisplayMode {
size = geom.Pt(mode.Width, mode.Height)
}
}
}
disp, err := allg5.NewDisplay(size.X, size.Y, dispOptions)
if err != nil { if err != nil {
return err return err
} }
defer disp.Destroy() defer disp.Destroy()
iconPath, err := res.Retrieve("icon.png")
if err != nil {
log.Printf("Unable to retrieve icon.")
} else {
icon, err := allg5.LoadBitmap(iconPath)
if err != nil {
log.Printf("Unable to load icon bitmap.")
} else {
defer icon.Destroy()
disp.SetIcon(icon)
}
}
eq, err := allg5.NewEventQueue() eq, err := allg5.NewEventQueue()
if err != nil { if err != nil {
return err return err
@ -56,17 +108,11 @@ func run() error {
eq.RegisterKeyboard() eq.RegisterKeyboard()
eq.RegisterMouse() eq.RegisterMouse()
res, err := resources()
if err != nil {
return err
}
defer res.Destroy()
fps := gut.NewFPS() fps := gut.NewFPS()
defer fps.Destroy() defer fps.Destroy()
game := &game{} game := &game{}
err = game.Init(disp, res, cons, fps) err = game.Init(disp, settings, res, resFs, cons, fps)
if err != nil { if err != nil {
return err return err
} }
@ -94,6 +140,8 @@ func run() error {
log.Printf("Stopping game loop, user pressed Alt+F4") log.Printf("Stopping game loop, user pressed Alt+F4")
return nil return nil
} }
case *allg5.DisplayResizeEvent:
game.ctx.DisplaySize = geom.Pt(disp.Width(), disp.Height())
} }
game.Handle(e) game.Handle(e)
e = eq.Get() e = eq.Get()

View File

@ -0,0 +1,6 @@
// +build windows,!console
package main
// #cgo LDFLAGS: -Wl,-subsystem,windows
import "C"

View File

@ -1,144 +0,0 @@
package main
import (
"errors"
"fmt"
"io"
"opslag.de/schobers/geom"
)
type entityType byte
type tile byte
const (
entityTypeInvalid entityType = entityType(0)
entityTypeNone = '_'
entityTypeCharacter = '@'
entityTypeVillain = 'X'
entityTypeBrick = 'B'
entityTypeCrate = 'C'
)
func (e entityType) IsValid() bool {
switch e {
case entityTypeNone:
case entityTypeCharacter:
case entityTypeVillain:
case entityTypeBrick:
case entityTypeCrate:
default:
return false
}
return true
}
const (
tileInvalid tile = tile(0)
tileNothing = '.'
tileBasic = '#'
tileWater = '~'
)
func (t tile) IsValid() bool {
switch t {
case tileNothing:
case tileBasic:
case tileWater:
default:
return false
}
return true
}
type level struct {
width int
height int
tiles []tile
entities []entityType
}
func (l level) idxToPos(i int) geom.Point { return geom.Pt(i%l.width, i/l.width) }
func (l level) posToIdx(p geom.Point) int {
if p.X < 0 || p.Y < 0 || p.X >= l.width || p.Y >= l.height {
return -1
}
return p.Y*l.width + p.X
}
func loadLevelAsset(r io.Reader) (level, error) {
var l level
ctx := levelContext{&l}
err := parseLines(r, ctx.parse)
if err != nil {
return level{}, err
}
return l, nil
}
type levelContext struct {
level *level
}
func (c *levelContext) parse(p *lineParser) parseLineFn {
if p.eof() {
return nil
}
switch p.peek() {
case "level:":
return c.parseContent
case "":
p.next() // skip
return c.parse
default:
return nil
}
}
func (c *levelContext) parseContent(p *lineParser) parseLineFn {
if p.next() != "level:" {
return p.emitErr(errors.New("expected level start"))
}
return c.parseRow
}
func (c *levelContext) parseRow(p *lineParser) parseLineFn {
if p.eof() {
return p.emitErr(errors.New("unexpected end of file"))
}
line := p.next()
if line == ":level" {
return c.parse
}
if c.level.height == 0 {
c.level.width = len(line) / 2
}
return c.addRow(p, line)
}
func (c *levelContext) addRow(p *lineParser, line string) parseLineFn {
var tiles []tile
var entities []entityType
for i := 0; i < len(line); i += 2 {
tiles = append(tiles, tile(line[i]))
entities = append(entities, entityType(line[i+1]))
}
for i, t := range tiles {
if !t.IsValid() {
return p.emitErr(fmt.Errorf("level contains invalid tile at (%d, %d)", i, c.level.height))
}
}
for i, e := range entities {
if !e.IsValid() {
return p.emitErr(fmt.Errorf("level contains invalid entity type at (%d, %d)", i, c.level.height))
}
}
c.level.height++
c.level.tiles = append(c.level.tiles, tiles...)
c.level.entities = append(c.level.entities, entities...)
return c.parseRow
}

129
cmd/krampus19/levelpack.go Normal file
View File

@ -0,0 +1,129 @@
package main
import (
"errors"
"io"
"strings"
"opslag.de/schobers/krampus19/gut"
"opslag.de/schobers/krampus19/soko"
)
type levelPack struct {
name string
order []string
levels map[string]soko.Level
}
func (p levelPack) find(level string) int {
for i, l := range p.order {
if l == level {
return i
}
}
return -1
}
func (p levelPack) FindNext(level string) (string, bool) {
idx := p.find(level)
if idx == -1 || idx == len(p.order)-1 {
return "", false
}
return p.order[idx+1], true
}
func (p levelPack) Len() int { return len(p.order) }
type parseLevelPackContext struct {
name string
levels []string
}
func parseLevelPackAsset(r io.Reader, openLevelFn func(id string) (io.ReadCloser, error)) (levelPack, error) {
ctx := &parseLevelPackContext{}
err := gut.ParseLines(r, ctx.Parse)
if err != nil {
return levelPack{}, err
}
pack := levelPack{name: ctx.name, levels: map[string]soko.Level{}}
for _, id := range ctx.levels {
rc, err := openLevelFn(id)
if err != nil {
return levelPack{}, err
}
defer rc.Close()
level, err := soko.ParseLevel(rc)
if err != nil {
return levelPack{}, err
}
pack.order = append(pack.order, id)
pack.levels[id] = level
}
return pack, nil
}
func (c *parseLevelPackContext) Parse(p *gut.LineParser) gut.ParseLineFn {
if p.SkipSpaceEOF() {
return p.EmitErr(errors.New("empty level pack"))
}
return c.parse
}
func (c *parseLevelPackContext) parse(p *gut.LineParser) gut.ParseLineFn {
const levelsTag = "levels:"
const nameTag = "name:"
if p.SkipSpaceEOF() {
return nil
}
line := p.Next()
switch {
case strings.HasPrefix(line, nameTag):
c.name = strings.TrimSpace(line[len(nameTag):])
return c.parse
case strings.HasPrefix(line, levelsTag):
return gut.SkipSpaceBeforeContent(c.parseLevels)
}
return p.EmitErr(errors.New("tag not allowed"))
}
func (c *parseLevelPackContext) parseLevels(p *gut.LineParser) gut.ParseLineFn {
const levelTag = "level:"
const levelsEndTag = ":levels"
line := p.Next()
switch line {
case levelTag:
return gut.SkipSpaceBeforeContent(c.parseLevel)
case levelsEndTag:
return c.parse
}
return p.EmitErr(errors.New("tag not allowed"))
}
func (c *parseLevelPackContext) parseLevel(p *gut.LineParser) gut.ParseLineFn {
const idTag = "id:"
line := p.Next()
switch {
case strings.HasPrefix(line, idTag):
c.levels = append(c.levels, strings.TrimSpace(line[len(idTag):]))
return gut.SkipSpaceBeforeContent(c.parseLevelEnd)
}
return p.EmitErr(errors.New("must have an id tag"))
}
func (c *parseLevelPackContext) parseLevelEnd(p *gut.LineParser) gut.ParseLineFn {
const levelEndTag = ":level"
line := p.Next()
switch {
case strings.HasPrefix(line, levelEndTag):
return gut.SkipSpaceBeforeContent(c.parseLevels)
}
return p.EmitErr(errors.New("tag not allowed"))
}

View File

@ -0,0 +1,36 @@
package main
type levelPacks struct {
packs map[string]levelPack
order []string
}
func newLevelPacks() *levelPacks {
return &levelPacks{map[string]levelPack{}, nil}
}
func (p *levelPacks) Add(id string, pack levelPack) {
p.order = append(p.order, id)
p.packs[id] = pack
}
func (p *levelPacks) ByID(id string) levelPack { return p.packs[id] }
func (p *levelPacks) FirstPackID() string {
if p.Len() == 0 {
return ""
}
return p.order[0]
}
func (p *levelPacks) Len() int { return len(p.order) }
func (p *levelPacks) LenLevels() int {
var cnt int
for _, pack := range p.packs {
cnt += pack.Len()
}
return cnt
}
func (p *levelPacks) MustSelect() bool { return p.Len() != 1 }

View File

@ -0,0 +1,40 @@
package main
import (
"opslag.de/schobers/allg5"
"opslag.de/schobers/krampus19/alui"
)
type levelPackSelect struct {
alui.Menu
ctx *Context
}
func (s *levelPackSelect) Enter(ctx *Context) error {
s.ctx = ctx
s.Init()
s.AddChild(newHeader("Select a level pack"))
for _, id := range s.ctx.Levels.order {
var copy = id
s.Add(s.ctx.Levels.ByID(id).name, func() {
s.ctx.Navigation.SelectLevel(copy)
})
}
s.Add("Back to main menu", func() { s.ctx.Navigation.ShowMainMenu() })
return nil
}
func (s *levelPackSelect) Handle(e allg5.Event) {
switch e := e.(type) {
case *allg5.KeyDownEvent:
switch e.KeyCode {
case allg5.KeyEscape:
s.ctx.Navigation.ShowMainMenu()
}
}
s.Menu.Handle(e)
}
func (s *levelPackSelect) Leave() {}

View File

@ -0,0 +1,59 @@
package main
import (
"fmt"
"opslag.de/schobers/allg5"
"opslag.de/schobers/krampus19/alui"
)
type levelSelect struct {
alui.Menu
ctx *Context
packID string
pack levelPack
}
func (s *levelSelect) Enter(ctx *Context) error {
s.ctx = ctx
s.pack = s.ctx.Levels.ByID(s.packID)
s.Init()
name := func(i int, steps int) string {
if steps == 0 {
return fmt.Sprintf("Level %d", i)
}
return fmt.Sprintf("Level %d (%d)", i, steps)
}
if s.ctx.Levels.MustSelect() {
s.AddChild(newHeader(fmt.Sprintf("Select a '%s' level", s.pack.name)))
} else {
s.AddChild(newHeader("Select a level"))
}
for i, id := range s.pack.order {
levelID := id
s.Add(name(i+1, s.ctx.Progress.Level(s.packID, levelID).Steps), func() {
s.ctx.Navigation.PlayLevel(s.packID, levelID)
})
}
if s.ctx.Levels.MustSelect() {
s.Add("Select level pack", func() { s.ctx.Navigation.SelectPack() })
}
s.Add("Back to main menu", func() { s.ctx.Navigation.ShowMainMenu() })
return nil
}
func (s *levelSelect) Handle(e allg5.Event) {
switch e := e.(type) {
case *allg5.KeyDownEvent:
switch e.KeyCode {
case allg5.KeyEscape:
s.ctx.Navigation.ShowMainMenu()
}
}
s.Menu.Handle(e)
}
func (s *levelSelect) Leave() {}

View File

@ -1,55 +0,0 @@
package main
import (
"errors"
"io"
"io/ioutil"
"strings"
)
type lineParser struct {
lines []string
i int
err error
}
var errUnexpectedEnd = errors.New("unexpected end of file")
func (p *lineParser) eof() bool { return p.i == len(p.lines) }
func (p *lineParser) peek() string { return p.lines[p.i] }
func (p *lineParser) next() string {
i := p.i
p.i++
return p.lines[i]
}
func (p *lineParser) emitErr(err error) parseLineFn {
p.err = err
return nil
}
func (p *lineParser) skipSpaceEOF() bool {
for !p.eof() && len(strings.TrimSpace(p.peek())) == 0 {
p.next()
}
return p.eof()
}
type parseLineFn func(p *lineParser) parseLineFn
func parseLines(r io.Reader, fn parseLineFn) error {
content, err := ioutil.ReadAll(r)
if err != nil {
return err
}
lines := strings.Split(string(content), "\n")
for i, line := range lines {
lines[i] = strings.TrimRight(line, "\r\n")
}
parser := &lineParser{lines: lines}
for fn != nil {
fn = fn(parser)
}
return parser.err
}

View File

@ -1,6 +1,7 @@
package main package main
import ( import (
"opslag.de/schobers/allg5"
"opslag.de/schobers/krampus19/alui" "opslag.de/schobers/krampus19/alui"
) )
@ -10,11 +11,17 @@ type mainMenu struct {
ctx *Context ctx *Context
} }
func newHeader(label string) alui.Control {
return alui.NewMargins(&alui.Label{ControlBase: alui.ControlBase{Font: "header"}, Text: label, TextAlign: allg5.AlignCenter}, 3*margin)
}
func (m *mainMenu) Enter(ctx *Context) error { func (m *mainMenu) Enter(ctx *Context) error {
m.ctx = ctx m.ctx = ctx
m.Init() m.Init()
m.Add("Play", func() { m.ctx.Navigation.playLevel("1") }) m.AddChild(newHeader("Sokodragon"))
m.Add("Quit", func() { m.ctx.Navigation.quit() }) m.Add("Play", func() { m.ctx.Navigation.SelectPack() })
m.Add("Settings", func() { m.ctx.Navigation.ChangeSettings() })
m.Add("Quit", func() { m.ctx.Navigation.Quit() })
return nil return nil
} }

View File

@ -16,24 +16,42 @@ type scene interface {
Leave() Leave()
} }
func (n *navigation) playLevel(l string) { func (n *navigation) ChangeSettings() {
n.switchTo(&playLevel{name: l}) n.switchTo(&changeSettings{})
} }
func (n *navigation) quit() { func (n *navigation) PlayLevel(packID, levelID string) {
n.switchTo(nil) n.switchTo(&playLevel{packID: packID, levelID: levelID})
} }
func (n *navigation) showMainMenu() { func (n *navigation) SelectLevel(packID string) {
n.switchTo(&levelSelect{packID: packID})
}
func (n *navigation) SelectPack() {
if n.game.ctx.Levels.MustSelect() {
n.switchTo(&levelPackSelect{})
} else {
packID := n.game.ctx.Levels.FirstPackID()
n.SelectLevel(packID)
}
}
func (n *navigation) ShowMainMenu() {
n.switchTo(&mainMenu{}) n.switchTo(&mainMenu{})
} }
func (n *navigation) Quit() {
n.switchTo(nil)
}
func (n *navigation) switchTo(s scene) { func (n *navigation) switchTo(s scene) {
if n.curr != nil { if n.curr != nil {
n.curr.Leave() n.curr.Leave()
} }
n.curr = s n.curr = s
n.game.scene.Proxy = s n.game.scene.Proxy = s
n.game.scene.Visible = s != nil
if n.curr != nil { if n.curr != nil {
n.curr.Enter(n.game.ctx) n.curr.Enter(n.game.ctx)
} }

View File

@ -3,374 +3,254 @@ package main
import ( import (
"fmt" "fmt"
"log" "log"
"sort" "strconv"
"time"
"opslag.de/schobers/allg5" "opslag.de/schobers/allg5"
"opslag.de/schobers/geom" "opslag.de/schobers/geom"
"opslag.de/schobers/krampus19/alui" "opslag.de/schobers/krampus19/alui"
"opslag.de/schobers/krampus19/gut" "opslag.de/schobers/krampus19/soko"
) )
type playLevel struct { type playLevel struct {
alui.ControlBase alui.ControlBase
ctx *Context ctx *Context
init bool
menu *alui.Menu menu *alui.Menu
end alui.Control
showMenu bool showMenu bool
name string packID string
levelID string
offset geom.PointF32 offset geom.PointF32
scale float32 scale float32
keysDown keyPressedState
level level state playLevelState
player *entity pathFinding bool
villain *entity
bricks []*entity
sunken []*entity
steps int
tick time.Duration
ani gut.Animations
} }
type keyPressedState map[allg5.Key]bool type keyPressedState map[allg5.Key]bool
func (s keyPressedState) CountPressed(keys ...allg5.Key) int { func (s keyPressedState) ArePressed(keys ...allg5.Key) []allg5.Key {
var cnt int pressed := make([]allg5.Key, 0, len(keys))
for _, k := range keys { for _, k := range keys {
if s[k] { if s[k] {
cnt++ pressed = append(pressed, k)
} }
} }
return cnt return pressed
} }
type entity struct { func (s keyPressedState) CountPressed(keys ...allg5.Key) int { return len(s.ArePressed(keys...)) }
typ entityType
pos geom.Point
scr geom.PointF32
}
func newEntity(typ entityType, pos geom.Point) *entity {
return &entity{typ, pos, pos.ToF32()}
}
type posToScrFn func(geom.Point) geom.PointF32
type entityMoveAnimation struct {
e *entity
from, to geom.Point
pos geom.PointF32
}
func newEntityMoveAnimation(e *entity, to geom.Point) *entityMoveAnimation {
ani := &entityMoveAnimation{e: e, from: e.pos, to: to, pos: e.pos.ToF32()}
ani.e.pos = to
return ani
}
func (a *entityMoveAnimation) Animate(start, now time.Duration) bool {
const duration = 240 * time.Millisecond
progress := float32((now-start)*1000/duration) * .001
from, to := a.from.ToF32(), a.to.ToF32()
if progress >= 1 {
a.e.scr = to
return false
}
a.e.scr = to.Sub(from).Mul(progress).Add(from)
return true
}
func (l *playLevel) idxToPos(i int) geom.PointF32 { return l.level.idxToPos(i).ToF32() }
func (l *playLevel) isIdle() bool { return l.ani.Idle() }
func findEntityAt(entities []*entity, pos geom.Point) *entity {
idx := findEntityIdx(entities, pos)
if idx == -1 {
return nil
}
return entities[idx]
}
func findEntityIdx(entities []*entity, pos geom.Point) int {
for i, e := range entities {
if e.pos == pos {
return i
}
}
return -1
}
func (l *playLevel) findEntityAt(pos geom.Point) *entity {
if l.player.pos == pos {
return l.player
}
brick := findEntityAt(l.bricks, pos)
if brick != nil {
return brick
}
return findEntityAt(l.sunken, pos)
}
func (l *playLevel) checkTile(pos geom.Point, check func(pos geom.Point, idx int, t tile) bool) bool {
return l.checkTileNotFound(pos, check, false)
}
func (l *playLevel) checkTileNotFound(pos geom.Point, check func(pos geom.Point, idx int, t tile) bool, notFound bool) bool {
idx := l.level.posToIdx(pos)
if idx == -1 {
return notFound
}
return check(pos, idx, l.level.tiles[idx])
}
func (l *playLevel) isSolidTile(pos geom.Point, idx int, t tile) bool {
switch t {
case tileBasic:
return true
case tileWater:
return findEntityAt(l.sunken, pos) != nil
}
return false
}
func (l *playLevel) wouldBrickSink(pos geom.Point, idx int, t tile) bool {
return t == tileWater && findEntityAt(l.sunken, pos) == nil
}
func (l *playLevel) isObstructed(pos geom.Point, idx int, t tile) bool {
if findEntityAt(l.bricks, pos) != nil {
return true // brick
}
switch l.level.tiles[idx] {
case tileWater:
return false
case tileBasic:
return false
}
return true
}
func (l *playLevel) canMove(from, dir geom.Point) bool {
to := from.Add(dir)
if !l.checkTile(to, l.isSolidTile) {
return false
}
brick := findEntityAt(l.bricks, to)
if brick != nil {
brickTo := to.Add(dir)
return !l.checkTileNotFound(brickTo, l.isObstructed, true)
}
return true
}
func (l *playLevel) Enter(ctx *Context) error { func (l *playLevel) Enter(ctx *Context) error {
l.ctx = ctx l.ctx = ctx
l.menu = alui.NewMenu() l.menu = alui.NewMenu()
l.menu.Add("Resume", func() { l.showMenu = false }) l.menu.Add("Resume", func() { l.showMenu = false })
l.menu.Add("Quit to main menu", func() { l.ctx.Navigation.showMainMenu() }) l.menu.Add("Restart", func() { l.ctx.Navigation.PlayLevel(l.packID, l.levelID) })
l.menu.Add("Quit to desktop", func() { l.ctx.Navigation.quit() }) l.menu.Add("Select other level", func() { l.ctx.Navigation.SelectLevel(l.packID) })
l.menu.Add("Quit to main menu", func() { l.ctx.Navigation.ShowMainMenu() })
l.menu.Add("Quit to desktop", func() { l.ctx.Navigation.Quit() })
l.menu.OnEscape = func() { l.showMenu = false }
l.keysDown = keyPressedState{} l.init = true
l.level = l.ctx.Levels[l.name] l.state.Init(l.ctx, l.packID, l.levelID, l.onComplete)
l.bricks = nil
l.sunken = nil
for i, e := range l.level.entities {
switch e {
case entityTypeBrick:
l.bricks = append(l.bricks, newEntity(e, l.level.idxToPos(i)))
case entityTypeCharacter:
l.player = newEntity(e, l.level.idxToPos(i))
case entityTypeVillain:
l.villain = newEntity(e, l.level.idxToPos(i))
}
}
return nil return nil
} }
func (l *playLevel) Leave() {} func (l *playLevel) Leave() {}
func (l *playLevel) posToScreen(p geom.Point) geom.PointF32 { func (l *playLevel) onComplete() {
return l.posToScreenF32(p.ToF32()) menu := alui.NewMenu()
menu.AddChild(alui.NewMargins(&alui.Label{ControlBase: alui.ControlBase{Font: "header"}, Text: "Congratulations", TextAlign: allg5.AlignCenter}, 3*margin, 0, 2*margin))
menu.AddChild(alui.NewMargins(&alui.Label{Text: fmt.Sprintf("You've completed the level in %d steps.", l.state.steps), TextAlign: allg5.AlignCenter}, 0, 0, 2*margin))
progress := l.ctx.Progress.Level(l.packID, l.levelID)
if l.state.steps < progress.Steps || progress.Steps == 0 {
var improvement = progress.Steps - l.state.steps
if improvement > 0 { // first time it is lower than zero (no previous record).
menu.AddChild(alui.NewMargins(&alui.Label{Text: fmt.Sprintf("This is an improvement of %d steps.", improvement), TextAlign: allg5.AlignCenter}, 0, 0, 2*margin))
} }
func (l *playLevel) posToScreenF32(p geom.PointF32) geom.PointF32 { err := l.ctx.Progress.Update(l.packID, l.levelID, func(p *levelProgress) {
pos := p.Add2D(.5, .5) p.Steps = l.state.steps
pos = geom.PtF32(pos.X*148-pos.Y*46, pos.Y*82) })
pos = geom.PtF32(pos.X*l.scale, pos.Y*l.scale) if err != nil {
return pos.Add(l.offset) log.Printf("Unable to store progress; err: %v", err)
}
} }
// <- 168-> nextID, ok := l.state.pack.FindNext(l.levelID)
// <-128-> if ok {
menu.Add("Continue with next", func() { l.ctx.Navigation.PlayLevel(l.packID, nextID) })
}
if l.ctx.Levels.MustSelect() {
menu.Add("Select level pack", func() { l.ctx.Navigation.SelectPack() })
}
menu.Add("Select level", func() { l.ctx.Navigation.SelectLevel(l.packID) })
menu.Add("Go to main menu", func() { l.ctx.Navigation.ShowMainMenu() })
l.end = menu
}
func (l *playLevel) posToScreenF32(p geom.PointF32, z float32) geom.PointF32 {
pos := l.posToCabinet(p.Add2D(.5, .5)).Add2D(0, z)
return pos.Mul(l.scale).Add(l.offset)
}
func (l *playLevel) posToCabinet(p geom.PointF32) geom.PointF32 {
return geom.PtF32(p.X*100-p.Y*50, p.Y*70)
}
// <- 150->
// <-100->
// //
// /----/| ^ ^ // /----/| ^ ^
// / / / | 72 // / / | | 70
// /----/ / 92 v ^ // /----/ | 170 v ^
// |----|/ v v 20 // | | | | |
// | | / | 100
// |----|/ v v
// //
// Gap: 20 // Offset between horizontal tiles: 100,0
// Center: 84,46 // Offset between vertical tiles: -25,70
// Offset between horizontal tiles: 148,0
// Offset between vertical tiles: -46,82
func (l *playLevel) Layout(ctx *alui.Context, bounds geom.RectangleF32) { func (l *playLevel) Layout(ctx *alui.Context, bounds geom.RectangleF32) {
l.scale = bounds.Dy() / 1080 if l.init {
l.scale = 1
l.offset = geom.PointF32{}
tilesCenter := geom.PtF32(.5*float32(l.level.width), .5*float32(l.level.height)) level := l.state.Level()
tilesCenter = geom.PtF32(tilesCenter.X*148-tilesCenter.Y*46, tilesCenter.Y*82) var contentCenter = l.posToScreenF32(geom.PtF32(.5*float32(level.Width), .5*float32(level.Height)), 0)
tilesCenter = geom.PtF32(tilesCenter.X*l.scale, tilesCenter.Y*l.scale) var content = geom.RectF32(contentCenter.X, contentCenter.Y, contentCenter.X, contentCenter.Y)
for idx, tile := range l.state.Level().Tiles {
if tile == soko.TileTypeNothing || tile == soko.TileTypeInvalid {
continue
}
pos := level.IdxToPos(idx).ToF32()
bottomLeft := l.posToScreenF32(pos.Add2D(-1.5, 1.5), 100)
content.Min = geom.MinPtF32(content.Min, bottomLeft)
content.Max = geom.MaxPtF32(content.Max, bottomLeft)
topRight := l.posToScreenF32(pos.Add2D(1.5, -1.5), 0)
content.Min = geom.MinPtF32(content.Min, topRight)
content.Max = geom.MaxPtF32(content.Max, topRight)
}
l.scale = geom.Min32(bounds.Dx()/content.Dx(), bounds.Dy()/content.Dy())
contentCenter = content.Center().Mul(l.scale)
center := bounds.Center() center := bounds.Center()
l.offset = geom.PtF32(center.X-tilesCenter.X, center.Y-tilesCenter.Y) l.offset = geom.PtF32(center.X-contentCenter.X, center.Y-contentCenter.Y)
l.init = false
l.ani.Animate(l.ctx.Tick)
} }
func (l *playLevel) tryPlayerMove(dir geom.Point, key allg5.Key) { l.state.Tick(l.ctx.Tick)
if !l.isIdle() {
return
}
to := l.player.pos.Add(dir)
if !l.canMove(l.player.pos, dir) {
log.Printf("Move is not allowed (tried out move to %s after key '%s' was pressed)", to, gut.KeyToString(key))
return
}
l.steps++
log.Printf("Moving player to %s", to)
l.ani.StartFn(l.ctx.Tick, newEntityMoveAnimation(l.player, to), func() {
log.Printf("Player movement finished")
if l.keysDown[key] && l.keysDown.CountPressed(l.ctx.Settings.Controls.MovementKeys()...) == 1 {
log.Printf("Key %s is still down, moving further", gut.KeyToString(key))
l.tryPlayerMove(dir, key)
}
})
if brick := findEntityAt(l.bricks, to); brick != nil {
log.Printf("Pushing brick at %s", to)
brickTo := to.Add(dir)
l.ani.StartFn(l.ctx.Tick, newEntityMoveAnimation(brick, brickTo), func() {
log.Printf("Brick movement finished")
if l.checkTile(brickTo, l.wouldBrickSink) {
log.Printf("Sinking brick at %s", brickTo)
idx := findEntityIdx(l.bricks, brickTo)
l.bricks = append(l.bricks[:idx], l.bricks[idx+1:]...)
l.sunken = append(l.sunken, brick)
}
})
}
} }
func (l *playLevel) Handle(e allg5.Event) { func (l *playLevel) Handle(e allg5.Event) {
switch e := e.(type) { switch e := e.(type) {
case *allg5.KeyDownEvent: case *allg5.KeyDownEvent:
l.keysDown[e.KeyCode] = true l.state.PressKey(e.KeyCode)
case *allg5.KeyUpEvent: case *allg5.KeyUpEvent:
l.keysDown[e.KeyCode] = false l.state.ReleaseKey(e.KeyCode)
} }
if l.showMenu { switch {
case l.showMenu:
l.menu.Handle(e) l.menu.Handle(e)
switch e := e.(type) { case l.state.complete:
case *allg5.KeyDownEvent: l.end.Handle(e)
switch e.KeyCode { default:
case allg5.KeyEscape:
l.showMenu = false
}
}
return
}
switch e := e.(type) { switch e := e.(type) {
case *allg5.KeyDownEvent: case *allg5.KeyDownEvent:
switch e.KeyCode { switch e.KeyCode {
case allg5.KeyEscape: case allg5.KeyEscape:
l.showMenu = true l.showMenu = true
l.menu.Activate(0) l.menu.Activate(0)
case l.ctx.Settings.Controls.MoveUp: case allg5.KeyF5:
l.tryPlayerMove(geom.Pt(0, -1), e.KeyCode) l.pathFinding = !l.pathFinding
case l.ctx.Settings.Controls.MoveRight: }
l.tryPlayerMove(geom.Pt(1, 0), e.KeyCode) l.state.TryPlayerMove(e.KeyCode)
case l.ctx.Settings.Controls.MoveDown:
l.tryPlayerMove(geom.Pt(0, 1), e.KeyCode)
case l.ctx.Settings.Controls.MoveLeft:
l.tryPlayerMove(geom.Pt(-1, 0), e.KeyCode)
} }
} }
} }
func (l *playLevel) drawSprite(name, partName string, pos entityLoc) {
l.ctx.SpriteDrawer.Draw(name, partName, l.posToScreenF32(pos.pos, pos.z), DrawSpriteOptions{Scale: l.scale})
}
func (l *playLevel) drawSpriteAlpha(name, partName string, pos entityLoc, alpha float32) {
a := byte(alpha * 255)
c := allg5.NewColorAlpha(a, a, a, a)
l.ctx.SpriteDrawer.Draw(name, partName, l.posToScreenF32(pos.pos, pos.z), DrawSpriteOptions{Scale: l.scale, Tint: &c})
}
func (l *playLevel) Render(ctx *alui.Context, bounds geom.RectangleF32) { func (l *playLevel) Render(ctx *alui.Context, bounds geom.RectangleF32) {
basicTile := l.ctx.Textures["basic_tile"] level := l.state.level
waterTile := l.ctx.Textures["water_tile"]
sunkenBrickTile := l.ctx.Textures["sunken_brick_tile"]
opts := allg5.DrawOptions{Center: true, Scale: allg5.NewUniformScale(l.scale * (168 / float32(basicTile.Width())))} drawParticles := func(particles []particle) {
level := l.level for _, p := range particles {
for i, t := range level.tiles { l.drawSpriteAlpha("particles", "splash", entityLoc{p.pos, p.z}, p.opaq)
pos := geom.Pt(i%level.width, i/level.width) }
scrPos := l.posToScreen(pos) }
for i, t := range level.Tiles {
pos := geom.Pt(i%level.Width, i/level.Width)
scr := entityLoc{pos.ToF32(), 0}
switch t { switch t {
case tileBasic: case soko.TileTypeBasic:
basicTile.DrawOptions(scrPos.X, scrPos.Y, opts) if l.state.IsNextToMagma(pos) {
case tileWater: l.drawSprite("lava_brick", "magma", scr)
scrPos := l.posToScreenF32(pos.ToF32().Add2D(0, .2*l.scale))
if findEntityAt(l.sunken, pos) == nil {
waterTile.DrawOptions(scrPos.X, scrPos.Y, opts)
} else { } else {
sunkenBrickTile.DrawOptions(scrPos.X, scrPos.Y, opts) l.drawSprite("lava_brick", "lava_brick", scr)
}
case soko.TileTypeMagma:
l.drawSprite("magma", "magma", scr)
brick := l.state.FindSunkenBrickEntity(pos)
if brick != nil {
behind, front := splitParticles(scr.pos.Y, l.state.Particles(pos))
drawParticles(behind)
l.drawSprite("brick", "brick", brick.scr)
l.drawSprite("magma", "sunken_overlay", scr)
drawParticles(front)
} }
} }
} }
character := l.ctx.Textures["main_character"] entities := l.state.Entities().RenderOrder()
villain := l.ctx.Textures["villain_character"]
brick := l.ctx.Textures["brick"]
crate := l.ctx.Textures["crate"]
var entities []*entity
entities = append(entities, l.player)
entities = append(entities, l.villain)
entities = append(entities, l.bricks...)
sort.Slice(entities, func(i, j int) bool {
if entities[i].scr.Y == entities[j].scr.Y {
return entities[i].scr.X < entities[j].scr.X
}
return entities[i].scr.Y < entities[j].scr.Y
})
for _, e := range entities { for _, e := range entities {
scrPos := l.posToScreenF32(e.scr)
switch e.typ { switch e.typ {
case entityTypeCharacter: case soko.EntityTypeBrick:
scrPos := l.posToScreenF32(e.scr.Add2D(-.2*l.scale, -.9*l.scale)) l.drawSprite("brick", "brick", e.scr)
character.DrawOptions(scrPos.X, scrPos.Y, opts) case soko.EntityTypePlayer:
case entityTypeVillain: l.drawSprite("dragon", "dragon", e.scr)
scrPos := l.posToScreenF32(e.scr.Add2D(-.2*l.scale, -.9*l.scale)) case soko.EntityTypeTarget:
villain.DrawOptions(scrPos.X, scrPos.Y, opts) l.drawSprite("egg", "egg", e.scr)
case entityTypeBrick:
if findEntityAt(l.bricks, e.pos) == nil {
break
}
scrPos := l.posToScreenF32(e.scr.Add2D(-.2*l.scale, -.7*l.scale))
brick.DrawOptions(scrPos.X, scrPos.Y, opts)
case entityTypeCrate:
crate.DrawOptions(scrPos.X, scrPos.Y, opts)
} }
} }
font := ctx.Fonts.Get("default") font := ctx.Fonts.Get("default")
steps := fmt.Sprintf("STEPS: %d", l.steps)
if l.pathFinding {
dists := soko.NewPathFinder(&l.state.state).FindDistances()
for i := range level.Tiles {
pos := geom.Pt(i%level.Width, i/level.Width)
scr := entityLoc{pos.ToF32(), 0}
posDist := l.posToScreenF32(scr.pos, -20)
ctx.Fonts.DrawAlignFont(font, posDist.X, posDist.Y, posDist.X, ctx.Palette.Text, allg5.AlignCenter, strconv.Itoa(dists[i]))
}
}
steps := fmt.Sprintf("STEPS: %d", l.state.Steps())
ctx.Fonts.DrawAlignFont(font, bounds.Min.X, 24, bounds.Max.X, ctx.Palette.Text, allg5.AlignCenter, steps) ctx.Fonts.DrawAlignFont(font, bounds.Min.X, 24, bounds.Max.X, ctx.Palette.Text, allg5.AlignCenter, steps)
if l.showMenu { switch {
case l.showMenu:
allg5.DrawFilledRectangle(bounds.Min.X, bounds.Min.Y, bounds.Max.X, bounds.Max.Y, allg5.NewColorAlpha(0, 0, 0, 0xaf)) allg5.DrawFilledRectangle(bounds.Min.X, bounds.Min.Y, bounds.Max.X, bounds.Max.Y, allg5.NewColorAlpha(0, 0, 0, 0xaf))
l.menu.Render(ctx, bounds) l.menu.Render(ctx, bounds)
case l.state.complete:
allg5.DrawFilledRectangle(bounds.Min.X, bounds.Min.Y, bounds.Max.X, bounds.Max.Y, allg5.NewColorAlpha(0, 0, 0, 0xaf))
l.end.Render(ctx, bounds)
} }
} }

View File

@ -0,0 +1,188 @@
package main
import (
"log"
"time"
"opslag.de/schobers/allg5"
"opslag.de/schobers/geom"
"opslag.de/schobers/krampus19/gut"
"opslag.de/schobers/krampus19/soko"
)
type playLevelState struct {
ctx *Context
pack levelPack
level soko.Level
state soko.State
player *entity
egg *entity
bricks entityMap
sunken entityMap
splash map[geom.Point]*splashAnimation
steps int
complete bool
onComplete func()
tick time.Duration
ani gut.Animations
keysDown keyPressedState
}
func (s *playLevelState) Entities() entityMap {
entities := entityMap{}
entities[s.player.id] = s.player
entities[s.egg.id] = s.egg
for id, e := range s.bricks {
entities[id] = e
}
return entities
}
func (s *playLevelState) Particles(at geom.Point) []particle {
var particles []particle
for pos, ani := range s.splash {
if pos != at {
continue
}
log.Println("Found particles at", at)
for _, p := range ani.particles {
particles = append(particles, p.part)
}
}
return particles
}
func (s *playLevelState) FindSunkenBrickEntity(pos geom.Point) *entity {
idx := s.level.PosToIdx(pos)
if idx == -1 {
return nil
}
id := s.state.SunkenBricks[idx]
if id != -1 {
return s.sunken[id]
}
return nil
}
func (s *playLevelState) IsNextToMagma(pos geom.Point) bool {
return s.state.Any(soko.IsMagma, soko.Neighbours(pos)...)
}
func (s *playLevelState) Init(ctx *Context, pack, level string, onComplete func()) {
s.ctx = ctx
s.pack = ctx.Levels.ByID(pack)
s.level = s.pack.levels[level]
s.state = s.level.State()
s.bricks = nil
s.sunken = nil
s.splash = map[geom.Point]*splashAnimation{}
newEntity := func(e soko.Entity) *entity { return newEntity(e, s.state.IdxToPos[e.Pos]) }
s.player = newEntity(s.state.Player)
s.egg = newEntity(s.state.Target)
s.bricks = entityMap{}
for _, e := range s.state.Entities {
if e.Typ != soko.EntityTypeBrick {
continue
}
s.bricks[e.ID] = newEntity(soko.Entity{ID: e.ID, Pos: e.Pos, Typ: soko.EntityTypeBrick})
}
s.sunken = entityMap{}
s.keysDown = keyPressedState{}
s.onComplete = onComplete
}
func (s *playLevelState) Level() soko.Level { return s.level }
func (s *playLevelState) PressKey(key allg5.Key) {
s.keysDown[key] = true
}
func (s *playLevelState) ReleaseKey(key allg5.Key) {
s.keysDown[key] = false
}
func (s *playLevelState) Steps() int { return s.steps }
func (s *playLevelState) Tick(now time.Duration) {
s.ani.Animate(now)
}
func (s *playLevelState) TryPlayerMove(key allg5.Key) {
var dir soko.Direction
switch key {
case s.ctx.Settings.Controls.MoveUp:
dir = soko.DirectionUp
case s.ctx.Settings.Controls.MoveRight:
dir = soko.DirectionRight
case s.ctx.Settings.Controls.MoveDown:
dir = soko.DirectionDown
case s.ctx.Settings.Controls.MoveLeft:
dir = soko.DirectionLeft
default:
return
}
s.tryPlayerMove(dir)
}
func (s *playLevelState) tryPlayerMove(dir soko.Direction) {
playerPt := s.state.IdxToPos[s.state.Player.Pos]
if s.player.scr.pos != playerPt.ToF32() {
return
}
state, ok := s.state.MovePlayer(dir)
if !ok {
log.Printf("Move is not allowed (tried out move %s)", dir.String())
return
}
to := state.Player.Pos
toPt := state.IdxToPos[to]
if brickID := s.state.Bricks[to]; brickID != -1 {
log.Printf("Brick %d moved", brickID)
brick := s.bricks[brickID]
brickTo := state.Entities.ByID(brickID).Pos
brickToPt := state.IdxToPos[brickTo]
s.ani.StartFn(s.ctx.Tick, newMoveAnimation(brick, toPt, brickToPt), func() {
log.Printf("Brick movement finished")
if sunkenBrickID := state.SunkenBricks[brickTo]; sunkenBrickID == brickID {
log.Printf("Sinking brick %d", brickID)
delete(s.bricks, brickID)
s.sunken[brickID] = brick
s.ani.Start(s.ctx.Tick, newSinkAnimation(brick))
splash := newSplashAnimation(brickToPt)
s.splash[brickToPt] = splash
s.ani.StartFn(s.ctx.Tick, splash, func() {
delete(s.splash, brickToPt)
})
}
})
}
s.steps++
log.Printf("Moving player to %s", toPt)
s.ani.StartFn(s.ctx.Tick, newMoveAnimation(s.player, playerPt, toPt), func() {
log.Printf("Player movement finished")
if to == state.Target.Pos {
s.complete = true
if onComplete := s.onComplete; onComplete != nil {
onComplete()
}
} else {
pressed := s.keysDown.ArePressed(s.ctx.Settings.Controls.MovementKeys()...)
if len(pressed) == 1 {
key := pressed[0]
log.Printf("Movement key %s is down, moving further", gut.KeyToString(key))
s.TryPlayerMove(key)
}
}
})
s.state = state
}

67
cmd/krampus19/progress.go Normal file
View File

@ -0,0 +1,67 @@
package main
type progress struct {
Packs map[string]packProgress
}
func (p *progress) Pack(packID string) packProgress {
if p.Packs == nil {
p.Packs = map[string]packProgress{}
}
return p.Packs[packID]
}
func (p *progress) Level(packID, levelID string) levelProgress {
pack := p.Pack(packID)
return pack.Level(levelID)
}
func (p *progress) Update(packID, levelID string, update func(*levelProgress)) error {
pack := p.Pack(packID)
pack.Update(levelID, update)
p.Packs[packID] = pack
return p.store()
}
type packProgress struct {
Levels map[string]levelProgress
}
func (p *packProgress) Level(id string) levelProgress {
if p.Levels == nil {
p.Levels = map[string]levelProgress{}
}
return p.Levels[id]
}
func (p *packProgress) Update(id string, update func(*levelProgress)) {
level := p.Level(id)
update(&level)
p.Levels[id] = level
}
type levelProgress struct {
Steps int
}
func (p *progress) store() error {
path, err := userFile("progress.json")
if err != nil {
return err
}
return encodeJSON(path, p)
}
func (p *progress) load() error {
path, err := userFile("progress.json")
if err != nil {
return err
}
var fromFile progress
err = decodeJSON(path, &fromFile)
if err != nil {
return err
}
*p = fromFile
return nil
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 719 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 246 KiB

Binary file not shown.

BIN
cmd/krampus19/res/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@ -0,0 +1,11 @@
level:
._._._._._._._._._._
._._._._._._._._._._
._._._._._._._._._._
._._._._._._._._._._
._._._._._._._._._._
._._._._._._._._._._
._._._._._._._._._._
._._._._._._._._._._
._._._._._._._._._._
:level

View File

@ -1,11 +0,0 @@
level:
._._._._._._._._._._
._._#_#_#_._._._._._
._._#_._#B._._._._._
._._#_#_#_._._._._._
._._#_._#B._._._._._
._#@#_#_#_~_~_#_#X._
._._._._~_~_#_._._._
._._._._#_#_#_._._._
._._._._._._._._._._
:level

View File

@ -0,0 +1,21 @@
name: Standard
levels:
level:
id: 1
:level
level:
id: 3
:level
level:
id: 2
:level
level:
id: 4
:level
:levels

View File

@ -0,0 +1,11 @@
level:
._._._._._._._._._._
._#_#_#_#_~_~_~_#_._
._#_#_._#B~_~_#_#_._
._#_#_#_#_~_~_~_#_._
._#_#_._#B~_~_#_#_._
._#@#_#_#_~_~_#_#X._
._#_#_~_~_~_#_#_#_._
._#_#_~_~_~_#_#_#_._
._._._._._._._._._._
:level

View File

@ -0,0 +1,13 @@
level:
._._._._._._._._._._._._._._._._._._._._
._._._._._#_#_#_._._._._._._._._._._._._
._._._._._#B#_#_._._._._._._._._._._._._
._._._._._#_#_#B._._._._._._._._._._._._
._._._#_#_#B#_#B#_._._._._._._._._._._._
._._._#_._#_._._#_._._._._#X#_~_~_~_#_._
._#_#_#_._#_._._#_._._._._._._._~_~_#_._
._#_#B#_#_#B#_#_#_#_#_#_#_#_#_#_~_#_#_._
._._._._._#_._._._#_._#@._._._._#_#_._._
._._._._._#_#_#_#_#_._._._._._._._._._._
._._._._._._._._._._._._._._._._._._._._
:level

View File

@ -0,0 +1,11 @@
level:
._._._._._._._._._._
._._._._._._._._._._
._~_#_#_#_#B#_._._._
._~_#B#_#_._#_._._._
._~_._#_~_#_#_._._._
._#X._#_~_#_._._._._
._._#_#B#_#_._._._._
._._#@#_._._._._._._
._._._._._._._._._._
:level

View File

@ -0,0 +1,16 @@
level:
._._._._._._._._._._._._
._._#_#_._._._._._._._._
._._#_#B#_#B#@#_#_._._._
._._#_#_#_#_#B#_#_._._._
._._._._._._#_._._._._._
._._._._._._#_._._._._._
._._._._._._#B._._._._._
._._._#_#_._#_._#_#_._._
._#_#_#_#_~_#_#_#_#_#_._
._#_._._#_._#_._#_._#_._
._#_._#X~_._~_._~_._#_._
._#_._._#_._#_._#_._#_._
._#_#_#_#_#_~_#_#_#_#_._
._._._._._._._._._._._._
:level

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

View File

@ -0,0 +1,11 @@
sprite:
texture: brick
part:
name: brick
sub_texture: 0,0,1020,1140
anchor: 510,870
scale: 6
:part
:sprite

View File

@ -2,27 +2,10 @@ sprite:
texture: dragon texture: dragon
part: part:
name: body name: dragon
sub_texture: 0,0,2107,1284 sub_texture: 0,0,1140,1980
anchor: 1065,594 anchor: 570,1920
:part scale: 5
part:
name: foot
sub_texture: 42,1345,529,856
anchor: 386,1283
:part
part:
name: upper_wing
sub_texture: 2112,39,1080,651
anchor: 2413,644
:part
part:
name: lower_wing
sub_texture: 2170,764,1030,736
anchor: 2658,799
:part :part
:sprite :sprite

View File

@ -0,0 +1,11 @@
sprite:
texture: egg
part:
name: egg
sub_texture: 0,0,1140,1980
anchor: 570,1860
scale: 6
:part
:sprite

View File

@ -0,0 +1,18 @@
sprite:
texture: lava_brick
part:
name: lava_brick
sub_texture: 0,0,1020,1140
anchor: 510,270
scale: 6
:part
part:
name: magma
sub_texture: 0,1140,1020,1140
anchor: 510,1410
scale: 6
:part
:sprite

View File

@ -0,0 +1,18 @@
sprite:
texture: magma
part:
name: magma
sub_texture: 0,0,1020,1140
anchor: 510,270
scale: 6
:part
part:
name: sunken_overlay
sub_texture: 0,1140,1020,1140
anchor: 510,1410
scale: 6
:part
:sprite

View File

@ -0,0 +1,11 @@
sprite:
texture: particles
part:
name: splash
sub_texture: 0,0,96,96
anchor: 48,48
scale: 6
:part
:sprite

View File

@ -0,0 +1,32 @@
sprite:
texture: ui
part:
name: square
sub_texture: 0,0,448,512
anchor: 224,256
scale: 16
:part
part:
name: check-square
sub_texture: 0,512,448,512
anchor: 224,768
scale: 16
:part
part:
name: angle-left
sub_texture: 768,0,192,512
anchor: 848,196
scale: 16
:part
part:
name: angle-right
sub_texture: 768,512,192,512
anchor: 848,720
scale: 16
:part
:sprite

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 292 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 419 KiB

BIN
cmd/krampus19/res/ui.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.0 KiB

View File

@ -1,10 +1,8 @@
package main package main
import "opslag.de/schobers/allg5" import (
"opslag.de/schobers/allg5"
type settings struct { )
Controls controls
}
func newDefaultSettings() settings { func newDefaultSettings() settings {
return settings{ return settings{
@ -14,9 +12,48 @@ func newDefaultSettings() settings {
MoveDown: allg5.KeyDown, MoveDown: allg5.KeyDown,
MoveLeft: allg5.KeyLeft, MoveLeft: allg5.KeyLeft,
}, },
Video: video{
Windowed: true,
DisplayMode: "",
},
} }
} }
type settings struct {
Controls controls
Video video
}
func (s *settings) DefaultPath() (string, error) { return userFile("settings.json") }
func (s *settings) Load(path string) error {
var fromFile settings
err := decodeJSON(path, &fromFile)
if err != nil {
return err
}
*s = fromFile
return nil
}
func (s *settings) LoadDefault() error {
path, err := s.DefaultPath()
if err != nil {
return err
}
return s.Load(path)
}
func (s *settings) Store(path string) error { return encodeJSON(path, s) }
func (s *settings) StoreDefault() error {
path, err := s.DefaultPath()
if err != nil {
return err
}
return s.Store(path)
}
type controls struct { type controls struct {
MoveUp allg5.Key MoveUp allg5.Key
MoveRight allg5.Key MoveRight allg5.Key
@ -24,6 +61,11 @@ type controls struct {
MoveLeft allg5.Key MoveLeft allg5.Key
} }
type video struct {
Windowed bool
DisplayMode string
}
func (c controls) MovementKeys() []allg5.Key { func (c controls) MovementKeys() []allg5.Key {
return []allg5.Key{c.MoveUp, c.MoveRight, c.MoveDown, c.MoveLeft} return []allg5.Key{c.MoveUp, c.MoveRight, c.MoveDown, c.MoveLeft}
} }

View File

@ -1,11 +1,8 @@
package main package main
import ( import (
"math"
"time" "time"
"opslag.de/schobers/allg5"
"opslag.de/schobers/geom" "opslag.de/schobers/geom"
"opslag.de/schobers/krampus19/alui" "opslag.de/schobers/krampus19/alui"
) )
@ -20,26 +17,5 @@ type splash struct {
} }
func (s *splash) Render(ctx *alui.Context, bounds geom.RectangleF32) { func (s *splash) Render(ctx *alui.Context, bounds geom.RectangleF32) {
var dragon = s.ctx.Sprites["dragon"] s.atEnd = true
var texture = s.ctx.Textures[dragon.texture]
var body = texture.Subs["body"]
var upperWing = texture.Subs["upper_wing"]
var lowerWing = texture.Subs["lower_wing"]
var foot = texture.Subs["foot"]
scale := bounds.Dy() / 1600
var repeat = 2 * time.Second / time.Millisecond
var tick = float64((s.ctx.Tick / time.Millisecond) % repeat)
flap := .5*float32(math.Cos(tick*2*math.Pi/float64(repeat))) + .5 // [0..1]
upperFlap := flap*.75 + .25 // [.25..1]
lowerFlap := flap*.5 + .5 // [.5..1]
body.DrawOptions(0, 0, allg5.DrawOptions{Scale: allg5.NewUniformScale(scale)})
foot.DrawOptions(750*scale, 500*scale, allg5.DrawOptions{Scale: allg5.NewUniformScale(scale)})
var upperWingOffset = float32(upperWing.Height()) * scale * (1 - flap) * .8
upperWing.DrawOptions(750*scale, -100*scale+upperWingOffset, allg5.DrawOptions{Scale: allg5.NewScale(scale, scale*upperFlap)})
lowerWing.DrawOptions(750*scale, -100*scale+upperWingOffset*.95, allg5.DrawOptions{Scale: allg5.NewScale(scale, scale*lowerFlap)})
} }

View File

@ -7,6 +7,7 @@ import (
"strings" "strings"
"opslag.de/schobers/geom" "opslag.de/schobers/geom"
"opslag.de/schobers/krampus19/gut"
) )
type sprite struct { type sprite struct {
@ -14,16 +15,26 @@ type sprite struct {
parts []spritePart parts []spritePart
} }
func (s sprite) FindPartByName(name string) spritePart {
for _, part := range s.parts {
if part.name == name {
return part
}
}
return spritePart{}
}
type spritePart struct { type spritePart struct {
name string name string
sub geom.Rectangle sub geom.Rectangle
anchor geom.Point anchor geom.Point
scale float32
} }
func loadSpriteAsset(r io.Reader) (sprite, error) { func loadSpriteAsset(r io.Reader) (sprite, error) {
var l sprite var l sprite
ctx := spriteContext{&l, nil} ctx := spriteContext{&l, nil}
err := parseLines(r, ctx.parse) err := gut.ParseLines(r, ctx.parse)
if err != nil { if err != nil {
return sprite{}, err return sprite{}, err
} }
@ -35,51 +46,51 @@ type spriteContext struct {
part *spritePart part *spritePart
} }
func (c *spriteContext) parse(p *lineParser) parseLineFn { func (c *spriteContext) parse(p *gut.LineParser) gut.ParseLineFn {
if p.skipSpaceEOF() { if p.SkipSpaceEOF() {
return nil return nil
} }
line := p.peek() line := p.Peek()
switch { switch {
case strings.HasPrefix(line, "sprite:"): case strings.HasPrefix(line, "sprite:"):
p.next() p.Next()
return c.parseContent return c.parseContent
default: default:
return nil return nil
} }
} }
func (c *spriteContext) parseContent(p *lineParser) parseLineFn { func (c *spriteContext) parseContent(p *gut.LineParser) gut.ParseLineFn {
const partTag = "part:" const partTag = "part:"
const textureTag = "texture:" const textureTag = "texture:"
const spriteEndTag = ":sprite" const spriteEndTag = ":sprite"
if p.skipSpaceEOF() { if p.SkipSpaceEOF() {
return p.emitErr(errUnexpectedEnd) return p.EmitErr(gut.ErrUnexpectedEnd)
} }
line := p.peek() line := p.Peek()
switch { switch {
case strings.HasPrefix(line, textureTag): case strings.HasPrefix(line, textureTag):
c.sprite.texture = strings.TrimSpace(line[len(textureTag):]) c.sprite.texture = strings.TrimSpace(line[len(textureTag):])
p.next() p.Next()
return c.parseContent return c.parseContent
case line == partTag: case line == partTag:
p.next() p.Next()
c.part = &spritePart{} c.part = &spritePart{}
return c.parsePart return c.parsePart
case line == spriteEndTag: case line == spriteEndTag:
return nil return nil
} }
return p.emitErr(errors.New("unexpected content of sprite")) return p.EmitErr(errors.New("unexpected content of sprite"))
} }
func (c *spriteContext) parsePart(p *lineParser) parseLineFn { func (c *spriteContext) parsePart(p *gut.LineParser) gut.ParseLineFn {
mustAtois := func(s ...string) []int { mustAtois := func(s ...string) []int {
res := make([]int, len(s)) res := make([]int, len(s))
var err error var err error
for i, s := range s { for i, s := range s {
res[i], err = strconv.Atoi(s) res[i], err = strconv.Atoi(s)
if err != nil { if err != nil {
panic("string does not represent an integer") panic("string does not represent an integer number")
} }
} }
return res return res
@ -88,18 +99,26 @@ func (c *spriteContext) parsePart(p *lineParser) parseLineFn {
coords := strings.Split(strings.TrimSpace(s), ",") coords := strings.Split(strings.TrimSpace(s), ",")
return mustAtois(coords...) return mustAtois(coords...)
} }
mustAtof := func(s string) float32 {
f, err := strconv.ParseFloat(strings.TrimSpace(s), 32)
if err != nil {
panic("string does not represent an floating point number")
}
return float32(f)
}
const nameTag = "name:" const nameTag = "name:"
const subTextureTag = "sub_texture:" const subTextureTag = "sub_texture:"
const anchorTag = "anchor:" const anchorTag = "anchor:"
const scaleTag = "scale:"
const partEndTag = ":part" const partEndTag = ":part"
if p.skipSpaceEOF() { if p.SkipSpaceEOF() {
return p.emitErr(errUnexpectedEnd) return p.EmitErr(gut.ErrUnexpectedEnd)
} }
line := p.peek() line := p.Peek()
switch { switch {
case strings.HasPrefix(line, nameTag): case strings.HasPrefix(line, nameTag):
c.part.name = strings.TrimSpace(line[len(nameTag):]) c.part.name = strings.TrimSpace(line[len(nameTag):])
p.next() p.Next()
return c.parsePart return c.parsePart
case strings.HasPrefix(line, subTextureTag): case strings.HasPrefix(line, subTextureTag):
var coords = mustCoords(line[len(subTextureTag):]) var coords = mustCoords(line[len(subTextureTag):])
@ -107,7 +126,7 @@ func (c *spriteContext) parsePart(p *lineParser) parseLineFn {
panic("expected four coordinates (min x, min y, size x, size y)") panic("expected four coordinates (min x, min y, size x, size y)")
} }
c.part.sub = geom.Rect(coords[0], coords[1], coords[0]+coords[2], coords[1]+coords[3]) c.part.sub = geom.Rect(coords[0], coords[1], coords[0]+coords[2], coords[1]+coords[3])
p.next() p.Next()
return c.parsePart return c.parsePart
case strings.HasPrefix(line, anchorTag): case strings.HasPrefix(line, anchorTag):
var coords = mustCoords(line[len(anchorTag):]) var coords = mustCoords(line[len(anchorTag):])
@ -115,12 +134,16 @@ func (c *spriteContext) parsePart(p *lineParser) parseLineFn {
panic("expected two coordinates (min x, min y)") panic("expected two coordinates (min x, min y)")
} }
c.part.anchor = geom.Pt(coords[0], coords[1]) c.part.anchor = geom.Pt(coords[0], coords[1])
p.next() p.Next()
return c.parsePart
case strings.HasPrefix(line, scaleTag):
c.part.scale = mustAtof(line[len(scaleTag):])
p.Next()
return c.parsePart return c.parsePart
case line == partEndTag: case line == partEndTag:
c.sprite.parts = append(c.sprite.parts, *c.part) c.sprite.parts = append(c.sprite.parts, *c.part)
p.next() p.Next()
return c.parseContent return c.parseContent
} }
return p.emitErr(errors.New("unexpected content of part")) return p.EmitErr(errors.New("unexpected content of part"))
} }

View File

@ -0,0 +1,69 @@
package main
import (
"opslag.de/schobers/allg5"
"opslag.de/schobers/geom"
)
type DrawSpriteOptions struct {
Scale float32
Tint *allg5.Color
}
type SpriteDrawer struct {
ctx *Context
}
func (d SpriteDrawer) scale(sprite, user float32) float32 {
var scale float32 = 1
if sprite != 0 {
scale *= 1 / sprite
}
if user != 0 {
scale *= user
}
return scale
}
func (d SpriteDrawer) Draw(name, partName string, pos geom.PointF32, opts DrawSpriteOptions) bool {
sprite, ok := d.ctx.Sprites[name]
if !ok {
return false
}
text, ok := d.ctx.Textures[sprite.texture]
if !ok {
return false
}
partText, ok := text.Subs[partName]
if !ok {
return false
}
part := sprite.FindPartByName(partName)
scale := d.scale(part.scale, opts.Scale)
anchor := part.sub.Min.Sub(part.anchor).ToF32().Mul(scale)
scrPos := pos.Add(anchor)
left, top := scrPos.X, scrPos.Y
var drawOpts allg5.DrawOptions
if scale != 1 {
drawOpts.Scale = allg5.NewUniformScale(scale)
}
if opts.Tint != nil {
drawOpts.Tint = opts.Tint
}
partText.DrawOptions(left, top, drawOpts)
return true
}
func (d SpriteDrawer) Size(name, partName string) geom.PointF32 {
return d.SizeScale(name, partName, 0)
}
func (d SpriteDrawer) SizeScale(name, partName string, scale float32) geom.PointF32 {
sprite, ok := d.ctx.Sprites[name]
if !ok {
return geom.PointF32{}
}
part := sprite.FindPartByName(partName)
scale = d.scale(part.scale, scale)
return part.sub.Size().ToF32().Mul(scale)
}

148
cmd/tilewarp/tilewarp.go Normal file
View File

@ -0,0 +1,148 @@
package main
import (
"image"
"image/color"
"image/png"
"log"
"os"
)
func main() {
err := run()
if err != nil {
log.Fatal(err)
}
}
func loadPNG(path string) (image.Image, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return png.Decode(f)
}
func storePNG(path string, im image.Image) error {
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
return png.Encode(f, im)
}
type warpFn func(image.Image) image.Image
func warp(path string, warp warpFn) error {
im, err := loadPNG(path)
if err != nil {
return err
}
warped := warp(im)
return storePNG(path, warped)
}
type warpTile struct {
im image.Image
right int
farRight int
top int
farTop int
src tile
dst tile
yOffset int
}
type tile struct {
width int
height int
}
func (w warpTile) ColorModel() color.Model { return w.im.ColorModel() }
func (w warpTile) Bounds() image.Rectangle {
bounds := w.im.Bounds()
bounds.Max.Y = bounds.Dy() * w.dst.height / w.src.height
return bounds
}
func (w warpTile) At(x, y int) color.Color {
offset := image.Point{}
for x >= w.dst.width {
x -= w.dst.width
offset.X += w.src.width
}
for y >= w.dst.height {
y -= w.dst.height
offset.Y += w.src.height
}
y += w.yOffset
if y >= w.top && x < w.right {
return w.im.At(x+offset.X, y-6*30+offset.Y)
}
isTopSide := func() bool {
if y >= w.top {
return false
}
if x < w.right {
return true
}
sideX := w.farRight - (w.farRight-w.right)*(y-w.farTop)/(w.top-w.farTop)
return x < sideX
}
if isTopSide() {
srcY := w.farTop + (6*40)*(y-w.farTop)/(w.top-w.farTop)
return w.im.At(x+offset.X, srcY+offset.Y)
}
srcY := y - (6*30)*(w.farRight-x)/(w.farRight-w.right)
srcBottom := 6 * 160
if srcY > srcBottom {
srcY = srcBottom
}
return w.im.At(x+offset.X, srcY+offset.Y)
}
func run() error {
warp("../krampus19/res/tile_lava_brick.png", func(im image.Image) image.Image {
return &warpTile{
im: im,
dst: tile{width: 6 * 170, height: 6 * 190},
src: tile{width: 6 * 170, height: 6 * 160},
right: 6 * 110,
farRight: 6 * 160,
top: 6 * 80,
farTop: 6 * 10,
}
})
warp("../krampus19/res/tile_magma.png", func(im image.Image) image.Image {
return &warpTile{
im: im,
dst: tile{width: 6 * 170, height: 6 * 190},
src: tile{width: 6 * 170, height: 6 * 160},
right: 6 * 110,
farRight: 6 * 160,
top: 6 * 100,
farTop: 6 * 30,
}
})
warp("../krampus19/res/entity_brick.png", func(im image.Image) image.Image {
return &warpTile{
im: im,
dst: tile{width: 6 * 170, height: 6 * 190},
src: tile{width: 6 * 170, height: 6 * 160},
yOffset: 18,
right: 6 * 100,
farRight: 6 * 150,
top: 6 * 100,
farTop: 6 * 30,
}
})
return nil
}

View File

@ -18,10 +18,6 @@ type animation struct {
done AnimationDoneFn done AnimationDoneFn
} }
func (a *Animations) Idle() bool {
return len(a.anis) == 0
}
func (a *Animations) Start(now time.Duration, ani Animation) { func (a *Animations) Start(now time.Duration, ani Animation) {
a.StartFn(now, ani, nil) a.StartFn(now, ani, nil)
} }

View File

@ -13,6 +13,9 @@ type Console struct {
func (c *Console) Write(p []byte) (int, error) { func (c *Console) Write(p []byte) (int, error) {
c.messages = append(c.messages, string(bytes.TrimRight(p, "\r\n"))) c.messages = append(c.messages, string(bytes.TrimRight(p, "\r\n")))
if len(c.messages) > 1000 {
c.messages = c.messages[1:]
}
return len(p), nil return len(p), nil
} }

66
gut/lineparser.go Normal file
View File

@ -0,0 +1,66 @@
package gut
import (
"errors"
"io"
"io/ioutil"
"strings"
)
type LineParser struct {
lines []string
i int
err error
}
var ErrUnexpectedEnd = errors.New("unexpected end of file")
func (p *LineParser) EOF() bool { return p.i == len(p.lines) }
func (p *LineParser) EmitErr(err error) ParseLineFn {
p.err = err
return nil
}
func (p *LineParser) Next() string {
i := p.i
p.i++
return p.lines[i]
}
func (p *LineParser) Peek() string { return p.lines[p.i] }
func (p *LineParser) SkipSpaceEOF() bool {
for !p.EOF() && len(strings.TrimSpace(p.Peek())) == 0 {
p.Next()
}
return p.EOF()
}
func SkipSpaceBeforeContent(next ParseLineFn) ParseLineFn {
return func(p *LineParser) ParseLineFn {
if p.SkipSpaceEOF() {
return p.EmitErr(ErrUnexpectedEnd)
}
return next
}
}
type ParseLineFn func(p *LineParser) ParseLineFn
func ParseLines(r io.Reader, fn ParseLineFn) error {
content, err := ioutil.ReadAll(r)
if err != nil {
return err
}
lines := strings.Split(string(content), "\n")
for i, line := range lines {
lines[i] = strings.TrimRight(line, "\r\n")
}
parser := &LineParser{lines: lines}
for fn != nil {
fn = fn(parser)
}
return parser.err
}

64
soko/direction.go Normal file
View File

@ -0,0 +1,64 @@
package soko
import "opslag.de/schobers/geom"
type Direction int
const (
DirectionUp Direction = iota
DirectionRight
DirectionDown
DirectionLeft
)
var Directions = [4]Direction{DirectionUp, DirectionRight, DirectionDown, DirectionLeft}
func (d Direction) Invert() Direction {
switch d {
case DirectionUp:
return DirectionDown
case DirectionRight:
return DirectionLeft
case DirectionDown:
return DirectionUp
case DirectionLeft:
return DirectionRight
}
panic("invalid direction")
}
func (d Direction) String() string {
switch d {
case DirectionUp:
return "up"
case DirectionRight:
return "right"
case DirectionDown:
return "down"
case DirectionLeft:
return "left"
}
return "invalid"
}
func (d Direction) ToPoint() geom.Point {
switch d {
case DirectionUp:
return geom.Pt(0, -1)
case DirectionRight:
return geom.Pt(1, 0)
case DirectionDown:
return geom.Pt(0, 1)
case DirectionLeft:
return geom.Pt(-1, 0)
}
return geom.Point{}
}
func Neighbours(p geom.Point) []geom.Point {
neighbours := make([]geom.Point, 4)
for i, dir := range Directions {
neighbours[i] = p.Add(dir.ToPoint())
}
return neighbours
}

48
soko/entity.go Normal file
View File

@ -0,0 +1,48 @@
package soko
type Entity struct {
ID int
Pos int
Typ EntityType
}
type Entities []Entity
func (e Entities) ByID(id int) Entity {
idx := e.IdxById(id)
if idx == -1 {
return Entity{ID: -1}
}
return e[idx]
}
func (e Entities) Clone() Entities {
clone := make(Entities, len(e))
copy(clone, e)
return clone
}
func (e Entities) IdxById(id int) int {
for i, e := range e {
if e.ID == id {
return i
}
}
return -1
}
type Ints []int
func NewInts(n int) Ints {
ids := make(Ints, n)
for i := range ids {
ids[i] = -1
}
return ids
}
func (e Ints) Clone() Ints {
clone := make(Ints, len(e))
copy(clone, e)
return clone
}

31
soko/entitylocations.go Normal file
View File

@ -0,0 +1,31 @@
package soko
import "opslag.de/schobers/geom"
type EntityLocations map[geom.Point]int
func (l EntityLocations) Add(p geom.Point, id int) { l[p] = id }
func (l EntityLocations) Clone() EntityLocations {
clone := EntityLocations{}
for p, id := range l {
clone[p] = id
}
return clone
}
func (l EntityLocations) Has(p geom.Point) bool {
_, ok := l[p]
return ok
}
func (l EntityLocations) Move(from, to geom.Point) {
id, ok := l[from]
if !ok {
panic("no entitiy at position")
}
l.Remove(from)
l.Add(to, id)
}
func (l EntityLocations) Remove(p geom.Point) { delete(l, p) }

23
soko/entitytype.go Normal file
View File

@ -0,0 +1,23 @@
package soko
type EntityType byte
const (
EntityTypeInvalid EntityType = EntityType(0)
EntityTypeNone = '_'
EntityTypePlayer = '@'
EntityTypeTarget = 'X'
EntityTypeBrick = 'B'
)
func (e EntityType) IsValid() bool {
switch e {
case EntityTypeNone:
case EntityTypePlayer:
case EntityTypeTarget:
case EntityTypeBrick:
default:
return false
}
return true
}

91
soko/level.go Normal file
View File

@ -0,0 +1,91 @@
package soko
import (
"opslag.de/schobers/geom"
)
type Level struct {
Width int
Height int
Tiles []TileType
Entities []EntityType
}
func (l Level) IdxToPos(i int) geom.Point { return geom.Pt(i%l.Width, i/l.Width) }
func (l Level) PosToIdx(p geom.Point) int {
if p.X < 0 || p.Y < 0 || p.X >= l.Width || p.Y >= l.Height {
return -1
}
return p.Y*l.Width + p.X
}
func (l Level) Moves() []Moves {
moves := make([]Moves, len(l.Tiles))
w := l.Width
for y := 0; y < l.Height; y++ {
for x := 0; x < w; x++ {
var m Moves
idx := y*w + x
if y > 0 {
m.Valid = append(m.Valid, idx-w)
m.All[DirectionUp] = idx - w
} else {
m.All[DirectionUp] = -1
}
if y < (l.Height - 1) {
m.Valid = append(m.Valid, idx+w)
m.All[DirectionDown] = idx + w
} else {
m.All[DirectionDown] = -1
}
if x > 0 {
m.Valid = append(m.Valid, idx-1)
m.All[DirectionLeft] = idx - 1
} else {
m.All[DirectionLeft] = idx - 1
}
if x < (w - 1) {
m.Valid = append(m.Valid, idx+1)
m.All[DirectionRight] = idx + 1
} else {
m.All[DirectionRight] = idx + 1
}
moves[idx] = m
}
}
return moves
}
func (l Level) MoveIdx(idx int, dir Direction) int {
switch dir {
case DirectionUp:
if idx < l.Width {
return -1
}
return idx - l.Width
case DirectionRight:
if (idx+1)%l.Width == 0 {
return -1
}
return idx + 1
case DirectionDown:
if idx >= (l.Width*l.Height)-l.Width {
return -1
}
return idx + l.Width
case DirectionLeft:
if idx%l.Width == 0 {
return -1
}
return idx - 1
}
return -1
}
func (l Level) Size() int { return l.Width * l.Height }
func (l Level) State() State {
return NewState(l)
}

85
soko/levelparser.go Normal file
View File

@ -0,0 +1,85 @@
package soko
import (
"errors"
"fmt"
"io"
"opslag.de/schobers/krampus19/gut"
)
func ParseLevel(r io.Reader) (Level, error) {
var l Level
ctx := levelContext{&l}
err := gut.ParseLines(r, ctx.parse)
if err != nil {
return Level{}, err
}
return l, nil
}
type levelContext struct {
level *Level
}
func (c *levelContext) parse(p *gut.LineParser) gut.ParseLineFn {
if p.EOF() {
return nil
}
switch p.Peek() {
case "level:":
return c.parseContent
case "":
p.Next() // skip
return c.parse
default:
return nil
}
}
func (c *levelContext) parseContent(p *gut.LineParser) gut.ParseLineFn {
if p.Next() != "level:" {
return p.EmitErr(errors.New("expected level start"))
}
return c.parseRow
}
func (c *levelContext) parseRow(p *gut.LineParser) gut.ParseLineFn {
if p.EOF() {
return p.EmitErr(errors.New("unexpected end of file"))
}
line := p.Next()
if line == ":level" {
return c.parse
}
if c.level.Height == 0 {
c.level.Width = len(line) / 2
}
return c.addRow(p, line)
}
func (c *levelContext) addRow(p *gut.LineParser, line string) gut.ParseLineFn {
var tiles []TileType
var entities []EntityType
for i := 0; i < len(line); i += 2 {
tiles = append(tiles, TileType(line[i]))
entities = append(entities, EntityType(line[i+1]))
}
for i, t := range tiles {
if !t.IsValid() {
return p.EmitErr(fmt.Errorf("level contains invalid TileType at (%d, %d)", i, c.level.Height))
}
}
for i, e := range entities {
if !e.IsValid() {
return p.EmitErr(fmt.Errorf("level contains invalid entity type at (%d, %d)", i, c.level.Height))
}
}
c.level.Height++
c.level.Tiles = append(c.level.Tiles, tiles...)
c.level.Entities = append(c.level.Entities, entities...)
return c.parseRow
}

17
soko/locations.go Normal file
View File

@ -0,0 +1,17 @@
package soko
import "opslag.de/schobers/geom"
type Locations map[geom.Point]bool
func (l Locations) Add(p geom.Point) { l[p] = true }
func (l Locations) Clone() Locations {
clone := Locations{}
for p := range l {
clone[p] = true
}
return clone
}
func (l Locations) Remove(p geom.Point) { delete(l, p) }

6
soko/moves.go Normal file
View File

@ -0,0 +1,6 @@
package soko
type Moves struct {
All [4]int
Valid []int
}

133
soko/pathfinder.go Normal file
View File

@ -0,0 +1,133 @@
package soko
import (
"sort"
)
type PathFinder struct {
state *State
moves []Moves
}
func NewPathFinder(s *State) PathFinder {
return PathFinder{s, nil}
}
func NewPathFinderMoves(s *State, moves []Moves) PathFinder {
return PathFinder{s, moves}
}
func (p PathFinder) Find(target int) []int {
source := p.state.Player.Pos
level := p.state.Level
size := level.Size()
distances := NewInts(size)
distances[source] = 0
moves := NewInts(size)
moves[source] = source
state := p.newPathFinderState(source)
heuristic := func(i int) int {
idx := state.frontier[i]
return distances[idx] + p.state.IdxToPos[idx].DistInt(p.state.IdxToPos[target])
}
for {
curr := state.frontier[0]
if curr == target {
break
}
state.frontier = state.frontier[1:]
state.findBetterNeighbours(distances, curr, func(nextIdx, newDistance int) {
moves[nextIdx] = curr
})
if len(state.frontier) == 0 {
return nil // no path
}
// apply heuristic to frontier (favor points closer to target)
sort.Slice(state.frontier, func(i, j int) bool { return heuristic(i) < heuristic(j) })
}
// build reverse path
curr := target
path := []int{curr}
for {
curr = moves[curr]
if curr == source {
break
}
path = append(path, curr)
}
// reverse path
n := len(path)
for i := 0; i < n/2; i++ {
path[i], path[n-i-1] = path[n-i-1], path[i]
}
return path
}
func (p PathFinder) FindDistances() Ints {
source := p.state.Player.Pos
level := p.state.Level
size := level.Size()
distances := NewInts(size)
distances[source] = 0
state := p.newPathFinderState(source)
for {
curr := state.frontier[0]
state.frontier = state.frontier[1:]
state.findBetterNeighbours(distances, curr, nil)
if len(state.frontier) == 0 {
return distances
}
}
}
func (p PathFinder) newPathFinderState(source int) *pathFinderState {
return &pathFinderState{p.state, append(make([]int, 0, p.state.Level.Size()), source), p.moves}
}
type pathFinderState struct {
state *State
frontier []int
moves []Moves
}
type betterNeighbourFn func(int, int)
func (s *pathFinderState) findBetterNeighbours(distances []int, curr int, better betterNeighbourFn) {
currDistance := distances[curr]
newDistance := currDistance + 1
var moves []int
if s.moves == nil {
for _, dir := range Directions {
nextIdx := s.state.Level.MoveIdx(curr, dir)
if nextIdx == -1 {
continue
}
moves = append(moves, nextIdx)
}
} else {
moves = s.moves[curr].Valid
}
for _, nextIdx := range moves {
if distance := distances[nextIdx]; distance != -1 && distance <= newDistance { // skip when shorter path exists
continue
}
if !s.state.Walkable[nextIdx] || s.state.Bricks[nextIdx] != -1 { // filter neighbours
continue
}
distances[nextIdx] = newDistance
s.frontier = append(s.frontier, nextIdx)
if better == nil {
continue
}
better(nextIdx, newDistance)
}
}

94
soko/solver.go Normal file
View File

@ -0,0 +1,94 @@
package soko
func Solve(l Level) int {
state := l.State()
return solve(state)
}
func solve(state State) int {
level := state.Level
target := state.Target.Pos
costs := &stateCostQueue{}
costs.Put(&stateCost{&state, 0, nil})
costsByPlayerIdx := make([][]*stateCost, level.Size())
findCost := func(s *State) *stateCost {
costs := costsByPlayerIdx[s.Player.Pos]
for i := 0; i < len(costs); i++ {
if !costs[i].state.Equal(s) {
continue
}
return costs[i]
}
return nil
}
addCost := func(next *State, nextCost int) {
cost := findCost(next)
if cost == nil {
newCost := &stateCost{next, nextCost, nil}
costs.Put(newCost)
player := next.Player.Pos
costsByPlayerIdx[player] = append(costsByPlayerIdx[player], newCost)
} else if nextCost < cost.cost {
cost.cost = nextCost
costs.Update(cost)
}
}
moves := level.Moves()
type direction struct {
dir Direction
inverse Direction
}
dirs := make([]direction, 4)
for _, dir := range Directions {
dirs[dir] = direction{dir, dir.Invert()}
}
for {
curr := costs.Get()
currPlayerPos := curr.state.Player.Pos
if currPlayerPos == target {
return curr.cost
}
if curr.distances == nil {
curr.distances = NewPathFinderMoves(curr.state, moves).FindDistances()
}
distances := curr.distances
for _, e := range curr.state.Entities {
idx := e.Pos
if e.Typ != EntityTypeBrick || curr.state.SunkenBricks[idx] == e.ID {
continue
}
for i := 0; i < 4; i++ {
player := moves[e.Pos].All[dirs[i].inverse]
if player == -1 {
continue
}
walk := distances[player]
if walk == -1 {
continue
}
if !curr.state.IsOpenForBrick(curr.state.IdxToPos[moves[e.Pos].All[i]]) {
continue
}
curr.state.Player.Pos = player
next, ok := curr.state.MovePlayer(dirs[i].dir)
if !ok {
panic("should be a valid move")
}
nextCost := curr.cost + walk + 1
addCost(&next, nextCost)
}
}
curr.state.Player.Pos = currPlayerPos
if walk := distances[target]; walk != -1 {
next := curr.state.Clone()
next.Player.Pos = target
nextCost := curr.cost + walk
addCost(&next, nextCost)
}
if costs.Empty() {
return -1
}
}
}

111
soko/solver_test.go Normal file
View File

@ -0,0 +1,111 @@
package soko
import (
"bytes"
"testing"
"github.com/stretchr/testify/assert"
)
var levelBenchmark = `level:
._._._._._._._._._._._._._._._._._._._._
._._._._._#_#_#_._._._._._._._._._._._._
._._._._._#_#_#_._._._._._._._._._._._._
._._._._._#_#_#_._._._._._._._._._._._._
._._._#_#_#_#_#_#_._._._._._._._._._._._
._._._#_._#_._._#_._._._._#X#_#_~_#_#_._
._#_#_#_._#_._._#_._._._._._._._~_#_#_._
._#_#B#_#_#B#_#_#_#_#_#_#_#_#_#_#_#_#_._
._._._._._#_._._._#_._#@._._._._#_#_._._
._._._._._#_#_#_#_#_._._._._._._._._._._
._._._._._._._._._._._._._._._._._._._._
:level`
var levelEasy = `level:
._._._._._._._._._._
._#@#_#_#B#_~_#_#X._
._._._._._._._._._._
:level`
var level1 = `level:
._._._._._._._._._._
._#_#_#_#_~_~_~_#_._
._#_#_._#B~_~_#_#_._
._#_#_#_#_~_~_~_#_._
._#_#_._#B~_~_#_#_._
._#@#_#_#_~_~_#_#X._
._#_#_~_~_~_#_#_#_._
._#_#_~_~_~_#_#_#_._
._._._._._._._._._._
:level`
var level2 = `level:
._._._._._._._._._._._._._._._._._._._._
._._._._._#_#_#_._._._._._._._._._._._._
._._._._._#B#_#_._._._._._._._._._._._._
._._._._._#_#_#B._._._._._._._._._._._._
._._._#_#_#B#_#B#_._._._._._._._._._._._
._._._#_._#_._._#_._._._._#X#_~_~_~_#_._
._#_#_#_._#_._._#_._._._._._._._~_~_#_._
._#_#B#_#_#B#_#_#_#_#_#_#_#_#_#_~_#_#_._
._._._._._#_._._._#_._#@._._._._#_#_._._
._._._._._#_#_#_#_#_._._._._._._._._._._
._._._._._._._._._._._._._._._._._._._._
:level`
var level3 = `level:
._._._._._._._._._._
._._._._._._._._._._
._~_#_#_#_#B#_._._._
._~_#B#_#_._#_._._._
._~_._#_~_#_#_._._._
._#X._#_~_#_._._._._
._._#_#B#_#_._._._._
._._#@#_._._._._._._
._._._._._._._._._._
:level`
var level4 = `level:
._._._._._._._._._._._._
._._#_#_._._._._._._._._
._._#_#B#_#B#@#_#_._._._
._._#_#_#_#_#B#_#_._._._
._._._._._._#_._._._._._
._._._._._._#_._._._._._
._._._._._._#B._._._._._
._._._#_#_._#_._#_#_._._
._#_#_#_#_~_#_#_#_#_#_._
._#_._._#_._#_._#_._#_._
._#_._#X~_._~_._~_._#_._
._#_._._#_._#_._#_._#_._
._#_#_#_#_#_~_#_#_#_#_._
._._._._._._._._._._._._
:level`
func mustParseLevel(s string) Level {
l, err := ParseLevel(bytes.NewBufferString(s))
if err != nil {
panic("couldn't parse level")
}
return l
}
func TestSolver(t *testing.T) {
solve := func(s string) int {
l := mustParseLevel(s)
steps := Solve(l)
return steps
}
assert.Equal(t, 7, solve(levelEasy))
assert.Equal(t, 35, solve(level1))
// assert.Equal(t, -1, solve(level2))
assert.Equal(t, 49, solve(level3))
// assert.Equal(t, -1, solve(level4))
}
func BenchmarkSolver(b *testing.B) {
l := mustParseLevel(levelBenchmark)
for n := 0; n < b.N; n++ {
Solve(l)
}
}

240
soko/state.go Normal file
View File

@ -0,0 +1,240 @@
package soko
import "opslag.de/schobers/geom"
type State struct {
Player Entity
Target Entity
Entities Entities
Level Level
IdxToPos []geom.Point
Bricks Ints
SunkenBricks Ints
Walkable []bool
nextEntityID int
}
func NewState(l Level) State {
size := l.Size()
s := State{
Entities: Entities{},
Level: l,
IdxToPos: make([]geom.Point, size),
Bricks: NewInts(size),
SunkenBricks: NewInts(size),
Walkable: make([]bool, size),
}
for idx, t := range l.Tiles {
switch t {
case TileTypeBasic:
s.Walkable[idx] = true
}
s.IdxToPos[idx] = s.Level.IdxToPos(idx)
}
for idx, e := range l.Entities {
pos := s.IdxToPos[idx]
switch e {
case EntityTypeBrick:
s.addBrick(pos)
case EntityTypePlayer:
s.initPlayer(pos)
case EntityTypeTarget:
s.initTarget(pos)
}
}
return s
}
// Clone creates and returns a clone of the state.
func (s State) Clone() State {
return State{
Player: s.Player,
Target: s.Target,
Entities: s.Entities.Clone(),
Level: s.Level,
IdxToPos: s.IdxToPos,
Bricks: s.Bricks.Clone(),
SunkenBricks: s.SunkenBricks.Clone(),
Walkable: append(s.Walkable[:0:0], s.Walkable...),
nextEntityID: s.nextEntityID,
}
}
func (s State) All(pred func(State, geom.Point) bool, p ...geom.Point) bool {
for _, p := range p {
if !pred(s, p) {
return false
}
}
return true
}
func (s State) Any(pred func(State, geom.Point) bool, p ...geom.Point) bool {
for _, p := range p {
if pred(s, p) {
return true
}
}
return false
}
func (s *State) Equal(other *State) bool {
for i := 0; i < len(s.Entities); i++ {
if other.Entities[i].Pos != s.Entities[i].Pos {
return false
}
}
return true
}
func (s State) IsOpenForBrick(p geom.Point) bool {
idx := s.Level.PosToIdx(p)
if idx == -1 {
return false
}
return s.isOpenForBrick(idx)
}
// IsWalkable indicates that a player could walk over this tile regardless of any Bricks that might be there.
func (s State) IsWalkable(p geom.Point) bool {
idx := s.Level.PosToIdx(p)
if idx == -1 {
return false
}
return s.Walkable[idx]
}
// IsWalkableAndFree indicates that a player can walk over this tile (no brick is at the tile).
func (s State) IsWalkableAndFree(p geom.Point) bool {
idx := s.Level.PosToIdx(p)
if idx == -1 {
return false
}
return s.Walkable[idx] && s.Bricks[idx] == -1
}
// MovePlayer tries to move the player in the specified direction. Returns the new state and true if the move is valid. Returns the current state and false is the move was invalid.
func (s State) MovePlayer(dir Direction) (State, bool) {
to := s.Level.MoveIdx(s.Player.Pos, dir)
if to == -1 {
return s, false
}
if !s.Walkable[to] {
return s, false
}
brickID := s.Bricks[to]
if brickID == -1 {
return s.Mutate(func(s *State) {
s.movePlayer(to)
}), true
}
brickTo := s.Level.MoveIdx(to, dir)
if brickTo == -1 {
return s, false
}
if !s.isOpenForBrick(brickTo) {
return s, false
}
return s.Mutate(func(s *State) {
s.movePlayer(to)
if s.Level.Tiles[brickTo] == TileTypeMagma && s.SunkenBricks[brickTo] == -1 {
s.SunkenBricks[brickTo] = brickID
s.Walkable[brickTo] = true
s.Bricks[to] = -1
} else {
s.Bricks[brickTo] = brickID
s.Bricks[to] = -1
}
s.updateEntity(brickID, Entity{brickID, brickTo, EntityTypeBrick})
}), true
}
func (s State) SetPlayer(to geom.Point) (State, bool) {
toIdx := s.Level.PosToIdx(to)
if toIdx == -1 {
return s, false
}
if !s.Walkable[toIdx] {
return s, false
}
if s.Bricks[toIdx] != -1 {
return s, false
}
return s.Mutate(func(s *State) {
s.movePlayer(toIdx)
}), true
}
// Mutate clones the state, applies the mutation on the clone and returns the clone.
func (s State) Mutate(fn func(s *State)) State {
clone := s.Clone()
fn(&clone)
return clone
}
func (s *State) addBrick(pos geom.Point) {
s.addEntity(pos, EntityTypeBrick, func(e Entity) {
idx := s.Level.PosToIdx(pos)
if idx != -1 {
s.Bricks[idx] = e.ID
}
})
}
func (s *State) addEntity(pos geom.Point, typ EntityType, add func(Entity)) {
id := s.nextEntityID
e := Entity{id, s.Level.PosToIdx(pos), typ}
add(e)
s.Entities = append(s.Entities, e)
s.nextEntityID++
}
func (s *State) initPlayer(pos geom.Point) {
s.addEntity(pos, EntityTypePlayer, func(e Entity) {
s.Player = e
})
}
func (s *State) initTarget(pos geom.Point) {
s.addEntity(pos, EntityTypeTarget, func(e Entity) {
s.Target = e
})
}
func (s State) isOpenForBrick(idx int) bool {
if s.Walkable[idx] {
return s.Bricks[idx] == -1
}
return s.Level.Tiles[idx] == TileTypeMagma
}
func (s *State) updateEntity(id int, e Entity) {
idx := s.Entities.IdxById(id)
if idx == -1 {
return
}
s.Entities[idx] = e
}
func (s *State) movePlayer(to int) {
s.Player.Pos = to
s.updateEntity(s.Player.ID, Entity{s.Player.ID, to, EntityTypePlayer})
}
func IsMagma(s State, p geom.Point) bool {
idx := s.Level.PosToIdx(p)
if idx == -1 {
return false
}
return s.Level.Tiles[idx] == TileTypeMagma
}

71
soko/statecost.go Normal file
View File

@ -0,0 +1,71 @@
package soko
type stateCost struct {
state *State
cost int
distances Ints
}
type stateCostQueue struct {
first *stateCostQueueItem
}
type stateCostQueueItem struct {
Value *stateCost
Next *stateCostQueueItem
}
func (q *stateCostQueue) Empty() bool {
return q.first == nil
}
func (q *stateCostQueue) Get() *stateCost {
if q.Empty() {
panic("nothing in queue")
}
first := q.first
q.first = first.Next
return first.Value
}
func (q *stateCostQueue) Put(value *stateCost) {
priority := value.cost
item := &stateCostQueueItem{value, nil}
if q.Empty() {
q.first = item
return
}
if priority < q.first.Value.cost {
item.Next = q.first
q.first = item
return
}
curr := q.first
for curr.Next != nil {
if priority < curr.Next.Value.cost {
item.Next = curr.Next
curr.Next = item
return
}
curr = curr.Next
}
curr.Next = item
}
func (q *stateCostQueue) Update(value *stateCost) {
var prev *stateCostQueueItem
curr := q.first
for curr.Value != value {
prev = curr
curr = curr.Next
if curr == nil {
panic("not in queue")
}
}
if prev == nil {
q.first = curr.Next
} else {
prev.Next = curr.Next
}
q.Put(value)
}

21
soko/tiletype.go Normal file
View File

@ -0,0 +1,21 @@
package soko
type TileType byte
const (
TileTypeInvalid TileType = TileType(0)
TileTypeNothing = '.'
TileTypeBasic = '#'
TileTypeMagma = '~'
)
func (t TileType) IsValid() bool {
switch t {
case TileTypeNothing:
case TileTypeBasic:
case TileTypeMagma:
default:
return false
}
return true
}