203 Commits

Author SHA1 Message Date
91dd84a437 [common] add PackId 2019-06-20 16:18:54 +03:00
1b36016a1a [common] fix load old level format 2019-06-20 11:16:17 +03:00
db0adbac30 [client] control settings rework 2019-06-19 22:35:11 +03:00
948648b313 [work] update 2019-06-19 17:23:09 +03:00
73822dc95a [client] add JoystickDevice 2019-06-18 20:47:04 +03:00
282bc68734 [client] DeviceType in SettingsEditor 2019-06-18 17:50:47 +03:00
2ff374abb6 [client] add ControlBus 2019-06-18 12:14:04 +03:00
f999c66fea [client] use touch events in GamepadView 2019-06-17 20:43:14 +03:00
2b3f368e0f [client] add screen gamepad 2019-06-17 17:33:35 +03:00
c0ab953115 [all] fixes for LevelPack 2019-06-17 11:45:33 +03:00
e39de4467d [common] added LevelPack 2019-06-14 16:06:22 +03:00
4c3f1ca0fc [common] clock bonus freeze team instead tanks 2019-06-14 12:47:20 +03:00
7fa5a4e048 [client] fix GamePlayer 2019-06-13 21:42:13 +03:00
dc1279f636 [editor] MapFrame rework 2019-06-13 16:23:22 +03:00
5798fa9db7 [editor] rename packages 2019-06-13 11:02:54 +03:00
c534cf20fd [common] add death mode map 2019-06-12 21:45:28 +03:00
38e14c9269 [editor] custom map size fix 2019-06-11 19:59:53 +03:00
a66b72ba22 [common] add map size 2019-06-11 17:29:18 +03:00
2c42d993ca [common] fix bullet and tank collision with bricks under bonus 2019-06-11 15:56:00 +03:00
a49d673f25 [client] fix tank destroy zero score label 2019-06-11 15:31:13 +03:00
ee5de9f3db [client] update CreateGamePopup 2019-06-10 21:30:30 +03:00
94b3a94cbb [server] join game after relogin 2019-06-10 16:12:08 +03:00
caab6ba3a3 up version 2019-06-07 18:41:10 +03:00
7f70c49b87 Merge branch 'develop' 2019-06-07 17:31:32 +03:00
8f50da64c2 [client] add tanks players names to render 2019-06-07 17:31:00 +03:00
982ca09a23 up version 2019-06-06 20:04:38 +03:00
dbf30decae [client] fix control 2019-06-06 17:38:37 +03:00
abd1b834d7 [client] game room frames update 2019-06-05 11:37:25 +03:00
6ad9076987 [client] add CreateGamePopup 2019-06-04 14:41:21 +03:00
78bbf5264e [proto] add rooms and slots 2019-06-04 12:13:27 +03:00
4c8ae66624 [connection] send queue in NekoConnection 2019-06-03 11:23:20 +03:00
5a3d5b974e [common] ticker update 2019-06-02 22:09:13 +03:00
fb9a28c126 [network] update 2019-05-31 15:47:16 +03:00
7115ea8ac2 [common] fix null color 2019-05-30 16:03:46 +03:00
01417f5bbd up version 2019-05-30 15:25:33 +03:00
abf944418e [common] add PlayerControl presets 2019-05-30 15:24:26 +03:00
c7946ef1da [common] PacketQueue fix 2019-05-29 16:09:46 +03:00
241499bc2d [common] add Ticker 2019-05-29 11:22:25 +03:00
74297dd9c7 [common] refactor ControlFactory 2019-05-28 21:50:05 +03:00
31cb20bf85 [common] add BaseControlFactory 2019-05-28 19:42:46 +03:00
1d95de02e1 [common] update for network 2019-05-28 17:03:04 +03:00
ba13111a8e [common] GameRunner extend from Game 2019-05-27 17:59:59 +03:00
94b19a1c26 up version 2019-05-24 16:04:36 +03:00
50a0cee044 [network] update 2019-05-24 15:43:00 +03:00
26ad5f47cd [client] add GameRoomFrame 2019-05-23 17:57:54 +03:00
864d5f3335 [common] binary message in ws connection 2019-05-23 11:43:35 +03:00
4b426183e8 [client] add GameListFrame 2019-05-22 17:25:51 +03:00
a5722dfa9d [common] add DesktopConnection 2019-05-21 17:44:48 +03:00
7984d8282c [client] update SoundManager 2019-05-20 22:02:13 +03:00
17823ede11 [core] disable autospawn bonuses 2019-05-20 17:20:44 +03:00
5db3ae1af0 [client] set FPS to 60 2019-05-20 17:11:50 +03:00
bbe2aeb7fb [editor] refactor MapEditView 2019-05-20 13:00:04 +03:00
09b188cf24 [build] disable editor 2019-05-17 16:24:29 +03:00
11f8fc6190 [render] add protect view 2019-05-17 16:10:10 +03:00
96e608c36f [render] bricks and cells from GameEvent 2019-05-17 12:55:32 +03:00
3c116db135 [render] use only GameEvent for redraw 2019-05-16 23:27:27 +03:00
efe826110c [render] spawn eagle from GameEvent 2019-05-16 21:25:53 +03:00
c1ff14111d [client] update render 2019-05-16 17:13:12 +03:00
cd7dd1984b [common] add GameEvent.MOVE 2019-05-15 15:15:07 +03:00
686c659c84 [editor] fix 2019-05-14 21:19:20 +03:00
797dfca2be [client] fix RecordStorage for linux 2019-05-14 17:16:57 +03:00
aa10825b12 [common] update GameEvent 2019-05-14 12:24:29 +03:00
608ed3acc4 [client] update RecordFrame 2019-05-13 22:35:16 +03:00
03b461f082 [common] implement GameEvent.DESTORY.CELL 2019-05-13 21:56:28 +03:00
cbb28f4158 [client] add position to IGamePanel 2019-05-13 19:32:52 +03:00
13240677b0 [client] refactored GameFrame 2019-05-13 17:34:53 +03:00
b0ae85334b [common] enity id 2019-05-08 16:40:58 +03:00
183c6c16f1 [client] add RecordFrame 2019-05-07 17:21:01 +03:00
a7f286dc42 [common] build bonus with EntityBuilder 2019-05-06 20:40:43 +03:00
20b60009e3 [common] build tank and bullet with EntityBulder 2019-05-06 17:53:34 +03:00
d6b572aead [common] add EntityBuilder 2019-05-06 16:21:45 +03:00
d11d0ac53f [common] add engine interface 2019-05-05 21:18:36 +03:00
ab02460b11 [common] add GameRecorder and GamePlayer 2019-04-30 17:26:54 +03:00
fc18e2e0b7 [common] add GameRunner 2019-04-30 12:17:28 +03:00
363a48bb1b [common] update Game with GameEvent 2019-04-26 17:28:36 +03:00
e9de677ceb [common] update GameEvent 2019-04-25 17:21:03 +03:00
5ff7b19475 [common] add GameEvent 2019-04-22 17:40:36 +03:00
7ddba8f69b use dispatcher macro 2019-04-22 10:36:39 +03:00
b86e0ddd20 [comon] remove change signal from engine 2019-04-19 16:20:01 +03:00
a3f3de3af5 [engine] fix position fix 2019-04-17 22:38:37 +03:00
4a4ca463c3 [client] update LevelPopup 2019-04-08 21:45:52 +03:00
13d01293f6 [common] diffilicity presets support 2019-04-08 14:53:44 +03:00
d0104e4361 up version 2019-04-05 16:51:03 +03:00
c3db9f2414 [client] update SoundManager 2019-04-05 16:29:17 +03:00
f34d35e03a up version 2019-04-04 20:41:54 +03:00
9868d27bc3 up version 2019-04-04 20:11:33 +03:00
c0b4b2a4c1 [common] add GameProgress 2019-04-04 17:12:00 +03:00
9dc0a4ce06 [client] add universal LevelFrame 2019-04-03 17:23:15 +03:00
c58735ea43 up version 2019-04-02 23:32:41 +03:00
4e2b65c225 [common] add gun bonus 2019-04-02 23:22:21 +03:00
663935bd75 [client] update clock, helmet bonuses images 2019-04-02 22:06:58 +03:00
d1ed17d1d7 [client] settings editor fix 2019-04-02 17:42:08 +03:00
135ad0d992 [client] update storages 2019-03-29 11:50:16 +03:00
8fb1d6132d [common] Player state life fix 2019-03-28 20:50:27 +03:00
f60feea6e8 [common] PlayerState update 2019-03-28 17:38:51 +03:00
d7b7744eb8 [client] add preloader 2019-03-28 15:59:46 +03:00
2eb606aa21 [engine] fix tank position 2019-03-28 12:18:40 +03:00
a86c4fc447 [common] add dota levels 2019-03-28 10:28:33 +03:00
1ea216fd20 up version 2019-03-27 23:56:36 +03:00
121c470b00 [common] add dota levels 2019-03-27 17:39:41 +03:00
404dd77806 [client] use LabelView for score in render 2019-03-26 22:20:07 +03:00
d2f23e7777 up version 2019-03-26 21:34:59 +03:00
fd0e2382d0 [client] add death game panel 2019-03-26 17:37:33 +03:00
e609dafedc [common] add GameDispatcher 2019-03-26 11:23:44 +03:00
a948dfbaad [editor] tanks colors 2019-03-25 21:17:39 +03:00
5b804c6902 [client] add colorize param to PlayerView 2019-03-25 17:56:41 +03:00
556cd2f1a9 [common] add deathmatch mode 2019-03-25 17:42:20 +03:00
7d570336a5 [client] update haxework 2019-03-25 16:45:54 +03:00
a9b591a7ca [editor] add ColorView 2019-03-25 16:01:37 +03:00
216e1aa476 [client] add font 2019-03-22 15:47:47 +03:00
4d8de90419 [client] rename frame => view 2019-03-21 20:26:28 +03:00
0b17fbf804 [common] add hard bot 2019-03-21 17:45:03 +03:00
c6639e11b1 [core] add color to PlayerState 2019-03-21 12:22:01 +03:00
e6f9aa8ba1 [client] apply LayoutSkin 2019-03-20 17:36:15 +03:00
2c191d932c [client] apply GeometrySkin 2019-03-19 22:47:24 +03:00
d52b94d095 [client] ResultFrame update 2019-03-17 14:12:13 +03:00
c67385576e [client] add ResultFrame 2019-03-15 16:15:47 +03:00
f09e70c5f8 [client] add linux taskbar icon 2019-03-14 22:37:28 +03:00
0f5cf7fdc5 [client] fix app icon 2019-03-14 21:26:57 +03:00
426b2718bb [common] game update 2019-03-14 17:49:47 +03:00
8ea862a118 [common] add GameState 2019-03-14 12:58:00 +03:00
1f87a71833 [build] disable server build 2019-03-13 21:17:31 +03:00
56c2cd9437 [client] small fixes 2019-03-13 21:10:46 +03:00
85e5f9a553 [common] add GameStart 2019-03-13 17:11:20 +03:00
d9915120d4 [client] update haxework. ep8 2019-03-13 13:06:48 +03:00
4863f37eef up version 2019-03-12 21:18:56 +03:00
c9ec4395ee [client] update haxework. ep7 2019-03-12 17:21:50 +03:00
b62956cc95 [client] set haxework version 0.9.0 2019-03-11 22:48:03 +03:00
b2ba4362fe [client] update haxework. ep6 2019-03-11 17:51:13 +03:00
7cca35195d [client] update haxework. ep5 2019-03-06 17:48:51 +03:00
d4a9c720d6 [common] abstract Direction 2019-03-05 16:39:03 +03:00
d2383fc4f0 [client] add button.level skin 2019-03-04 21:12:30 +03:00
74322ca6a4 [client] level frames update 2019-03-04 18:00:44 +03:00
a6323edb36 [client] update haxework. ep4 2019-03-01 16:30:17 +03:00
2d4c56d04c update haxework. ep3 2019-03-01 12:48:35 +03:00
e3d3359019 [client] update haxework. ep2 2019-02-25 17:38:14 +03:00
2aa1c82aea [client] update haxework. ep1 2019-02-22 21:54:23 +03:00
45af6c2a50 up dependencies versions 2018-10-12 15:49:06 +03:00
d6cf708035 [server] build fix 2018-08-09 19:39:49 +03:00
085431fe73 [client] update ui 2018-08-09 17:55:40 +03:00
95148a9b0b [common] remove GameSave; [client] update @:template macro use 2018-08-09 12:17:41 +03:00
a24d610b05 [client] update StartFrame 2018-07-27 17:35:12 +03:00
f8bba85eb4 [common] fix Color zero 2018-07-26 21:06:59 +03:00
80f2ac25ad [client] add StartGameFrame 2018-07-26 18:01:15 +03:00
17e4f1f172 Merge branch 'network' 2018-07-26 16:48:42 +03:00
af5aa6b8e6 [client] added game panels 2018-07-26 16:48:07 +03:00
1fd1c669a0 [ansible] deploy master 2018-07-22 19:47:32 +03:00
122c54a0de [editor] fix build 2018-07-22 19:44:37 +03:00
ac1df9a9a4 [client] update layout 2018-07-20 17:09:48 +03:00
d0c796aab2 [client] add SettingsFrame 2018-07-19 17:47:25 +03:00
17289fde92 [gulp] remove editor build from default task 2018-07-13 19:46:47 +03:00
7d27f0cd35 [npm] add package-lock.json 2018-07-13 19:40:37 +03:00
a64463ddc6 [npm] update gulp-haxetool version 2018-07-13 19:37:56 +03:00
007621c48c [proto] added GameRequest and GameResponse 2018-05-17 17:45:02 +03:00
33b0693a4e [proto] update message names 2018-05-15 15:06:34 +03:00
13c1299bf0 [package.json] downgrade openfl version (html5 build fail) 2018-05-14 17:19:36 +03:00
fbdf018422 [gulp] added android build 2018-05-10 23:11:50 +03:00
8800fe48ee [package] up dependencies versions 2018-05-07 17:06:09 +03:00
2be44de710 fixes 2018-05-04 16:45:37 +03:00
9269bde518 [gulp] update to gulp-haxetool 0.0.9 2018-04-27 17:50:28 +03:00
4c8181b3ea [gulp] use gulp-haxetool from npm 2018-04-26 10:24:58 +03:00
61852ab47e [gulp] added editor to default task 2018-04-25 16:13:33 +03:00
914a4dcf3b Merge branch 'gulp' of bitbucket.org:infernalgames/tankz into gulp 2018-04-25 15:38:13 +03:00
8f3fb4474c [gulp] update 2018-04-25 15:37:59 +03:00
08ef40b736 [ansible] fix gulp path 2018-04-25 00:18:16 +03:00
0048d6fc92 [ansible] update roles 2018-04-24 16:14:24 +03:00
caae1216d0 [build] update to fulp-haxetool 0.0.6 2018-04-06 16:29:45 +03:00
2255a806b9 [gulp] move project to gulp-haxetool 2018-04-05 18:03:42 +03:00
0eb150eb8b [gulp] update to gulp-haxetool 0.0.4 2018-04-05 11:36:41 +03:00
01f811ebd2 [gulp] udpate project 2018-04-04 22:49:03 +03:00
c70eed8a06 [gulp] added project 2018-04-04 17:58:14 +03:00
b12b26b87e [build] udpate to gulp-haxetool 0.0.2 2018-04-03 17:03:33 +03:00
836eebaf11 [gulp] move tasks to gulp-haxetool package 2018-04-03 15:12:53 +03:00
92a2628e90 [ansible] move deploy role in other repo 2018-03-30 14:47:03 +03:00
d2360fde25 [ansible] update tasks 2018-03-29 17:13:31 +03:00
c603753226 [server] host from args 2018-03-29 15:04:30 +03:00
c8448b7848 [client] hostname from environ 2018-03-28 17:30:42 +03:00
6d2a1a002b [ansible] added deploy role 2018-03-28 16:38:16 +03:00
f6ebec32ca [ansible] added service role 2018-03-26 22:06:22 +03:00
7a57f22967 [ansible] added 2018-03-26 17:03:21 +03:00
dd2c1eb9d2 [build] update sdk.js 2018-03-24 18:14:57 +03:00
e657fb16bd [server] update 2018-03-19 17:39:34 +03:00
f7bf5e2b0e [build] haxe activate 2018-03-16 16:43:34 +03:00
51f07bd330 [build] added environ setup in haxe tasks 2018-03-15 17:58:38 +03:00
2183c0710c [render] show scores 2018-03-14 22:18:05 +03:00
e9212a889d [build] up haxe version 2018-03-07 17:17:02 +03:00
0d4ac4e3e5 [client] fixes 2018-03-06 22:57:07 +03:00
df99ff817a [client] update haxework 2018-03-06 17:18:18 +03:00
2705afc327 [client] use meta @:provide 2018-03-05 17:38:55 +03:00
5330be142c [engine] use signals 2018-03-05 15:06:31 +03:00
73c46d821e [server] GameManager restore 2018-03-02 16:08:53 +03:00
0565eec871 [server] update 2018-03-01 17:36:34 +03:00
d895fb70f7 [proto] update 2018-03-01 15:50:03 +03:00
45fab2c0b5 [common] udpate proto 2018-03-01 12:05:06 +03:00
634f5ad2d0 [server] update proto 2018-02-28 22:25:29 +03:00
34e5ac2b9e [client] update proto 2018-02-28 22:06:00 +03:00
336896b37e [client] update network view 2018-02-27 22:12:29 +03:00
c9698f1f5c [client] added NetworkManager 2018-02-22 17:18:55 +03:00
dd447656f8 [network] added NetworkFrame 2018-02-21 17:46:52 +03:00
db2339ab3a fix 2018-02-20 22:25:27 +03:00
8d3308d74a [client] added ogg sounds 2018-02-20 22:20:55 +03:00
22e7965442 [client] added SoundManager 2018-02-20 17:47:04 +03:00
2e856c1256 [common] added PlayerState 2018-02-20 17:23:53 +03:00
435 changed files with 16432 additions and 7359 deletions

9
.editorconfig Normal file
View File

@@ -0,0 +1,9 @@
# Editor configuration, see http://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = true

2
.gitignore vendored
View File

@@ -9,6 +9,6 @@ out/
.idea/
.ideaDataSources/
config.json
package-lock.json
/node_modules
/log
/ansible/*.retry

29
CHANGELOG.md Normal file
View File

@@ -0,0 +1,29 @@
0.15.0
------
* Added display tank player name in `Render`
* Fixed join game after relogin
* Updated `CreateGamePopup` for any screen sizes
* Fixed tank destroy zero score label
* Added custom size map support
* Fixed clock bonus for spawned tanks
0.14.0
------
* Added `CreateGamePopup`
* Fixed null tank color
* Updated `Ticker`
0.13.0
------
* Added `Ticker`
* Fixed `PacketQueue` stream reading
* Added `PlayerControl` and `ControlPreset`
* Added `BaseControlFactory`
0.12.0
------
* Added `GameRoomFrame`
* Improved websocket connection with using binary protocol instead of text
* Added `GameListFrame`
* Added `DesktopConnection` for linux client build
* Updated `SoundManager`

85
WORK.md
View File

@@ -1,73 +1,12 @@
* build
* gulp 100%
* linux 100%
* deb-package 100%
* windows 0%
* exe-package 0% (inno setup)
* deploy
* capistrano 100%
* ui
* auth frame 0%
* select game frame 100% (classic 1/2 player, dota singe/coop/vs)
* select level frame 10%
* game frame 50%
* engine
* config 100%
* map 100%
* tanks 100%
* bullets 100%
* boxes 100%
* map changes 100%
* bonuses 100%
* eagle 100%
* game
* classic
* state 50%
* bot 50%
* human 100%
* dota
* state 50%
* bot 10%
* human 100%
* bonus
* star 50%
* grenade 0%
* helm 0%
* clock 0%
* shovel 0%
* state
* score 0%
* human tank 0%
* save/load 0%
* export/import 0%
* render
* map 100%
* tanks 100%
* bullet 100%
* calc redraw 50%
* animations
* tank spawn 0%
* tank move 100%
* map water 100%
* bullet boom 90%
* tank boom 90%
* bonuses 100%
* html5 50%
* proto
...
* editor
* level
* open 100%
* edit 50%
* save 100%
* tank
* color 10%
* **shovel** bonus with armor bricks
* bonuses in dota/death mod
* tanks and bullets speed balancing
* result frame update (next game select, only human player info)
* network game series
* map packs (create in editor, import in game, save imported in local storage)
* update bots
* improve bonuses system
* gamepad support
* screen gamepad on mobiles
* resize render on mobiles
* [bug] game progress broken

11
ansible/ansible.cfg Normal file
View File

@@ -0,0 +1,11 @@
[defaults]
hash_behaviour = merge
host_key_checking = False
#callback_whitelist = profile_tasks
display_skipped_hosts = False
stdout_callback = yaml
bin_ansible_callbacks = True
[ssh_connection]
pipelining = True
ssh_args = -o ForwardAgent=yes

14
ansible/deploy.yml Normal file
View File

@@ -0,0 +1,14 @@
---
- hosts: all
vars:
ansible_user: "{{ deploy_user }}"
roles:
- ansible-deploy
- build
post_tasks:
- include_role:
name: ansible-deploy
tasks_from: complete.yml
- include_role:
name: service
tasks_from: restart.yml

View File

@@ -0,0 +1,2 @@
all:
hosts: localhost

View File

@@ -0,0 +1,15 @@
---
project_name: tankz
project_user: holop
deploy_user: "{{ project_user }}"
deploy_project: "{{ project_name }}"
deploy_repo_url: "git@bitbucket.org:infernalgames/{{ project_name }}.git"
deploy_repo_version: master
deploy_npm: yes
service_name: "{{ project_name }}"
service_work_dir: "{{ deploy_current_dir }}/target/server/neko"
service_command: "/usr/bin/neko {{ service_work_dir }}/{{ project_name }}.n {{ service_host }}"
service_user: www-data
service_control_user: "{{ project_user }}"

View File

@@ -0,0 +1,4 @@
all:
hosts: shmyga.ru
vars:
service_host: 172.31.1.100

7
ansible/requirements.yml Normal file
View File

@@ -0,0 +1,7 @@
---
- name: ansible-deploy
src: git@bitbucket.org:shmyga/ansible-deploy.git
version: master
scm: git
- name: geerlingguy.nodejs

View File

@@ -0,0 +1,11 @@
---
- name: "Copy config"
copy:
src: "{{ deploy_release_dir }}/config.{{ inventory_hostname }}.json"
dest: "{{ deploy_release_dir }}/config.json"
remote_src: true
- name: "Gulp build"
command: "/usr/local/lib/npm/bin/gulp default --host shmyga.ru"
args:
chdir: "{{ deploy_release_dir }}"

View File

@@ -0,0 +1,6 @@
service_name: null
service_description: "{{ service_name }} service"
service_work_dir: null
service_command: null
service_user: null
service_control_user: null

View File

@@ -0,0 +1,21 @@
---
- name: "Install {{ service_name }} systemd unit file"
template:
src: "template/service.j2"
dest: "/etc/systemd/system/{{ service_name }}.service"
- name: "Start {{ service_name }} service"
systemd:
enabled: yes
state: started
name: "{{ service_name }}"
daemon_reload: yes
- name: "Add sudoers record for {{ service_name }} service"
lineinfile:
path: /etc/sudoers.d/{{ service_name }}
state: present
create: yes
regexp: "^{{ service_control_user }} ALL="
line: "{{ service_control_user }} ALL= NOPASSWD: /bin/systemctl * {{ service_name }}"
validate: "/usr/sbin/visudo -cf %s"

View File

@@ -0,0 +1,11 @@
---
# - name: "Restart {{ service_name }} service"
# systemd:
# enabled: yes
# state: restarted
# name: "{{ service_name }}"
- name: "Restart {{ service_name }} service"
command: "sudo /bin/systemctl restart {{ service_name }}"
args:
warn: no

View File

@@ -0,0 +1,15 @@
[Unit]
Description={{ service_description }}
[Service]
Type=simple
PIDFile=/var/run/{{ service_name }}.pid
WorkingDirectory={{ service_work_dir }}
User={{ service_user }}
Group={{ service_user }}
ExecStart={{ service_command }}
TimeoutSec=300
Restart=always
[Install]
WantedBy=multi-user.target

View File

@@ -0,0 +1,3 @@
- name: "Install neko package"
apt:
name: neko

View File

@@ -0,0 +1,2 @@
- import_tasks: apt.yml
when: ansible_distribution|lower == 'ubuntu'

View File

@@ -0,0 +1 @@
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCot1zSeqj7Tj5/7aNMzXAuXQPPxudYFV9z6M03dPijh2bXyHDcXk53xUO8XY5R4GyLhvAn98axbPM++urKY8BXuQqAG36soI7iZJ/KcPY1EKDwVBeZneFC/wMc8HMT0hj9+uHcGAMtmklIgPPkawzLxbEh6oAY4H8Vvz08qyco6suYB5NjkpFwVMf9Xa2Fj8rTodKpPRDBh/Xk+5bh11RKL6b9WcwuwpKU8zl2qZiqNfjr0H+sKEk7ohcYvzSCltLdKJcoKbiCcnrnBJT5/JpGWeAbA2MMmvmt/dJrHykd1CbmXW2DuG4tIlwMb5xU739PoKCePctK1retb8TrWOLT shmyga@shmyga-desktop

View File

@@ -0,0 +1,40 @@
# barin
- name: Make barin group
group:
name: barin
state: present
- name: Make barin user
user:
name: barin
group: barin
password: '$6$mbw5KZWwtrRUy$eFcMNTW.QzG1Em45r5hZf/qri4hKAHImozWuW4/pYnDK.tOrVKrXTKYfRDtYEFRgCgVVg0zuPvyq/xn0KiKlz0'
groups: www-data,sudo,adm
- name: Set up authorized_keys for the barin user
authorized_key:
user: barin
key: '{{ item }}'
with_file:
- keys/shmyga.pub
# holop
- name: Make holop group
group:
name: holop
state: present
- name: Make holop user
user:
name: holop
group: holop
password: '$6$B/7g0xlcXFCIHk$hzSjb8KLll7YrTsp3z640sxNixNAkLpm6UUdZgWPh0Ffy7Ue18AiXTzkDdGTaTH6Woz4kvgVDSggnKGTU6u03.'
groups: www-data
- name: Set up authorized_keys for the holop user
authorized_key:
user: holop
key: '{{ item }}'
with_file:
- keys/shmyga.pub

View File

@@ -0,0 +1 @@
ansible_become: yes

8
ansible/service.yml Normal file
View File

@@ -0,0 +1,8 @@
---
- hosts: all
vars:
ansible_user: "{{ deploy_user }}"
tasks:
- include_role:
name: service
tasks_from: restart.yml

16
ansible/setup.yml Normal file
View File

@@ -0,0 +1,16 @@
---
- hosts:
- all
pre_tasks:
- include_role:
name: ansible-deploy
tasks_from: facts.yml
roles:
- geerlingguy.nodejs
- setup
- service
vars:
nodejs_version: 9.x
nodejs_npm_global_packages: [gulp-cli]
vars_files:
- vars/barin.yml

4
ansible/user.yml Normal file
View File

@@ -0,0 +1,4 @@
- hosts: all
gather_facts: no
roles:
- user

4
ansible/vars/barin.yml Normal file
View File

@@ -0,0 +1,4 @@
---
ansible_user: barin
ansible_become_pass: 1234!QAZ
ansible_become: yes

View File

@@ -1,140 +0,0 @@
const gulp = require('gulp');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const babel = require('gulp-babel');
const template = require('gulp-template');
const yargs = require('yargs');
const Haxe = require('../tasks/haxe');
const FlashPlayer = require('../tasks/flashplayer');
const version = require('./version');
const prepare = require('./prepare');
const debug = require('../tasks/debug');
const webserver = require('gulp-webserver');
const run = require('gulp-run');
const tail = require('../tasks/tail');
const deb = require('gulp-debian');
const generate = () => function generate() {
return new Haxe().haxelib([
'run', 'protohx', 'generate', 'protohx.json'
]);
};
const build = (platform, values) => function build() {
const argv = yargs.argv;
return gulp.src('.')
.pipe(new Haxe().openfl({
command: 'build',
platform: platform,
version: version,
debug: argv.dev,
values: values
}))
.pipe(gulp.dest(`target/${platform}`));
};
const flashIndex = function() {
return gulp.src('src/client/html/index.html')
.pipe(template({
scripts: ['app.min.js'],
swf: 'tankz.swf'
}))
.pipe(gulp.dest('target/flash'))
};
const flashJs = function() {
const src = [
'src/client/html/js/*.js'
];
return gulp.src(src)
.pipe(babel({presets: ['es2015']}))
.pipe(uglify())
.pipe(concat('app.min.js'))
.pipe(gulp.dest('target/flash'))
};
const webapp = function () {
return gulp.src('src/webapp/*').pipe(gulp.dest('target'));
};
const buildDeb = gulp.series(
() => gulp.src('src/client/debian/**/*').pipe(gulp.dest('target/debian')),
() => gulp.src('target/linux/**/*').pipe(gulp.dest('target/debian/usr/share/tankz')),
() => gulp.src('target/debian/*')
.pipe(deb({
package: 'tankz',
version: version,
section: 'base',
priority: 'optional',
architecture: 'all',
maintainer: 'shmyga <shmyga.z@gmail.com>',
description: 'Tank\'z',
changelog: [],
postinst: [
'if [ "$1" = "configure" ] && [ -x "`which update-menus 2>/dev/null`" ] ; then\n' +
' update-menus\n' +
'fi'
],
_target: '/',
_out: 'target',
_clean: false,
_verbose: true
}))
);
exports['client:flash:html'] = gulp.parallel(flashIndex, flashJs);
exports['client:flash'] = gulp.series(prepare(Haxe.ID), generate(), build('flash'), exports['client:flash:html']);
exports['client:html5'] = gulp.series(prepare(Haxe.ID), generate(), build('html5'));
exports['client:html5-dom'] = gulp.series(prepare(Haxe.ID), generate(), build('html5', {dom:true}));
exports['client:linux'] = gulp.series(prepare(Haxe.ID), generate(), build('linux'));
exports['client:webapp'] = webapp;
exports['client:deb'] = buildDeb;
exports['client'] = gulp.series(
prepare(Haxe.ID),
generate(),
gulp.parallel(build('flash'), build('html5'), build('linux')),
exports['client:flash:html'],
webapp,
buildDeb,
);
const testFlash = function() {
const argv = yargs.argv;
return build('flash')()
.pipe(new FlashPlayer().run(argv.dev))
.pipe(debug());
};
const testHtml5 = (dom) => function() {
return gulp.series(
build('html5', {dom:dom}),
() => gulp.src('target/html5').pipe(webserver({
host: 'localhost', port: 3000,
open: true,
fallback: 'index.html'
}))
)();
};
const testLinux = gulp.series(
build('linux'),
() => gulp.src('target/linux/tankz')
.pipe(run('./tankz', {cwd: 'target/linux', verbosity: 1}))
.pipe(tail(debug.log))
.pipe(gulp.dest('target/log'))
);
exports['client:flash:test'] = gulp.series(prepare(Haxe.ID, FlashPlayer.ID), testFlash);
exports['client:html5:test'] = gulp.series(prepare(Haxe.ID), testHtml5());
exports['client:html5-dom:test'] = gulp.series(prepare(Haxe.ID), testHtml5(true));
exports['client:linux:test'] = gulp.series(prepare(Haxe.ID), testLinux);
exports['client:test'] = exports['client:flash:test'];

View File

@@ -1,35 +0,0 @@
const gulp = require('gulp');
const yargs = require('yargs');
const Haxe = require('../tasks/haxe');
const FlashPlayer = require('../tasks/flashplayer');
const version = require('./version');
const prepare = require('./prepare');
const debug = require('../tasks/debug');
const build = (platform) => function build() {
const argv = yargs.argv;
return gulp.src('.')
.pipe(new Haxe().openfl({
command: 'build',
platform: platform,
version: version,
values: {
build_editor: true
},
debug: argv.dev,
}))
.pipe(gulp.dest(`target/${platform}`));
};
const testFlash = function() {
const argv = yargs.argv;
return build('flash')()
.pipe(new FlashPlayer().run(argv.dev))
.pipe(debug());
};
exports['editor:flash'] = gulp.series(prepare(Haxe.ID), build('flash'));
exports['editor:flash:test'] = gulp.series(prepare(Haxe.ID, FlashPlayer.ID), testFlash);

View File

@@ -1,32 +0,0 @@
const AdobeAir = require('../tasks/adobeAir');
const Haxe = require('../tasks/haxe');
const FlashPlayer = require('../tasks/flashplayer');
const packageInfo = require('../package.json');
const prepareOne = (value) => {
switch (value) {
case Haxe.ID:
const haxe = new Haxe();
return haxe.prepare().then(() => haxe.install(packageInfo.haxeDependencies));
case AdobeAir.ID:
return new AdobeAir().prepare();
case FlashPlayer.ID:
return new FlashPlayer().prepare();
default:
throw Error(`Unknown target: ${value}`)
}
};
const prepare = (...targets) => function prepare() {
const tasks = targets.map((target) => prepareOne(target));
return Promise.all(tasks);
};
const update = () => {
return new Haxe().upgrade();
};
module.exports = prepare;
module.exports.update = update;

View File

@@ -1,43 +0,0 @@
const gulp = require('gulp');
const yargs = require('yargs');
const Haxe = require('../tasks/haxe');
const FlashPlayer = require('../tasks/flashplayer');
const Neko = require('../tasks/neko');
const version = require('./version');
const prepare = require('./prepare');
const debug = require('../tasks/debug');
const build = () => function build() {
const argv = yargs.argv;
return gulp.src('.')
.pipe(new Haxe().build({
platform: 'neko',
version: version,
lib: [
'protohx',
'orm',
'haxework:git',
],
cp: [
'src/common/haxe',
'src/server/haxe',
'src-gen/haxe',
],
main: 'ru.m.tankz.server.Server',
outputFile: 'tankz.n',
debug: argv.dev,
}))
.pipe(gulp.dest('target'));
};
const test = (build) => function test() {
const argv = yargs.argv;
return build()
.pipe(new Neko().run(argv.dev))
.pipe(debug());
};
exports['server'] = gulp.series(prepare(Haxe.ID), build());
exports['server:test'] = gulp.series(prepare(Haxe.ID, FlashPlayer.ID), test(build()));

View File

@@ -1,2 +0,0 @@
const packageInfo = require('../package.json');
module.exports = packageInfo.version;

View File

11
capfile
View File

@@ -1,11 +0,0 @@
require 'capistrano/setup'
require 'capistrano/deploy'
require 'capistrano/scm/git'
install_plugin Capistrano::SCM::Git
require 'capistrano/scm/git-with-submodules'
install_plugin Capistrano::SCM::Git::WithSubmodules
require 'capistrano/npm'
require 'capistrano/gulp'
require 'airbrussh/capistrano'
Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }

View File

@@ -1,16 +0,0 @@
set :config_role, :app
set :config_path, -> { release_path }
set :config_type, 'json'
namespace :config do
task :setup do
config_role = fetch(:config_role)
config_path = fetch(:config_path)
config_type = fetch(:config_type)
on roles(config_role) do |server|
# stage = fetch(:stage)
execute "cd #{config_path} && cp config.#{server.hostname}.#{config_type} config.#{config_type}"
end
end
end

View File

@@ -1,31 +0,0 @@
require_relative 'npm'
require_relative 'config'
app = 'tankz'
user = 'holop'
# git
set :application, app
set :repo_url, "git@bitbucket.org:infernalgames/#{app}.git"
set :user, user
set :deploy_to, "/home/#{user}/repo/#{app}"
# airbrussh
set :format, :airbrussh
set :format_options, command_output: false
# config
before 'deploy:updated', 'config:setup'
# npm
set :npm_target_path, -> { "/home/#{fetch(:user)}/npm" }
set :npm_flags, '--silent --no-spin'
set :npm_roles, :web
set :npm_env_variables, {}
# gulp
set :gulp_target_path, -> { release_path }
set :gulp_tasks, 'default'
set :gulp_flags, '--no-color'
set :gulp_roles, :web
before 'deploy:updated', 'gulp'

View File

@@ -1,11 +0,0 @@
role :app, %w{localhost}
role :web, %w{localhost}
role :db, %w{localhost}
set :user, ENV['USER']
user = fetch(:user)
server 'localhost', ssh_options: { port: 22, user: user, forward_agent: true }
set :tmp_dir, "/home/#{user}/tmp"
set :branch, 'master'

View File

@@ -1,13 +0,0 @@
# host = '94.130.110.9'
host = 'shmyga.ru'
role :app, host
role :web, host
role :db, host
user = fetch(:user)
server host, ssh_options: { port: 22, user: user, forward_agent: true }
set :tmp_dir, "/home/#{user}/tmp"
set :branch, 'master'

View File

@@ -1,24 +0,0 @@
set :npm_path, -> { release_path }
namespace :npm do
task :prepare do
npm_roles = fetch(:npm_roles)
on roles(npm_roles) do
npm_target_path = fetch(:npm_target_path)
npm_path = fetch(:npm_path)
execute "mkdir -p #{npm_target_path}"
execute "cp #{npm_path}/package.json #{npm_target_path}"
end
end
task :link do
npm_roles = fetch(:npm_roles)
on roles(npm_roles) do
npm_target_path = fetch(:npm_target_path)
npm_path = fetch(:npm_path)
execute "ln -s #{npm_target_path}/node_modules #{npm_path}/"
end
end
end
before 'npm:install', 'npm:prepare'
after 'npm:install', 'npm:link'

View File

@@ -1,6 +0,0 @@
source 'https://rubygems.org'
gem 'capistrano', '~> 3.7.0'
gem 'capistrano-git-with-submodules', '~> 2.0'
gem 'capistrano-npm'
gem 'capistrano-gulp'
gem 'airbrussh', :require => false

2
gen.sh
View File

@@ -1,6 +1,6 @@
#!/bin/bash
haxelib run protohx generate protohx.json
haxelib run orm mysql://shmyga:xkbp8jh9z2@localhost:3306/armageddon \
haxelib run orm mysql://shmyga:password@localhost:3306/armageddon \
-s src-gen/haxe \
-c ru.m.tankz.db \
-a ru.m.tankz.db

View File

@@ -1,36 +1,176 @@
"use strict";
const os = require('os');
const gulp = require('gulp');
const clean = require('gulp-clean');
const Sdk = require('./tasks/sdk');
const FlashPlayer = require('./tasks/flashplayer');
const zip = require('gulp-zip');
const foreach = require('gulp-foreach');
const gulpClean = require('gulp-clean');
const Config = require('./config.json');
const prepare = require('./build/prepare');
//FlashPlayer.VERSION = '25.0.0.171';
const packageInfo = require('./package.json');
const {Sdk, Haxe, Project, FlashPlayer} = require('gulp-haxetool');
const dateformat = require('dateformat');
const argv = require('yargs').argv;
// ToDo: update default in gulp-haxetool
FlashPlayer.VERSION = '32';
//Haxe.VERSION = '4.0.0-rc.2';
if (Config.SdkDir) {
Sdk.dir = Config.SdkDir;
}
exports.clean = () => {
return gulp.src('target/*', {read: false}).pipe(clean());
exports.clean = function clean() {
return gulp.src('target/*', {read: false}).pipe(gulpClean());
};
const merge = (value) => {
if (typeof value === 'string') {
value = require(value);
}
for (let key in value) if (value.hasOwnProperty(key)) {
exports[key] = value[key];
}
exports.generate = function generate() {
return new Haxe().haxelib(['run', 'protohx', 'generate', 'protohx.json']).then(({stdout}) => {
if (stdout.indexOf('FAIL') > -1) {
throw stdout;
}
});
};
exports.update = prepare.update;
merge('./build/prepare');
merge('./build/client');
merge('./build/editor');
merge('./build/server');
exports.levels = function () {
return gulp.src("./src/common/level/*").pipe(foreach(function (stream, file) {
const type = file.path.substr(file.path.lastIndexOf("/") + 1);
gulp.src("./src/common/level/" + type + "/*").pipe(foreach(function (stream, file) {
const name = file.path.substr(file.path.lastIndexOf("/") + 1);
gulp.src("./src/common/level/" + type + "/" + name + "/*")
.pipe(zip(`${type}_${name}.zip`))
.pipe(gulp.dest("./target/levels"));
}));
return stream;
}));
};
/**
* ToDo:
* windows target
* window exe package (innosetup)
*/
const config = new Project.Config({
meta: {
title: 'Tank\'z',
filename: 'tankz',
icon: 'src/client/resources/icon.png',
pack: 'ru.m.tankz',
author: 'shmyga <shmyga.z@gmail.com>',
company: 'MegaLoMania',
version: packageInfo.version,
},
libs: packageInfo.haxeDependencies,
sources: [
'src/common/haxe',
'src-gen/haxe',
],
assets: [
'src/common/resources',
'target/levels'
],
flags: [
//'proto_debug',
],
macros: [
`CompilationOption.set('build','${dateformat(new Date(), 'yyyy-mm-dd HH:MM:ss')}')`,
]
});
exports.default = gulp.series(exports.clean, exports.client);
const host = argv.host || 'localhost';
const port = argv.port || 5000;
/**
* client
*/
const client = new Project(
Project.BuildSystem.OPENFL,
[
Project.Platform.FLASH,
Project.Platform.HTML5,
Project.Platform.LINUX,
Project.Platform.ANDROID,
],
config.branch({
name: 'client',
sources: ['src/client/haxe'],
main: 'ru.m.tankz.Client',
preloader: 'ru.m.tankz.Preloader',
assets: [
'src/client/resources',
],
meta: {
width: 1024,
height: 768,
},
flags: [
//'proto_debug',
//'dom',
//'dev_layout',
//'bitmap_text',
],
macros: [
`CompilationOption.set('host','${host}')`,
`CompilationOption.set('port',${port})`,
]
}),
module.exports.generate
).bind(module, gulp);
/**
* editor
*/
const editor = new Project(
Project.BuildSystem.OPENFL,
[
Project.Platform.FLASH,
Project.Platform.HTML5,
],
config.branch({
name: 'editor',
sources: ['src/client/haxe', 'src/editor/haxe'],
main: 'ru.m.tankz.editor.Editor',
preloader: 'ru.m.tankz.Preloader',
assets: [
'src/client/resources',
'src/editor/resources',
],
meta: {
filename: 'editor',
width: 1024,
height: 850,
},
flags: [
//'dev_layout',
]
})
).bind(module, gulp);
/**
* server
*/
const server = new Project(
Project.BuildSystem.HAXE,
Project.Platform.NEKO,
config.branch({
name: 'server',
sources: ['src/server/haxe'],
main: 'ru.m.tankz.server.Server',
}),
module.exports.generate
).bind(module, gulp);
/**
* default
*/
module.exports.default = gulp.series(
exports.clean,
exports.levels,
module.exports['client:flash:build'],
module.exports['client:flash:html'],
module.exports['client:html5:build'],
module.exports['client:linux:build'],
module.exports['client:linux:deb'],
//module.exports['client:android:build'],
module.exports['editor:flash:build'],
module.exports['editor:flash:html'],
module.exports['editor:html5:build'],
module.exports['server:neko:build'],
);

6882
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,43 +1,28 @@
{
"name": "tankz",
"version": "0.7.0",
"private": true,
"devDependencies": {
"ansi-colors": "^1.0.1",
"async": "^2.6.0",
"babel-core": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"download": "^6.2.5",
"fancy-log": "^1.3.2",
"fs-extra": "^5.0.0",
"got": "^8.0.1",
"gulp": "github:gulpjs/gulp#4.0",
"gulp-babel": "^7.0.0",
"gulp-clean": "^0.3.2",
"gulp-concat": "^2.6.1",
"gulp-debian": "^0.1.9",
"gulp-run": "^1.7.1",
"gulp-template": "^5.0.0",
"gulp-uglify": "^3.0.0",
"gulp-webserver": "^0.9.1",
"plugin-error": "^0.1.2",
"progress": "^2.0.0",
"promise-streams": "^2.1.1",
"rmdir": "^1.2.0",
"tar": "^4.2.0",
"tmp-file": "^2.0.1",
"unzip-stream": "^0.2.1",
"vinyl-fs": "^3.0.1",
"yargs": "^10.0.3"
},
"haxeDependencies": {
"lime": "6.0.1",
"openfl": "7.0.0",
"promhx": "1.1.0",
"protohx": "0.4.6",
"yaml": "1.3.0",
"haxework": "git@bitbucket.org:shmyga/haxework.git",
"orm": "2.1.0",
"yield": "1.1.2"
}
"name": "tankz",
"version": "0.15.0",
"private": true,
"devDependencies": {
"dateformat": "^3.0.3",
"gulp": "^4.0.0",
"gulp-add": "0.0.2",
"gulp-clean": "^0.4.0",
"gulp-foreach": "^0.1.0",
"gulp-haxetool": "^0.0.19",
"gulp-zip": "^5.0.0",
"yargs": "^13.2.4"
},
"haxeDependencies": {
"haxework": "git@bitbucket.org:shmyga/haxework.git",
"lime": "7.5.0",
"openfl": "8.9.1",
"hxcpp": "4.0.8",
"promhx": "1.1.0",
"protohx": "0.4.6",
"yaml": "1.3.0",
"orm": "2.1.0",
"yield": "2.0.0",
"haxe-crypto": "0.0.7",
"svg": "1.1.2"
}
}

View File

@@ -1,30 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<project>
<meta title="Tank'z" package="ru.m.tankz" version="0.0.0" company="MegaLoMania"/>
<app main="ru.m.tankz.Client" path="target" file="tankz"/>
<source path="src/common/haxe"/>
<source path="src/client/haxe"/>
<source path="src-gen/haxe"/>
<assets path="src/client/resources" rename="resources" include="*"/>
<haxelib name="lime" version="6.0.1"/>
<haxelib name="openfl" version="7.0.0"/>
<haxelib name="promhx" version="1.1.0"/>
<haxelib name="protohx" version="0.4.6"/>
<haxelib name="haxework" version="git"/>
<haxelib name="yaml" version="1.3.0"/>
<haxelib name="yield" version="1.1.2"/>
<window fps="30"/>
<window width="1024" height="768" unless="html5"/>
<haxeflag name="-D" value="swf-gpu"/>
<haxeflag name="-D" value="native-trace"/>
<!--<haxeflag name="-D" value="proto_debug"/>-->
<haxeflag name="-dce" value="no"/>
<!--<haxeflag name="-D" value="dom"/>-->
<haxeflag name="--macro" value="yield.parser.Parser.auto()"/>
<!--<template path="src/client/webapp/index_template.html" rename="index.html"/>-->
<section if="build_editor">
<app main="ru.m.tankz.editor.Editor" path="target" file="editor"/>
<source path="src/editor/haxe"/>
</section>
</project>

View File

@@ -3,6 +3,7 @@
"protoFiles": [
"src/common/proto/core.proto",
"src/common/proto/game.proto",
"src/common/proto/room.proto",
"src/common/proto/pack.proto"
],
"cleanOut": true,

BIN
resources/11756.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

BIN
resources/60016.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

View File

@@ -1,9 +0,0 @@
[Desktop Entry]
Encoding=UTF-8
Type=Application
Comment=Tank'z game
Exec=bash -c 'cd "/usr/share/tankz" && ./tankz'
Icon=/usr/share/tankz/resources/images/tank/player/tank_p3_0-0.png
Name=Tank'z
Categories=Game
Terminal=false

View File

@@ -0,0 +1,43 @@
package ru.m.control;
import haxework.signal.Signal;
import ru.m.control.IControlBus;
class ControlBus implements IControlBus {
private static inline var TAG = "control";
public var devices(default, null):Array<IControlDevice>;
public var signal(default, null):Signal3<DeviceType, DeviceAction, Bool>;
public var devicesSignal(default, null):Signal<Array<IControlDevice>>;
private var connections:Map<DeviceType, DeviceAction->Bool->Void>;
public function new() {
devices = [];
signal = new Signal3();
devicesSignal = new Signal();
connections = new Map();
}
public function connect(device:IControlDevice):Void {
var connector = function(action:DeviceAction, on:Bool):Void {
//L.d("TAG", '${device.type}, ${action}, ${on}');
signal.emit(device.type, action, on);
}
connections.set(device.type, connector);
device.signal.connect(connector);
devices.push(device);
devicesSignal.emit(devices);
}
public function disconnect(device:IControlDevice):Void {
if (connections.exists(device.type)) {
device.signal.disconnect(connections.get(device.type));
connections.remove(device.type);
devices.remove(device);
devicesSignal.emit(devices);
}
}
}

View File

@@ -0,0 +1,8 @@
package ru.m.control;
import ru.m.geom.Direction;
enum DeviceAction {
DIRECTION(direction:Direction);
KEY(code:Int);
}

View File

@@ -0,0 +1,7 @@
package ru.m.control;
enum DeviceType {
NONE;
KEYBOARD;
GAMEPAD(id:Int);
}

View File

@@ -0,0 +1,13 @@
package ru.m.control;
import haxework.signal.Signal;
interface IControlBus {
public var devices(default, null):Array<IControlDevice>;
public var signal(default, null):Signal3<DeviceType, DeviceAction, Bool>;
public var devicesSignal(default, null):Signal<Array<IControlDevice>>;
public function connect(device:IControlDevice):Void;
public function disconnect(device:IControlDevice):Void;
}

View File

@@ -0,0 +1,10 @@
package ru.m.control;
import haxework.signal.Signal;
interface IControlDevice {
public var type(default, null):DeviceType;
public var signal(default, null):Signal2<DeviceAction, Bool>;
public function dispose():Void;
}

View File

@@ -0,0 +1,62 @@
package ru.m.control;
import haxework.signal.Signal;
import lime.ui.Joystick;
import ru.m.control.DeviceAction;
import ru.m.control.DeviceType;
import ru.m.geom.Direction;
class JoystickDevice implements IControlDevice {
public var type(default, null):DeviceType;
public var signal(default, null):Signal2<DeviceAction, Bool>;
private var joystick:Joystick;
private var axisState:Map<Int, Direction>;
public function new(joystick:Joystick) {
this.joystick = joystick;
type = GAMEPAD(joystick.id);
signal = new Signal2();
axisState = new Map();
joystick.onButtonDown.add(onButtonDown);
joystick.onButtonUp.add(onButtonUp);
joystick.onAxisMove.add(onAxisMove);
}
private function onButtonDown(code:Int):Void {
signal.emit(KEY(code), true);
}
private function onButtonUp(code:Int):Void {
signal.emit(KEY(code), false);
}
private function onAxisMove(axis:Int, position:Float):Void {
var direction:Direction = switch [axis, position] {
case [0, 1]: Direction.RIGHT;
case [0, -1]: Direction.LEFT;
case [1, 1]: Direction.BOTTOM;
case [1, -1]: Direction.TOP;
case _: null;
}
if (direction != null) {
axisState.set(axis, direction);
signal.emit(DIRECTION(direction), true);
} else if (position == 0) {
if (axisState.exists(axis)) {
signal.emit(DIRECTION(axisState.get(axis)), false);
axisState.remove(axis);
}
}
}
public function dispose():Void {
if (joystick != null) {
joystick.onButtonDown.remove(onButtonDown);
joystick.onButtonUp.remove(onButtonUp);
joystick.onAxisMove.remove(onAxisMove);
joystick = null;
}
}
}

View File

@@ -0,0 +1,38 @@
package ru.m.control;
import flash.display.Stage;
import flash.events.KeyboardEvent;
import haxework.signal.Signal;
import ru.m.control.DeviceAction;
class KeyboardDevice implements IControlDevice {
public var type(default, null):DeviceType;
public var signal(default, null):Signal2<DeviceAction, Bool>;
private var stage:Stage;
public function new(stage:Stage) {
this.stage = stage;
type = DeviceType.KEYBOARD;
signal = new Signal2();
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
}
private function onKeyDown(event:KeyboardEvent):Void {
signal.emit(KEY(event.keyCode), true);
}
private function onKeyUp(event:KeyboardEvent):Void {
signal.emit(KEY(event.keyCode), false);
}
public function dispose():Void {
if (stage != null) {
stage.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.removeEventListener(KeyboardEvent.KEY_UP, onKeyUp);
stage = null;
}
}
}

View File

@@ -0,0 +1,14 @@
package ru.m.display;
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
class DisplayObjectContainerExtender {
public static function removeChildSafety(self:DisplayObjectContainer, child:DisplayObject):DisplayObject {
if (self.contains(child)) {
return self.removeChild(child);
}
return null;
}
}

View File

@@ -1,17 +0,0 @@
package ru.m.draw;
import flash.geom.ColorTransform;
import flash.geom.Rectangle;
import flash.display.BitmapData;
class BitmapUtil {
public static function colorize(data: BitmapData, color: Color):BitmapData {
if (color.zero) return data;
var result = data.clone();
var transform = new ColorTransform(color.red / 255, color.green / 255, color.blue / 255, 1, 0, 0, 0, 0);
result.colorTransform(new Rectangle(0, 0, result.width, result.height), transform);
return result;
}
}

View File

@@ -1,47 +0,0 @@
package ru.m.draw;
abstract Color(Int) {
public var alpha(get, never):Int;
public var red(get, never):Int;
public var green(get, never):Int;
public var blue(get, never):Int;
public var zero(get, never):Bool;
public inline function new(value:Int) {
this = value;
}
private inline function get_alpha():Int {
return (this >> 24) & 255;
}
private inline function get_red():Int {
return (this >> 16) & 255;
}
private inline function get_green():Int {
return (this >> 8) & 255;
}
private inline function get_blue():Int {
return this & 255;
}
private inline function get_zero():Bool {
return this == 0;
}
@:from
static public inline function fromInt(value:Int):Color {
return new Color(value);
}
@:from
static public inline function fromString(value:String):Color {
return new Color(Std.parseInt('0x${value.split('#').pop()}'));
}
public function toString():String {
return 'Color(${red},${green},${blue})';
}
}

View File

@@ -0,0 +1,45 @@
package ru.m.skin;
import format.SVG;
import haxework.color.Color;
import haxework.color.ColorUtil;
import haxework.view.ButtonView;
import haxework.view.skin.ISkin;
class ButtonSVGSkin implements ISkin<ButtonView> {
private var svg:String;
private var color:Color;
private var svgs:Map<ButtonState, SVG>;
public function new(svg:String, color:Color) {
this.svg = svg;
this.color = color;
init();
}
private inline function buildSVG(color:Color):SVG {
return new SVG(StringTools.replace(svg, "currentColor", '#${StringTools.hex(color)}'));
}
private function init():Void {
svgs = new Map<ButtonState, SVG>();
svgs.set(ButtonState.UP, buildSVG(color));
svgs.set(ButtonState.DOWN, buildSVG(ColorUtil.diff(color, -24)));
svgs.set(ButtonState.OVER, buildSVG(ColorUtil.diff(color, 24)));
svgs.set(ButtonState.DISABLED, buildSVG(ColorUtil.grey(color)));
}
public function draw(view:ButtonView):Void {
var svg = svgs.get(view.state);
var graphics = view.content.graphics;
graphics.beginFill(0, 0);
graphics.drawRect(0, 0, view.width, view.height);
graphics.beginFill(color);
graphics.lineStyle(2, ColorUtil.multiply(color, 1.5));
svg.render(graphics, 0, 0, Std.int(view.width * 0.8), Std.int(view.height * 0.8));
graphics.lineStyle();
graphics.endFill();
}
}

View File

@@ -1,112 +1,39 @@
package ru.m.tankz;
import flash.events.KeyboardEvent;
import flash.text.Font;
import flash.ui.Keyboard;
import haxework.gui.ButtonView;
import haxework.gui.frame.IFrameSwitcher;
import haxework.gui.Root;
import haxework.gui.VGroupView;
import haxework.gui.ViewBuilder;
import flash.Lib;
import haxework.animate.Animate;
import haxework.log.TraceLogger;
import haxework.provider.Provider;
import haxework.resources.IResources;
import haxework.resources.Resources;
import ru.m.connect.IConnection;
import ru.m.tankz.bundle.ConfigBundle;
import ru.m.tankz.bundle.IConfigBundle;
import ru.m.tankz.bundle.ILevelBundle;
import ru.m.tankz.bundle.LevelBundle;
import ru.m.tankz.frame.StartFrame;
import ru.m.tankz.game.ClassicGame;
import ru.m.tankz.game.DotaGame;
import ru.m.tankz.game.Game;
import ru.m.tankz.PacketBuilder;
import ru.m.tankz.storage.SaveStorage;
#if flash import haxework.log.JSLogger; #end
#if debug import haxework.log.SocketLogger; #end
import haxework.view.Root;
import ru.m.tankz.view.ClientView;
interface ClientViewLayout {
var switcher(default, null):IFrameSwitcher;
}
@:template('ru/m/tankz/Client.yaml', 'ru/m/tankz/Style.yaml')
class ClientView extends VGroupView implements ClientViewLayout implements ViewBuilder {}
class Client implements IConnectionHandler {
private static inline var TAG = 'Tankz';
class Client {
private static inline var TAG = "Tankz";
public static function main() {
L.push(new TraceLogger());
#if flash
L.push(new JSLogger());
L.push(new haxework.log.JSLogger());
#end
#if debug
L.push(new SocketLogger());
//L.push(new haxework.log.SocketLogger());
#end
Const.init();
Init.init();
Animate.bind(Lib.current.stage);
L.d(TAG, 'Debug: ${Const.DEBUG}');
L.i(TAG, 'Version: ${Const.VERSION}');
L.i(TAG, 'Build: ${Const.BUILD}');
new Client();
}
private var view:ClientView;
public function new() {
Provider.setFactory(IResources, Resources);
var font:Font = Font.enumerateFonts()[0];
Provider.get(IResources).text.put('font', 'Bookman Old Style');
Provider.get(IResources).text.put('version', 'v${Const.VERSION} b${Const.BUILD}');
Provider.set(IPacketBuilder, new PacketBuilder());
#if flash
Provider.set(IConnection, new ru.m.connect.flash.FlashConnection('localhost', 5001));
#elseif html5
Provider.set(IConnection, new ru.m.connect.js.JsConnection('localhost', 5001));
#if linux
LinuxIcon.apply();
#end
//Provider.get(IConnection).handler.addListener(this);
view = new ClientView();
Provider.set(IFrameSwitcher, view.switcher);
Style.register();
var view:ClientView = new ClientView();
Root.bind(view);
view.content.stage.stageFocusRect = false;
//view.logout.onPress = this;
view.launch();
view.content.stage.addEventListener(KeyboardEvent.KEY_UP, function(event:KeyboardEvent):Void {
if (event.keyCode == Keyboard.ESCAPE) {
view.switcher.change(StartFrame.ID);
}
});
Provider.setFactory(IConfigBundle, ConfigBundle);
Provider.setFactory(ILevelBundle, LevelBundle);
Provider.setFactory(SaveStorage, SaveStorage);
Provider.setFactory(Game, ClassicGame, ClassicGame.TYPE);
Provider.setFactory(Game, DotaGame, DotaGame.TYPE);
view.switcher.change(StartFrame.ID);
}
public function onPress(view:ButtonView):Void {
switch (view.id) {
case 'logout':
Provider.get(IConnection).disconnect();
}
}
public function onConnected():Void {}
public function onDisconnected():Void {
//view.switcher.change(AuthFrame.ID);
}
public function onError(error:Dynamic):Void {
L.e(TAG, '', error);
//view.switcher.change(AuthFrame.ID);
#if debug
var fps = new openfl.display.FPS(0, 0, 0x00ff00);
Lib.current.addChild(fps);
#end
}
}

View File

@@ -1,27 +0,0 @@
---
$type: haxework.gui.VGroupView
pWidth: 100
pHeight: 100
views:
- id: switcher
$type: haxework.gui.frame.FrameSwitcher
pWidth: 100
pHeight: 100
skin:
$type: haxework.gui.skin.BitmapSkin
image: "@asset:image:resources/image/ui/background.png"
fillType: REPEAT
views:
- id: start
$type: ru.m.tankz.frame.StartFrame
- id: level
$type: ru.m.tankz.frame.LevelFrame
- id: game
$type: ru.m.tankz.frame.GameFrame
- $type: haxework.gui.LabelView
$style: label
inLayout: false
contentSize: true
vAlign: BOTTOM
hAlign: RIGHT
text: "@res:text:version"

View File

@@ -3,17 +3,16 @@ package ru.m.tankz;
import flash.Lib;
import flash.system.Capabilities;
class Const {
public static var FPS:Int;
public static var BUILD:String;
public static var VERSION:String;
public static var DEBUG:Bool;
public static var FPS:Int;
public static var BUILD:String;
public static var VERSION:String;
public static var DEBUG:Bool;
public static function init():Void {
FPS = Lib.current.stage.application.config.fps;
BUILD = CompilationOption.get("build");
VERSION = Lib.current.stage.application.config.version;
DEBUG = Capabilities.isDebugger;
}
public static function init():Void {
FPS = Std.parseInt(Lib.current.stage.application.meta.get("fps"));
BUILD = CompilationOption.get("build");
VERSION = Lib.current.stage.application.meta.get("version");
DEBUG = Capabilities.isDebugger;
}
}

View File

@@ -0,0 +1,91 @@
package ru.m.tankz;
import flash.Lib;
import haxework.animate.FadeAnimate;
import haxework.animate.UnFadeAnimate;
import haxework.resources.IResources;
import haxework.resources.Resources;
import haxework.view.popup.PopupManager;
import lime.ui.Gamepad;
import lime.ui.Joystick;
import ru.m.connect.IConnection;
import ru.m.control.ControlBus;
import ru.m.control.IControlBus;
import ru.m.control.JoystickDevice;
import ru.m.control.KeyboardDevice;
import ru.m.tankz.bundle.ConfigBundle;
import ru.m.tankz.bundle.IConfigBundle;
import ru.m.tankz.bundle.ILevelBundle;
import ru.m.tankz.bundle.LevelBundle;
import ru.m.tankz.network.NetworkManager;
import ru.m.tankz.proto.pack.Request;
import ru.m.tankz.proto.pack.Response;
import ru.m.tankz.sound.SoundManager;
import ru.m.tankz.storage.GameStorage;
import ru.m.tankz.storage.NetworkStorage;
import ru.m.tankz.storage.RecordStorage;
import ru.m.tankz.storage.SettingsStorage;
class Init {
@:provide static var resources:IResources;
@:provide static var levelBundle:ILevelBundle;
@:provide static var configBundle:IConfigBundle;
@:provide static var settingsStorage:SettingsStorage;
@:provide static var multiplayerStorage:NetworkStorage;
@:provide static var gameStorage:GameStorage;
@:provide static var recordStorage:RecordStorage;
@:provide static var soundManager:SoundManager;
@:provide static var networkManager:NetworkManager;
@:provide static var popupManager:PopupManager;
@:provide static var connection:IConnection<Request, Response>;
@:provide static var bus:IControlBus;
private static function buildConnection():IConnection<Request, Response> {
var host:String = CompilationOption.get("host");
var port:Int = CompilationOption.get("port");
L.d("Init", 'connect to $host:$port');
#if flash
return new ru.m.connect.flash.FlashConnection<Request, Response>(host, port, Response);
#elseif html5
return new ru.m.connect.js.JsConnection<Request, Response>(host, port + (ru.m.connect.js.JsConnection.isSecured() ? 1 : 0), Response);
#else
return new ru.m.connect.desktop.DesktopConnection<Request, Response>(host, port, Response);
#end
}
public static function init():Void {
resources = new Resources();
levelBundle = new LevelBundle();
configBundle = new ConfigBundle();
settingsStorage = new SettingsStorage();
multiplayerStorage = new NetworkStorage();
gameStorage = new GameStorage();
recordStorage = new RecordStorage();
soundManager = new SoundManager();
popupManager = new PopupManager();
popupManager.showAnimateFactory = function(v) return new UnFadeAnimate(v, 100);
popupManager.closeAnimateFactory = function(v) return new FadeAnimate(v, 100);
connection = buildConnection();
networkManager = new NetworkManager();
bus = new ControlBus();
bus.connect(new KeyboardDevice(Lib.current.stage));
for (device in Gamepad.devices) {
trace('gamepad', device);
}
Gamepad.onConnect.add(function(device) {
trace('connect gamepad', device);
});
for (device in Joystick.devices) {
bus.connect(new JoystickDevice(device));
}
Joystick.onConnect.add(function(device) {
bus.connect(new JoystickDevice(device));
});
}
}

View File

@@ -0,0 +1,27 @@
package ru.m.tankz;
import flash.display.BitmapData;
import flash.filters.ColorMatrixFilter;
import flash.geom.Point;
import flash.Lib;
import openfl.Assets;
class LinuxIcon {
private static function prepareIcon(bitmap:BitmapData):BitmapData {
var matrix:Array<Float> = [];
matrix = matrix.concat([0, 0, 1, 0, 0]);
matrix = matrix.concat([0, 1, 0, 0, 0]);
matrix = matrix.concat([1, 0, 0, 0, 0]);
matrix = matrix.concat([0, 0, 0, 1, 0]);
var cmf:ColorMatrixFilter = new ColorMatrixFilter(matrix);
var bitmap:BitmapData = bitmap.clone();
bitmap.applyFilter(bitmap, bitmap.rect, new Point(0, 0), cmf);
return bitmap;
}
public static function apply() {
var icon = Assets.getBitmapData("resources/icon.png");
Lib.current.stage.window.setIcon(prepareIcon(icon).image);
}
}

View File

@@ -0,0 +1,141 @@
package ru.m.tankz;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.Lib;
import haxework.view.core.Size;
class Progress extends Sprite {
public var color(default, set):Int = 0;
public var backColor(default, set):Int = 0;
public var progress(default, set):Float = 0;
public var size(default, set):Size = [0, 0];
public var radius(get, null):Float;
private var maskShape:Shape;
private var toRedraw:Bool;
public function new() {
super();
maskShape = new Shape();
addChild(maskShape);
mask = maskShape;
}
private inline function get_radius():Float {
return Math.min(size.width, size.height) / 2;
}
private function set_color(value:Int):Int {
if (color != value) {
color = value;
toRedraw = true;
}
return color;
}
private function set_backColor(value:Int):Int {
if (backColor != value) {
backColor = value;
toRedraw = true;
}
return color;
}
private function set_progress(value:Float):Float {
if (progress != value) {
progress = value;
toRedraw = true;
}
return progress;
}
private function set_size(value:Size):Size {
if (size != value) {
size = value;
toRedraw = true;
}
return size;
}
public function update():Void {
if (toRedraw) {
redraw();
redrawMask();
toRedraw = false;
}
}
public function redraw():Void {
graphics.clear();
graphics.beginFill(color);
graphics.drawCircle(radius, radius, radius);
graphics.beginFill(backColor);
graphics.drawCircle(radius, radius, radius / 2);
graphics.endFill();
}
public function redrawMask():Void {
maskShape.graphics.clear();
maskShape.graphics.beginFill(0x00ff00);
maskShape.graphics.moveTo(radius, radius);
var sides = 6;
var rotation = (-(Math.PI) / 2);
var r = radius / Math.cos(1/sides * Math.PI);
var lineToRadians = function(rads:Float):Void {
maskShape.graphics.lineTo(Math.cos(rads) * r + radius, Math.sin(rads) * r + radius);
};
var sidesToDraw:Int = Math.floor(progress * sides);
for (i in 0...sidesToDraw + 1) {
lineToRadians((i / sides) * (Math.PI * 2) + rotation);
}
if (progress * sides != sidesToDraw) {
lineToRadians(progress * (Math.PI * 2) + rotation);
}
maskShape.graphics.endFill();
}
}
class Preloader extends Sprite {
private var progress:Progress;
public function new() {
super();
Lib.current.stage.color = Style.lightColor;
progress = new Progress();
progress.color = Style.darkColor;
progress.backColor = Style.lightColor;
progress.size = [200, 200];
addChild(progress);
onResize(null);
Lib.current.stage.addEventListener(Event.RESIZE, onResize);
Lib.current.stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
Lib.current.stage.addEventListener(ProgressEvent.PROGRESS, onProgress);
addEventListener(Event.COMPLETE, onComplete);
}
private function onResize(event:Event):Void {
progress.x = (Lib.current.stage.stageWidth - progress.size.width) / 2;
progress.y = (Lib.current.stage.stageHeight - progress.size.height) / 2;
}
private function onEnterFrame(event:Event):Void {
progress.update();
}
private function onProgress(event:ProgressEvent):Void {
progress.progress = event.bytesLoaded / event.bytesTotal;
}
private function onComplete(event:Event):Void {
progress.update();
Lib.current.stage.removeEventListener(Event.RESIZE, onResize);
Lib.current.stage.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
Lib.current.stage.removeEventListener(ProgressEvent.PROGRESS, onProgress);
removeEventListener(Event.COMPLETE, onComplete);
}
}

View File

@@ -0,0 +1,164 @@
package ru.m.tankz;
import flash.text.Font;
import flash.text.FontType;
import haxework.color.ColorUtil;
import haxework.resources.IResources;
import haxework.view.core.Geometry;
import haxework.view.core.HAlign;
import haxework.view.core.VAlign;
import haxework.view.ITextView;
import haxework.view.layout.Layout;
import haxework.view.skin.ISkin;
import haxework.view.skin.Skin;
import openfl.Assets;
import ru.m.skin.ButtonSVGSkin;
class Style {
@:provide private static var resources:IResources;
public static var lightColor = 0x95937D;
public static var darkColor = 0x777564;
public static var textColor = 0xE7E0BB;
public static var activeColor = 0xFFFF00;
public static var borderColor = ColorUtil.multiply(lightColor, 1.5);
public static var baseFontSize = 18;
public static var bigFontSize = 22;
public static var veryBigFontSize = 24;
public static var fontFamily = "Courirer New";
public static var fontEmbed = false;
public static function text(color):ISkin<ITextView> {
return Skin.text(color, baseFontSize, fontFamily, fontEmbed);
}
public static function registerButton(name:String, resource:String):Void {
resources.skin.put('button.$name', [
Skin.size(42, 42),
new ButtonSVGSkin(Assets.getText('resources/image/icon/$resource'), lightColor),
]);
resources.skin.put('button.$name.small', [
Skin.size(32, 32),
new ButtonSVGSkin(Assets.getText('resources/image/icon/$resource'), lightColor),
]);
}
public static function textBox(color:Int):SkinSet {
return [
Skin.color(0x000000, 0.1),
Skin.border(lightColor, 1, 2),
Skin.text(color, baseFontSize, fontFamily, fontEmbed),
];
}
public static function register(font:Font = null):Void {
resources.color.put("light", lightColor);
resources.color.put("dark", darkColor);
if (font == null) {
font = Font.enumerateFonts()[0];
}
if (font == null) {
font = Font.enumerateFonts(true)[0];
}
fontFamily = font == null ? "Courirer New" : font.fontName;
fontEmbed = font == null ? false : switch font.fontType {
case DEVICE: false;
case _: true;
};
resources.skin.put("light", [
Skin.color(lightColor),
]);
resources.skin.put("dark", [
Skin.color(darkColor),
]);
resources.skin.put("font", [
Skin.text(textColor, 0, fontFamily, fontEmbed),
]);
resources.skin.put("text", [
Skin.text(textColor, baseFontSize, fontFamily, fontEmbed),
]);
resources.skin.put("scroll.vertical", [
haxework.view.skin.Skin.scrollVertical(lightColor, darkColor),
]);
resources.skin.put("text.header", [
Skin.color(0x000000, 0.1),
Skin.border(lightColor, 1, 2),
Skin.text(textColor, bigFontSize, fontFamily, fontEmbed),
Skin.geometry(new Geometry().setPadding([50, 8]).setMargin([0, 0, 0, 30])),
]);
resources.skin.put("button", [
Skin.buttonColor(lightColor),
Skin.text(textColor, bigFontSize, fontFamily, fontEmbed),
Skin.size(250, 50),
]);
resources.skin.put("text.box", [
Skin.color(0x000000, 0.1),
Skin.border(lightColor, 1, 2),
Skin.text(textColor, baseFontSize, fontFamily, fontEmbed),
]);
resources.skin.put("text.box.active", [
Skin.color(0x55aa55),
Skin.border(0x88dd88, 1, 2),
Skin.text(textColor, baseFontSize, fontFamily, fontEmbed),
]);
resources.skin.put("button.simple", [
Skin.buttonColor(lightColor),
Skin.text(textColor, baseFontSize, fontFamily, fontEmbed),
Skin.geometry(new Geometry().setPadding([25, 8])),
]);
resources.skin.put("button.simple.active", [
Skin.buttonColor(lightColor, activeColor),
Skin.text(activeColor, baseFontSize, fontFamily, fontEmbed),
Skin.geometry(new Geometry().setPadding([25, 8])),
]);
resources.skin.put("button.tab", [
Skin.tabColor(lightColor),
Skin.text(textColor, baseFontSize, fontFamily, fontEmbed),
Skin.geometry(new Geometry().setPadding([25, 8])),
]);
resources.skin.put("border", [
Skin.border(borderColor, 1, 2),
]);
resources.skin.put("scroll", [
Skin.scrollVertical(lightColor, ColorUtil.diff(lightColor, 128)),
]);
resources.skin.put("button.level", [
Skin.buttonColor(lightColor),
Skin.text(textColor, veryBigFontSize, fontFamily, fontEmbed),
Skin.size(64, 64),
]);
resources.skin.put("container", [
Skin.geometry(new Geometry().setSize("100%", "100%")),
Skin.layout(new Layout().setAlign(CENTER, MIDDLE)),
Skin.color(darkColor),
]);
resources.skin.put("panel", [
Skin.geometry(new Geometry().setSize("100%", -1).setPadding([10, 5])),
Skin.layout(new Layout().setAlign(NONE, MIDDLE)),
Skin.color(lightColor),
]);
resources.skin.put("window", [
Skin.color(darkColor),
Skin.border(borderColor, 1, 2),
Skin.geometry(new Geometry().setPadding(2)),
]);
resources.skin.put("window.close", [
Skin.size(36, 36),
new ButtonSVGSkin(Assets.getText("resources/image/icon/window-close-solid.svg"), lightColor),
]);
resources.skin.put("line", [
Skin.color(borderColor),
]);
registerButton("settings", "cog-solid.svg");
registerButton("close", "times-circle-solid.svg");
registerButton("next", "arrow-alt-circle-right-solid.svg");
registerButton("start", "play-circle-solid.svg");
registerButton("login", "sign-in-solid.svg");
registerButton("logout", "sign-out-solid.svg");
}
}

View File

@@ -1,21 +0,0 @@
---
button:
width: 250
height: 60
skin:
$type: haxework.gui.skin.ButtonBitmapSkin
upImage: "@asset:image:resources/image/ui/button/normal.png"
downImage: "@asset:image:resources/image/ui/button/down.png"
overImage: "@asset:image:resources/image/ui/button/over.png"
fillType: NINEPATH
fontFamily: "@res:text:font"
fontEmbed: true
fontColor: "#E7E0BB"
fontSize: 20
label:
fontColor: "#ffffff"
fontEmbed: false
fontFamily: Courirer New
fontSize: 16
shadowColor: 0x000000

View File

@@ -1,30 +1,23 @@
package ru.m.tankz.bundle;
import openfl.Assets;
import ru.m.tankz.bundle.IConfigBundle;
import ru.m.tankz.config.Config;
import ru.m.tankz.Type;
import yaml.Parser;
import yaml.Yaml;
typedef ConfigSource = {
var game:GameConfig;
var map: MapConfig;
var bricks: Array<BrickConfig>;
var presets: Array<GamePreset>;
var points: Array<SpawnPoint>;
var tanks: Array<TankConfig>;
var bonuses: Array<BonusConfig>;
}
class ConfigBundle implements IConfigBundle {
private static function convert(raw:Dynamic):ConfigSource {
return raw;
}
private var _cache:Map<GameType, Config> = new Map();
public function new() {}
public function get(type:GameType):Config {
var source = convert(Yaml.parse(Assets.getText('resources/${type}/config.yaml'), Parser.options().useObjects()));
return new Config(type, source.game, source.map, source.bricks, source.presets, source.points, source.tanks, source.bonuses);
if (!_cache.exists(type)) {
var source:ConfigSource = Yaml.parse(Assets.getText('resources/config/${type}.yaml'), Parser.options().useObjects());
_cache.set(type, Config.fromSource(type, source));
}
return _cache.get(type);
}
}

View File

@@ -5,11 +5,15 @@ import ru.m.tankz.config.Config;
import ru.m.tankz.Type;
import ru.m.tankz.util.LevelUtil;
class LevelBundle implements ILevelBundle {
public function get(type:GameType, config:Config, level:Int):LevelConfig {
var data:String = Assets.getText('resources/${type}/levels/level${LevelUtil.formatLevel(level)}.txt');
return LevelUtil.loads(config, data);
public function new() {}
public function get(id:PackId):LevelPack {
var bytes = Assets.getBytes('levels/${id}.zip');
return {
id: id,
data: LevelUtil.unpack(bytes),
};
}
}

View File

@@ -0,0 +1,12 @@
package ru.m.tankz.control;
import ru.m.control.DeviceAction;
import ru.m.control.DeviceType;
import ru.m.tankz.control.Control;
typedef BindAction = {
var device:DeviceType;
var action:DeviceAction;
}
typedef Binding = Map<TankAction, BindAction>;

View File

@@ -1,63 +1,85 @@
package ru.m.tankz.control;
import flash.events.FocusEvent;
import flash.events.KeyboardEvent;
import flash.Lib;
import flash.ui.Keyboard;
import haxe.Timer;
import ru.m.control.DeviceAction;
import ru.m.control.DeviceType;
import ru.m.control.IControlBus;
import ru.m.geom.Direction;
import ru.m.tankz.control.Control;
import ru.m.tankz.storage.SettingsStorage;
import ru.m.tankz.Type;
typedef KeyBinding = Map<Int, TankAction>;
class HumanControl extends Control {
private var keyBinding:KeyBinding;
private var moveQueue:Array<Int>;
@:provide static var storage:SettingsStorage;
@:provide static var bus:IControlBus;
private var binding:Map<DeviceType, Map<DeviceAction, TankAction>>;
private var moveQueue:Array<Direction>;
private var shotTimer:Timer;
public function new(playerId:PlayerId, controlIndex:Int) {
super(playerId);
this.keyBinding = resolve(controlIndex);
moveQueue = new Array<Int>();
Lib.current.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
Lib.current.stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
//Lib.current.stage.addEventListener(FocusEvent.FOCUS_OUT, onFocusOut);
var config = storage.getBinding(controlIndex);
binding = new Map();
for (action in config.keys()) {
var bind = config.get(action);
if (!binding.exists(bind.device)) {
binding.set(bind.device, new Map());
}
binding.get(bind.device).set(bind.action, action);
}
moveQueue = [];
}
private function onKeyDown(event:KeyboardEvent):Void {
if (keyBinding.exists(event.keyCode)) switch (keyBinding.get(event.keyCode)) {
case TankAction.MOVE(direction):
if (moveQueue.indexOf(event.keyCode) == -1) {
moveQueue.unshift(event.keyCode);
updateMove();
}
case TankAction.SHOT:
if (shotTimer == null) {
shotTimer = new Timer(300);
shotTimer.run = shot;
shot();
}
case _:
}
if (event.keyCode == Keyboard.U) {
action(TankAction.UPGRADE);
private function onDeviceAction(device:DeviceType, action:DeviceAction, on:Bool):Void {
if (binding.exists(device) && binding[device].exists(action)) {
toggleAction(binding[device][action], on);
}
}
private function onKeyUp(event:KeyboardEvent):Void {
if (keyBinding.exists(event.keyCode)) switch (keyBinding.get(event.keyCode)) {
override public function start():Void {
super.start();
bus.signal.connect(onDeviceAction);
}
override public function stop():Void {
super.stop();
bus.signal.disconnect(onDeviceAction);
moveQueue = [];
if (shotTimer != null) {
shotTimer.stop();
shotTimer = null;
}
}
public function toggleAction(action:TankAction, on:Bool):Void {
switch action {
case TankAction.MOVE(direction):
moveQueue.remove(event.keyCode);
if (on) {
if (moveQueue.indexOf(direction) == -1) {
moveQueue.unshift(direction);
}
} else {
moveQueue.remove(direction);
}
updateMove();
case TankAction.SHOT:
if (shotTimer != null) {
shotTimer.stop();
shotTimer = null;
if (on) {
if (shotTimer == null) {
shotTimer = new Timer(300);
shotTimer.run = shot;
shot();
}
} else {
if (shotTimer != null) {
shotTimer.stop();
shotTimer = null;
}
}
case _:
case TankAction.STOP:
}
}
@@ -68,40 +90,13 @@ class HumanControl extends Control {
private function updateMove():Void {
if (moveQueue.length == 0) {
action(TankAction.STOP);
action(STOP);
} else {
switch (keyBinding.get(moveQueue[0])) {
case TankAction.MOVE(direction):
action(TankAction.MOVE(direction));
case _:
}
action(MOVE(moveQueue[0]));
}
}
private function shot():Void {
action(TankAction.SHOT);
}
private static function resolve(controlIndex:Int):KeyBinding {
switch (controlIndex) {
case 0:
return [
Keyboard.A => TankAction.MOVE(Direction.LEFT),
Keyboard.S => TankAction.MOVE(Direction.BOTTOM),
Keyboard.W => TankAction.MOVE(Direction.TOP),
Keyboard.D => TankAction.MOVE(Direction.RIGHT),
Keyboard.SPACE => TankAction.SHOT
];
case 1:
return [
Keyboard.LEFT => TankAction.MOVE(Direction.LEFT),
Keyboard.DOWN => TankAction.MOVE(Direction.BOTTOM),
Keyboard.UP => TankAction.MOVE(Direction.TOP),
Keyboard.RIGHT => TankAction.MOVE(Direction.RIGHT),
Keyboard.NUMPAD_0 => TankAction.SHOT
];
case x:
throw 'Invalid control index ${x}';
}
action(SHOT);
}
}

View File

@@ -1,133 +0,0 @@
package ru.m.tankz.frame;
import flash.events.Event;
import haxe.ds.Option;
import haxe.Timer;
import haxework.gui.frame.IFrameSwitcher;
import haxework.gui.LabelView;
import haxework.gui.VGroupView;
import haxework.gui.ViewBuilder;
import haxework.provider.Provider;
import protohx.Message;
import ru.m.connect.IConnection;
import ru.m.tankz.game.Game;
import ru.m.tankz.game.GameSave;
import ru.m.tankz.game.GameState;
import ru.m.tankz.proto.pack.GameUpdateResponse;
import ru.m.tankz.render.Render;
import ru.m.tankz.storage.SaveStorage;
interface GameFrameLayout {
var state(default, null):LabelView;
var render(default, null):Render;
}
@:template("ru/m/tankz/frame/GameFrame.yaml", "ru/m/tankz/Style.yaml")
class GameFrame extends VGroupView implements ViewBuilder implements IPacketHandler implements GameFrameLayout {
private static inline var TAG = "GameFrame";
public static inline var ID = "game";
private var game:Game;
private var timer:Timer;
public function init():Void {}
public function onShow():Void {
start(Provider.get(GameSave));
}
private function start(save:GameSave):Void {
game = Provider.build(Game, save.state.type);
if (game == null) {
throw 'Unsupported game type "${save.state.type}"';
}
game.engine.listeners.push(render);
game.start(save).then(onGameStateChange).endThen(onGameComplete);
content.addEventListener(Event.ENTER_FRAME, redraw);
//Provider.get(IConnection).packetHandler.addListener(this);
render.draw(game.engine);
timer = new Timer(10);
timer.run = updateEngine;
state.text = stateString(game);
}
private function stop():Void {
//Provider.get(IConnection).packetHandler.removeListener(this);
if (timer != null) {
timer.stop();
timer = null;
}
content.removeEventListener(Event.ENTER_FRAME, redraw);
if (game != null) {
game.dispose();
game = null;
}
render.reset();
}
private function stateString(game:Game):String {
if (game.state == null) {
return '';
}
var result:Array<String> = [];
result.push('Level: ${game.state.level}');
for (team in game.teams) {
if (game.state.loser == team.id) {
result.push('${team.id}: LOSE');
} else if (team.life > -1) {
result.push('${team.id}: ${team.life}');
} else {
for (player in team.players) {
if (player.life > -1) {
result.push('${player.id.team}${player.id.index}: ${player.life}');
}
}
}
}
return '[ ${result.join(' | ')} ]';
}
private function onGameStateChange(s:GameState):GameState {
state.text = stateString(game);
return s;
}
private function onGameComplete(result:Option<GameState>):Void {
switch (result) {
case Option.Some(s):
state.text = stateString(game);
case Option.None:
}
switch (game.next()) {
case Option.Some(s):
var save = game.save();
Provider.get(SaveStorage).write(save);
stop();
start(save);
case Option.None:
Provider.get(IFrameSwitcher).change(StartFrame.ID);
}
}
public function onHide():Void {
stop();
}
private function updateEngine():Void {
game.engine.update();
}
private function redraw(_):Void {
render.draw(game.engine);
}
public function onGameUpdateResponse(packet:GameUpdateResponse):Void {
//engine.updateFromChanges(packet.changes);
render.draw(game.engine);
}
public function onPacket(packet:Message):Void {}
}

View File

@@ -1,12 +0,0 @@
---
pWidth: 100
pHeight: 100
views:
- id: state
$type: haxework.gui.LabelView
$style: label
pWidth: 100
height: 20
- id: render
$type: ru.m.tankz.render.Render
contentSize: true

View File

@@ -1,36 +0,0 @@
package ru.m.tankz.frame;
import ru.m.tankz.game.GameSave;
import haxework.gui.frame.IFrameSwitcher;
import haxework.gui.list.ListView;
import haxework.gui.VGroupView;
import haxework.gui.ViewBuilder;
import haxework.provider.Provider;
import ru.m.tankz.bundle.IConfigBundle;
import ru.m.tankz.game.GameState;
interface LevelFrameLayout {
var levels(default, null):ListView<Int>;
}
@:template("ru/m/tankz/frame/LevelFrame.yaml", "ru/m/tankz/Style.yaml")
class LevelFrame extends VGroupView implements ViewBuilder implements LevelFrameLayout {
public static inline var ID = "level";
public function init():Void {
levels.dispatcher.addListener(this);
}
public function onShow():Void {
var state:GameState = Provider.get(GameSave).state;
var c = Provider.get(IConfigBundle).get(state.type).game.levels;
levels.data = [for (i in 0...c) i];
}
public function onListItemClick(item:IListItemView<Int>):Void {
Provider.get(GameSave).state.level = item.data;
Provider.get(IFrameSwitcher).change(GameFrame.ID);
}
}

View File

@@ -1,20 +0,0 @@
---
pWidth: 100
pHeight: 100
views:
- id: levels
$type: haxework.gui.list.VListView<Int>
factory: "@class:ru.m.tankz.frame.level.LevelView"
pWidth: 100
pHeight: 100
paddings: 10
scroll:
$type: haxework.gui.list.VScrollView
width: 10
pHeight: 100
skin:
$type: haxework.gui.list.VScrollSkin
skin:
$type: haxework.gui.skin.ColorSkin
color: "#000000"
alpha: 0

View File

@@ -1,70 +0,0 @@
package ru.m.tankz.frame;
import ru.m.tankz.storage.SaveStorage;
import ru.m.tankz.game.GameSave;
import haxework.gui.ButtonView;
import haxework.gui.frame.IFrameSwitcher;
import haxework.gui.VGroupView;
import haxework.gui.ViewBuilder;
import haxework.provider.Provider;
import ru.m.tankz.game.ClassicGame;
import ru.m.tankz.game.DotaGame;
import ru.m.tankz.game.GameState;
import ru.m.tankz.Type;
interface StartFrameLayout {
var classic_1p(default, null):ButtonView;
var classic_2p(default, null):ButtonView;
var classic_load(default, null):ButtonView;
var dota_1p(default, null):ButtonView;
var dota_2p_coop(default, null):ButtonView;
var dota_2p_vs(default, null):ButtonView;
}
@:template("ru/m/tankz/frame/StartFrame.yaml", "ru/m/tankz/Style.yaml")
class StartFrame extends VGroupView implements ViewBuilder implements StartFrameLayout {
public static inline var ID = "start";
public function init():Void {
classic_1p.onPress = this;
classic_2p.onPress = this;
classic_load.onPress = this;
dota_1p.onPress = this;
dota_2p_coop.onPress = this;
dota_2p_vs.onPress = this;
}
public function onShow():Void {
classic_load.visible = Provider.get(SaveStorage).read(ClassicGame.TYPE) != null;
}
public function onPress(view:ButtonView):Void {
switch (view.id) {
case 'classic_1p':
startGame(ClassicGame.TYPE, ClassicGame.PLAYER1);
case 'classic_2p':
startGame(ClassicGame.TYPE, ClassicGame.PLAYER2);
case 'classic_load':
loadGame(ClassicGame.TYPE);
case 'dota_1p':
startGame(DotaGame.TYPE, DotaGame.PLAYER1);
case 'dota_2p_coop':
startGame(DotaGame.TYPE, DotaGame.PLAYER2_COOP);
case 'dota_2p_vs':
startGame(DotaGame.TYPE, DotaGame.PLAYER2_VS);
}
}
private function startGame(type:GameType, presetId:PresetId):Void {
Provider.set(GameSave, new GameSave({type: type, presetId: presetId}));
Provider.get(IFrameSwitcher).change(LevelFrame.ID);
}
private function loadGame(type:GameType):Void {
var save:GameSave = Provider.get(SaveStorage).read(type);
Provider.set(GameSave, save);
Provider.get(IFrameSwitcher).change(GameFrame.ID);
}
}

View File

@@ -1,44 +0,0 @@
---
pWidth: 100
pHeight: 100
views:
- $type: haxework.gui.ImageView
image: "@asset:image:resources/image/ui/logo.png"
contentSize: true
bottomMargin: 15
- $type: haxework.gui.LabelView
$style: label
fontSize: 20
topMargin: 15
contentSize: true
text: Classic
- id: classic_1p
$type: haxework.gui.ButtonView
text: 1 Player
$style: button
- id: classic_2p
$type: haxework.gui.ButtonView
text: 2 Player
$style: button
- id: classic_load
$type: haxework.gui.ButtonView
text: Load
$style: button
- $type: haxework.gui.LabelView
$style: label
fontSize: 20
topMargin: 15
contentSize: true
text: DotA
- id: dota_1p
$type: haxework.gui.ButtonView
text: 1 Player
$style: button
- id: dota_2p_coop
$type: haxework.gui.ButtonView
text: 2 COOP
$style: button
- id: dota_2p_vs
$type: haxework.gui.ButtonView
text: 2 VS
$style: button

View File

@@ -1,24 +0,0 @@
package ru.m.tankz.frame.level;
import haxework.gui.ViewBuilder;
import haxework.gui.HGroupView;
import haxework.gui.LabelView;
import haxework.gui.list.ListView.IListItemView;
interface LevelViewLayout {
var label(default, null):LabelView;
}
@:template("ru/m/tankz/frame/level/LevelView.yaml", "ru/m/tankz/Style.yaml")
class LevelView extends HGroupView implements ViewBuilder implements IListItemView<Int> implements LevelViewLayout {
public var item_index(default, default):Int;
public var data(default, set):Int;
private function set_data(value:Int):Int {
data = value;
label.text = 'Level ${data}';
return data;
}
}

View File

@@ -1,15 +0,0 @@
---
width: 440
height: 44
margins: 5
views:
- id: label
$type: haxework.gui.LabelView
$style: label
pWidth: 100
pHeight: 100
text: ""
skin:
$type: haxework.gui.skin.ColorSkin
color: "#000000"
alpha: 0.2

View File

@@ -0,0 +1,13 @@
package ru.m.tankz.local;
import ru.m.tankz.control.BaseControlFactory;
import ru.m.tankz.control.Control;
import ru.m.tankz.control.HumanControl;
import ru.m.tankz.Type;
class LocalControlFactory extends BaseControlFactory {
override private function buildHuman(id:PlayerId, index:Int):Control {
return new HumanControl(id, index);
}
}

View File

@@ -0,0 +1,32 @@
package ru.m.tankz.local;
import ru.m.tankz.config.Config;
import ru.m.tankz.game.GameEvent;
import ru.m.tankz.game.GameRunner;
import ru.m.tankz.game.GameState;
import ru.m.tankz.game.record.GameRecorder;
import ru.m.tankz.local.LocalControlFactory;
import ru.m.tankz.storage.RecordStorage;
class LocalGame extends GameRunner {
@:provide var recordStorage:RecordStorage;
private var recorder:GameRecorder;
public function new(state:GameState, level:LevelConfig) {
super(state, level);
controlFactory = new LocalControlFactory();
recorder = new GameRecorder();
connect(recorder);
}
override public function onGameEvent(event:GameEvent):Void {
super.onGameEvent(event);
switch event {
case GameEvent.COMPLETE(_, _):
disconnect(recorder);
recorder.onGameEvent(event); //ToDo:
recordStorage.save(recorder.record);
case _:
}
}
}

View File

@@ -0,0 +1,16 @@
package ru.m.tankz.network;
import ru.m.tankz.control.HumanControl;
import ru.m.tankz.network.NetworkManager;
import ru.m.tankz.control.Control;
class NetworkControl extends HumanControl {
@:provide private var network:NetworkManager;
override public function action(action:TankAction):Void {
if (tankId > -1) {
network.action(tankId, action);
}
}
}

View File

@@ -0,0 +1,16 @@
package ru.m.tankz.network;
import ru.m.tankz.control.BaseControlFactory;
import ru.m.tankz.control.Control;
import ru.m.tankz.Type;
class NetworkControlFactory extends BaseControlFactory {
override private function buildHuman(id:PlayerId, index:Int):Control {
return new NetworkControl(id, index);
}
override private function buildBot(id:PlayerId, type:String):Control {
return null;
}
}

View File

@@ -0,0 +1,54 @@
package ru.m.tankz.network;
import haxe.Unserializer;
import ru.m.tankz.game.Game;
import ru.m.tankz.game.GameEvent;
import ru.m.tankz.game.GameState;
import ru.m.tankz.network.NetworkControlFactory;
import ru.m.tankz.network.NetworkManager;
import ru.m.tankz.proto.pack.GameEventResponse;
import ru.m.tankz.proto.room.RoomSlotProto;
class NetworkGame extends Game {
private var network:NetworkManager;
public function new(network:NetworkManager) {
super(new GameState(network.room.game.type, 0), null);
this.network = network;
this.controlFactory = new NetworkControlFactory();
network.gameEventSignal.connect(onGameEventProto);
network.stateSignal.connect(onConnectionState);
}
private function onGameEventProto(game:GameEventResponse):Void {
var time = game.event.time;
var eventStr = game.event.event;
var event:GameEvent = Unserializer.run(eventStr);
gameEventSignal.emit(event);
}
private function onConnectionState(state:ConnectionState):Void {
switch state {
case ONLINE(user):
if (network.room != null) {
network.joinGame(network.room.game.id);
}
case _:
}
}
override public function start():Void {
var slot:RoomSlotProto = Lambda.find(network.room.slots, function(slot:RoomSlotProto) return slot.hasUser() && slot.user.uuid == network.user.uuid);
if (slot != null) {
state.controls.push({playerId: [slot.slot.team, slot.slot.index], control: "human-0"});
}
super.start();
}
override public function dispose():Void {
super.dispose();
network.gameEventSignal.disconnect(onGameEventProto);
network.stateSignal.disconnect(onConnectionState);
}
}

View File

@@ -0,0 +1,173 @@
package ru.m.tankz.network;
import ru.m.tankz.proto.game.GameEventProto;
import ru.m.tankz.proto.room.SlotProto;
import ru.m.tankz.proto.room.SlotRequest;
import haxe.Serializer;
import haxework.signal.Signal;
import ru.m.connect.IConnection;
import ru.m.tankz.control.Control;
import ru.m.tankz.game.GameEvent;
import ru.m.tankz.proto.core.UserProto;
import ru.m.tankz.proto.pack.GameEventRequest;
import ru.m.tankz.proto.pack.GameEventResponse;
import ru.m.tankz.proto.pack.LoginRequest;
import ru.m.tankz.proto.pack.LogoutRequest;
import ru.m.tankz.proto.pack.Request;
import ru.m.tankz.proto.pack.Response;
import ru.m.tankz.proto.room.CreateRequest;
import ru.m.tankz.proto.room.JoinRequest;
import ru.m.tankz.proto.room.LeaveRequest;
import ru.m.tankz.proto.room.RoomListRequest;
import ru.m.tankz.proto.room.RoomProto;
import ru.m.tankz.proto.room.RoomRequest;
import ru.m.tankz.proto.room.StartRequest;
import ru.m.tankz.storage.NetworkStorage;
typedef ClientConnection = IConnection<Request, Response>;
enum ConnectionState {
OFFLINE;
CONNECT;
CONNECTED;
LOGIN;
ONLINE(user:User);
ERROR(error:Dynamic);
}
class NetworkManager {
public var state(default, null):ConnectionState;
public var room(default, null):RoomProto;
public var user(default, null):UserProto;
public var stateSignal:Signal<ConnectionState>;
public var listRoomSignal:Signal<Array<RoomProto>>;
public var roomSignal:Signal<RoomProto>;
public var gameEventSignal:Signal<GameEventResponse>;
@:provide private var connection:ClientConnection;
@:provide private var storage:NetworkStorage;
private var reconnectTimer:Timer;
private var reconnectDelay:Int;
public function new() {
reconnectDelay = 500;
stateSignal = new Signal();
listRoomSignal = new Signal();
roomSignal = new Signal();
gameEventSignal = new Signal();
updateState(OFFLINE);
connection.handler.connect(onConnectionEvent);
connection.receiveHandler.connect(onResponse);
connect();
}
private function updateState(value:ConnectionState):Void {
state = value;
stateSignal.emit(value);
}
public function login(name:String, uuid:String = null):Void {
updateState(LOGIN);
connection.send(new Request().setLogin(
new LoginRequest()
.setUuid(uuid)
.setName(name)
));
}
public function logout():Void {
connection.send(new Request().setLogout(new LogoutRequest()));
}
public function listGame(subscribe:Bool):Void {
connection.send(new Request().setRoomList(new RoomListRequest().setSubscribe(subscribe)));
}
public function createGame(type:String, level:Int):Void {
connection.send(new Request().setRoom(new RoomRequest().setCreate(new CreateRequest().setType(type).setLevel(level))));
}
public function joinGame(gameId:Int, restore:Bool = false):Void {
connection.send(new Request().setRoom(new RoomRequest().setJoin(new JoinRequest().setGameId(gameId).setRestore(restore))));
}
public function selectSlot(slot:SlotProto):Void {
connection.send(new Request().setRoom(new RoomRequest().setSlot(new SlotRequest().setSlot(slot))));
}
public function leaveGame():Void {
connection.send(new Request().setRoom(new RoomRequest().setLeave(new LeaveRequest())));
}
public function startGame():Void {
connection.send(new Request().setRoom(new RoomRequest().setStart(new StartRequest())));
}
public function action(tankId:Int, action:TankAction):Void {
connection.send(new Request().setGameEvent(new GameEventRequest().setEvent(
new GameEventProto().setTime(0).setEvent(
Serializer.run(GameEvent.ACTION(tankId, action))
)))
);
}
private function connect():Void {
if (reconnectTimer != null) {
reconnectTimer.stop();
reconnectTimer = null;
}
reconnectTimer = null;
updateState(CONNECT);
connection.connect().catchError(function(error) {});
}
private function reconnect():Void {
reconnectDelay = Std.int(Math.min(reconnectDelay * 2, 10000));
if (reconnectTimer == null) {
reconnectTimer = Timer.delay(connect, reconnectDelay);
}
}
private function onConnectionEvent(event:ConnectionEvent):Void {
updateState(switch event {
case CONNECTED: CONNECTED;
case DISCONNECTED: OFFLINE;
case ERROR(error): ERROR(error);
});
switch event {
case CONNECTED:
reconnectDelay = 500;
var user = storage.user;
if (user != null) {
login(user.name, user.uuid);
}
case DISCONNECTED | ERROR(_):
reconnect();
}
}
private function onResponse(packet:Response):Void {
if (packet.hasLogin()) {
this.user = packet.login.user;
var user = {
uuid: this.user.uuid,
name: this.user.name,
};
storage.user = user;
updateState(ONLINE(user));
} else if (packet.hasLogout()) {
storage.user = null;
updateState(CONNECTED);
} else if (packet.hasRoomList()) {
listRoomSignal.emit(packet.roomList.rooms);
} else if (packet.hasRoom()) {
room = packet.room.room;
roomSignal.emit(room);
} else if (packet.hasGameEvent()) {
gameEventSignal.emit(packet.gameEvent);
}
}
}

View File

@@ -1,14 +1,8 @@
package ru.m.tankz.render;
import ru.m.draw.BitmapUtil;
import ru.m.draw.Color;
import flash.display.BitmapData;
import openfl.Assets;
import ru.m.animate.Animate;
import ru.m.animate.OnceAnimate;
import ru.m.tankz.core.Tank;
import ru.m.tankz.Type;
class AnimateBundle {
@@ -45,27 +39,4 @@ class AnimateBundle {
length: 5
})]);
}
public static function tankFrames(tank:Tank):Array<Frame> {
var color:Color = switch (tank.hits) {
case 1: 0x869C43;
case 2: 0xDEAF80;
case 3: 0x5EA67A;
case _: tank.color;
}
var colors:Array<Color> = [color, color];
if (tank.bonus) {
colors[1] = 0xff00aa;
}
return [for (i in 0...2) ({
image: BitmapUtil.colorize(Assets.getBitmapData('resources/image/tank/${tank.config.skin}-${i}.png'), colors[i]),
length: 3
})];
}
public static function bonusFrames(type:BonusType):Array<Frame> {
var image = Assets.getBitmapData('resources/image/bonus/${type}.png');
var empty = new BitmapData(image.width, image.height, true, 0x00000000);
return [{image: image, length: 15}, {image: empty, length: 15}];
}
}

View File

@@ -0,0 +1,12 @@
package ru.m.tankz.render;
import haxework.view.IView;
import ru.m.tankz.config.Config;
import ru.m.tankz.game.IGame;
interface IRender extends IView<Dynamic> extends GameListener {
public var config(default, set):Config;
public var gridSize(default, set):GridSize;
public function draw():Void;
public function reset():Void;
}

View File

@@ -3,16 +3,33 @@ package ru.m.tankz.render;
import flash.display.DisplayObjectContainer;
import flash.display.Graphics;
import flash.display.Sprite;
import haxework.gui.SpriteView;
import flash.events.Event;
import haxe.Timer;
import haxework.view.LabelView;
import haxework.view.SpriteView;
import promhx.Promise;
import ru.m.animate.Animate;
import ru.m.animate.OnceAnimate;
import ru.m.geom.Point;
import ru.m.tankz.config.Config;
import ru.m.tankz.core.EntityType;
import ru.m.tankz.engine.Engine;
import ru.m.tankz.render.RenderItem;
import ru.m.tankz.game.GameEvent;
import ru.m.tankz.render.item.BonusRenderItem;
import ru.m.tankz.render.item.BrickRenderItem;
import ru.m.tankz.render.item.BulletRenderItem;
import ru.m.tankz.render.item.EagleRenderItem;
import ru.m.tankz.render.item.IRenderItem;
import ru.m.tankz.render.item.TankRenderItem;
import ru.m.tankz.Type;
using ru.m.display.DisplayObjectContainerExtender;
class Render extends SpriteView implements IRender {
class Render extends SpriteView implements EngineListener {
public var config(default, set):Config;
public var gridSize(default, set):GridSize;
private var mapWidth(get, null):Float;
private var mapHeight(get, null):Float;
private var backgroundLayer:Sprite;
private var groundLayer:Sprite;
@@ -20,8 +37,7 @@ class Render extends SpriteView implements EngineListener {
private var upLayer:Sprite;
private var upperLayer:Sprite;
private var background:Sprite;
private var items:Map<String, RenderItem<Dynamic, Dynamic>>;
private var items:Map<Int, IRenderItem>;
public function new() {
super();
@@ -31,143 +47,234 @@ class Render extends SpriteView implements EngineListener {
entryLayer = new Sprite();
upLayer = new Sprite();
upperLayer = new Sprite();
contentAsSprite.addChild(backgroundLayer);
contentAsSprite.addChild(groundLayer);
contentAsSprite.addChild(entryLayer);
contentAsSprite.addChild(upLayer);
contentAsSprite.addChild(upperLayer);
content.addChild(backgroundLayer);
content.addChild(groundLayer);
content.addChild(entryLayer);
content.addChild(upLayer);
content.addChild(upperLayer);
reset();
}
private function drawBackground(game:Engine):Void {
var mapWidth = game.map.gridWidth * game.map.cellWidth;
var mapHeight = game.map.gridHeight * game.map.cellHeight;
private function get_mapWidth():Float {
return config.map.cell.width * (gridSize != null ? gridSize.width : config.map.grid.width);
}
private function get_mapHeight():Float {
return config.map.cell.height * (gridSize != null ? gridSize.height : config.map.grid.height);
}
private function set_config(value:Config):Config {
config = value;
setContentSize(mapWidth, mapHeight, "render");
drawBackground();
return config;
}
private function set_gridSize(value:GridSize):GridSize {
gridSize = value;
setContentSize(mapWidth, mapHeight, "render");
drawBackground();
return gridSize;
}
private function drawBackground():Void {
var g:Graphics = backgroundLayer.graphics;
g.clear();
g.beginFill(0x000000);
g.drawRect(0, 0, mapWidth, mapHeight);
g.endFill();
if (contentSize) {
width = mapWidth;
height = mapHeight;
}
public function draw():Void {
for (item in items) {
item.update();
}
}
public function draw(game:Engine):Void {
for (brick in game.map.bricks) if (brick.config.index > 0) {
if (!items.exists(brick.key)) {
var item:RenderItem<Dynamic, Dynamic> = switch(brick.config.type) {
case 'ace' | 'bush': new BrickItem(brick);
case 'water': new BrickAnimateItem(brick);
case 'armor' | 'brick': new BrickBreakingItem(brick);
case x: null;
};
if (item != null) {
items[brick.key] = item;
if (brick.config.layer > 2) {
private function onEnterFrame(event:Event):Void {
draw();
}
private function clearLayer(layer:DisplayObjectContainer) {
while (layer.numChildren > 0) {
layer.removeChildAt(0);
}
}
public function reset():Void {
content.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
for (item in items.iterator()) {
item.dispose();
}
items = new Map();
clearLayer(entryLayer);
clearLayer(groundLayer);
clearLayer(upLayer);
clearLayer(upperLayer);
}
public function onGameEvent(event:GameEvent):Void {
switch event {
case START(_, level):
gridSize = level.size;
content.addEventListener(Event.ENTER_FRAME, onEnterFrame);
case COMPLETE(_, _):
content.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
case SPAWN(BRICK(bricks)):
drawBackground();
for (brick in bricks) {
var item:IRenderItem = new BrickRenderItem(brick.rect, brick.type);
var config = config.getBrick(brick.type);
items[brick.id] = item;
if (config.layer > 2) {
upLayer.addChild(item.view);
} else {
groundLayer.addChild(item.view);
}
}
}
}
for (item in items) {
item.update();
}
if (background == null) {
drawBackground(game);
}
}
private function clearLayer(layer:DisplayObjectContainer) {
while (layer.numChildren > 0) layer.removeChildAt(0);
}
public function reset():Void {
for (item in items.iterator()) {
item.dispose();
}
items = new Map();
if (background != null) {
backgroundLayer.removeChild(background);
background = null;
}
clearLayer(entryLayer);
clearLayer(groundLayer);
clearLayer(upLayer);
}
public function onSpawn(entity:EntityType):Void {
switch(entity) {
case EntityType.TANK(tank):
var item = new TankItem(tank);
items.set(tank.key, item);
case SPAWN(EAGLE(id, rect, teamId)):
var item = new EagleRenderItem(rect, config.getColor(new PlayerId(teamId, -1)));
items.set(id, item);
entryLayer.addChild(item.view);
item.update();
playAnimate(tank.rect.center, AnimateBundle.tankSpawn());
case EntityType.BULLET(bullet):
var item = new BulletItem(bullet);
items.set(bullet.key, item);
case SPAWN(TANK(id, rect, playerId, info)):
var item = new TankRenderItem(rect);
var tankConfig = config.getTank(info.type);
item.color = info.color;
item.skin = tankConfig.skin;
item.hits = info.hits;
item.bonus = info.bonus;
item.name = info.name == null ? "" : info.name;
items.set(id, item);
entryLayer.addChild(item.view);
item.update();
case EntityType.EAGLE(eagle):
var item = new EagleItem(eagle);
items.set(eagle.key, item);
playAnimate(item.rect.center, AnimateBundle.tankSpawn());
case SPAWN(BULLET(id, rect, playerId, piercing)):
var item = new BulletRenderItem(rect, piercing);
items.set(id, item);
entryLayer.addChild(item.view);
item.update();
case EntityType.BONUS(bonus):
var item = new BonusItem(bonus);
items.set(bonus.key, item);
case SPAWN(BONUS(id, rect, type)):
var item = new BonusRenderItem(rect, type);
items.set(id, item);
upperLayer.addChild(item.view);
item.update();
case _:
}
}
public function onChange(entity:EntityType, ?change:EntityChange):Void {}
public function onCollision(entity:EntityType, with:EntityType):Void {
switch [entity, with] {
case [EntityType.BULLET(_), EntityType.EAGLE(eagle)]:
if (eagle.death) {
playAnimate(eagle.rect.center, AnimateBundle.tankBoom());
case MOVE(EAGLE(id, position)):
if (items.exists(id)) {
var item = items[id];
item.move(position);
}
case _:
}
}
public function onDestroy(entity:EntityType):Void {
switch entity {
case EntityType.TANK(tank):
if (items.exists(tank.key)) {
entryLayer.removeChild(items.get(tank.key).view);
items.remove(tank.key);
playAnimate(tank.rect.center, AnimateBundle.tankBoom());
case MOVE(BULLET(id, position)):
if (items.exists(id)) {
var item = items[id];
item.move(position);
}
case EntityType.BULLET(bullet):
if (items.exists(bullet.key)) {
entryLayer.removeChild(items.get(bullet.key).view);
items.remove(bullet.key);
var point = bullet.rect.center.add(new Point(bullet.rect.width * bullet.rect.direction.x, bullet.rect.height * bullet.rect.direction.y));
case MOVE(TANK(id, position)):
if (items.exists(id)) {
var item = items[id];
item.move(position);
cast(item, TankRenderItem).moves = true;
}
case STOP(TANK(id)):
if (items.exists(id)) {
var item = items[id];
cast(item, TankRenderItem).moves = false;
}
case CHANGE(TANK(id, type, hits, bonus)):
if (items.exists(id)) {
var item:TankRenderItem = cast items[id];
item.skin = config.getTank(type).skin;
item.hits = hits;
item.bonus = bonus;
}
case CHANGE(TANK_PROTECT(id, state)):
if (items.exists(id)) {
var item:TankRenderItem = cast items[id];
item.protect = state;
}
case CHANGE(EAGLE_PROTECT(id, state)):
if (items.exists(id)) {
var item:EagleRenderItem = cast items[id];
item.protect = state;
}
case CHANGE(BRICK(id, type)):
if (items.exists(id)) {
var item:BrickRenderItem = cast items[id];
item.type = type;
}
case DESTROY(TANK(id, shot)):
if (items.exists(id)) {
var item = items[id];
entryLayer.removeChild(item.view);
playAnimate(item.rect.center, AnimateBundle.tankBoom());
if (shot.score != null) {
showScore(item.rect.center, shot.score);
}
items.remove(id);
}
case DESTROY(BULLET(id)):
if (items.exists(id)) {
var item = items[id];
entryLayer.removeChild(item.view);
var rect = item.rect;
// move boom
var point = rect.center.add(new Point(rect.width * rect.direction.x, rect.height * rect.direction.y));
playAnimate(point, AnimateBundle.bulletBoom());
items.remove(id);
}
case EntityType.BONUS(bonus):
if (items.exists(bonus.key)) {
upperLayer.removeChild(items.get(bonus.key).view);
items.remove(bonus.key);
case DESTROY(EAGLE(id, shot)):
if (items.exists(id)) {
var item = items[id];
playAnimate(item.rect.center, AnimateBundle.tankBoom());
if (shot.score != null) {
showScore(item.rect.center, shot.score);
}
cast(item, EagleRenderItem).death = true;
}
case DESTROY(BONUS(id, shot)):
if (items.exists(id)) {
var item = items[id];
upperLayer.removeChild(item.view);
if (shot.score != null) {
showScore(item.rect.center, shot.score);
}
items.remove(id);
}
case DESTROY(CELL(id, x, y, shot)):
var item:BrickRenderItem = cast items.get(id);
item.destroyCell(x, y);
case DESTROY(BRICK(id, shot)):
var item:BrickRenderItem = cast items.get(id);
item.destroy();
case _:
}
#if cpp
flash.Lib.current.stage.invalidate();
#end
}
private function playAnimate(point:Point, animate:OnceAnimate):Void {
private function playAnimate(point:Point, animate:OnceAnimate):Promise<Dynamic> {
animate.x = point.x - animate.width / 2;
animate.y = point.y - animate.height / 2;
upperLayer.addChild(animate);
animate.play().then(function(animate:Animate):Void {
upperLayer.removeChild(animate);
return animate.play().then(function(animate:Animate):Void {
// ToDo: clean animates on reset
if (upperLayer.contains(animate)) {
upperLayer.removeChildSafety(animate);
}
animate.dispose();
});
}
private function showScore(point:Point, score:Int):Void {
var view:LabelView = new LabelView();
view.skinId = "text";
view.text = Std.string(score);
view.update();
view.redraw();
view.x = point.x - view.width / 2;
view.y = point.y - view.height / 2;
upperLayer.addChild(view.content);
Timer.delay(function() upperLayer.removeChildSafety(view.content), 1000);
}
}

View File

@@ -1,287 +0,0 @@
package ru.m.tankz.render;
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.display.Shape;
import flash.display.Sprite;
import openfl.Assets;
import ru.m.animate.Animate;
import ru.m.geom.Direction;
import ru.m.geom.Rectangle;
import ru.m.tankz.core.Bonus;
import ru.m.tankz.core.Bullet;
import ru.m.tankz.core.Eagle;
import ru.m.tankz.core.Tank;
import ru.m.tankz.map.Brick;
import ru.m.tankz.Type.BrickType;
typedef TRectangle = {
var rect(default, null):Rectangle;
}
class RenderItem<T:TRectangle, D:DisplayObject> {
public var value(default, null):T;
public var view(default, null):D;
public function new(value:T) {
this.value = value;
this.view = null;
}
public function redraw():Void {}
public function update():Void {
var rect = value.rect;
view.rotation = calcRotate(rect.direction);
view.x = rect.x - rect.width * (rect.direction.x + 1) / 2 + rect.width * (rect.direction.y + 1) / 2 + 0.5 * rect.width;
view.y = rect.y - rect.height * (rect.direction.x + 1) / 2 - rect.height * (rect.direction.y + 1) / 2 + 1.5 * rect.height;
}
private static function calcRotate(direction:Direction):Float {
return (if (direction == Direction.RIGHT) {
0;
} else if (direction == Direction.LEFT) {
180;
} else if (direction == Direction.TOP) {
270;
} else if (direction == Direction.BOTTOM) {
90;
} else {
0;
});
}
public function dispose():Void {}
}
class BitmapItem<T:TRectangle> extends RenderItem<T, Bitmap> {
public function new(value:T) {
super(value);
this.view = new Bitmap();
redraw();
}
override public function redraw():Void {
view.bitmapData = Assets.getBitmapData(getImage());
}
private function getImage():String {
return 'ERROR';
}
}
class BrickItem extends BitmapItem<Brick> {
private var type:BrickType;
public function new(value:Brick) {
super(value);
redraw();
}
override public function update():Void {
super.update();
var t = value.config.type;
if (t != type) {
type = t;
view.visible = t != 'none';
redraw();
}
}
override private function getImage():String {
return 'resources/image/map/${value.config.type}.png';
}
}
class BrickAnimateItem extends AnimateItem<Brick> {
public function new(value:Brick) {
super(value);
redraw();
}
override public function redraw():Void {
view.frames = [for (i in 0...2) ({
image: Assets.getBitmapData('resources/image/map/${value.config.type}-${i}.png'),
length: 15
})];
view.playing = true;
}
}
class BrickBreakingItem extends RenderItem<Brick, Shape> {
private var broken:Int;
private var type:BrickType;
public function new(value:Brick) {
super(value);
this.view = new Shape();
redraw();
}
override public function redraw():Void {
var image = Assets.getBitmapData(getImage());
var g = view.graphics;
g.clear();
if (value.destroyed) return;
if (value.config.index > 0) {
g.beginBitmapFill(image);
g.drawRect(0, 0, value.rect.width, value.rect.height);
for (c in value.cells) {
if (c.destroyed) {
g.beginFill(0x000000);
g.drawRect(c.rect.x - value.rect.x, c.rect.y - value.rect.y, c.rect.width, c.rect.height);
}
}
g.endFill();
}
}
override public function update():Void {
super.update();
var b = value.broken;
var t = value.config.type;
if (b != broken || t != type) {
broken = b;
type = t;
redraw();
}
}
private function getImage():String {
return 'resources/image/map/${value.config.type}.png';
}
}
class AnimateItem<T:TRectangle> extends RenderItem<T, Animate> {
public function new(value:T) {
super(value);
view = new Animate();
}
override public function dispose():Void {
view.dispose();
}
}
class TankItem extends RenderItem<Tank, Sprite> {
private var type:String;
private var hits:Int;
private var protected:Bool;
private var frozen:Bool;
private var tankView:Animate;
private var protectView:Animate;
public function new(value:Tank) {
super(value);
view = new Sprite();
tankView = new Animate();
view.addChild(tankView);
protectView = AnimateBundle.tankProtect();
protectView.visible = false;
view.addChild(protectView);
redraw();
}
override public function redraw():Void {
tankView.frames = AnimateBundle.tankFrames(value);
if (value.protect.active) {
protectView.x = (tankView.frames[0].image.width - protectView.frames[0].image.width) / 2;
protectView.y = (tankView.frames[0].image.height - protectView.frames[0].image.height) / 2;
protectView.playing = true;
protectView.visible = true;
} else {
protectView.playing = false;
protectView.visible = false;
}
}
private function getFrames():Array<String> {
var frame0 = 'resources/image/tank/${value.config.skin}-0.png';
var frame1 = 'resources/image/tank/${value.config.skin}-1.png';
return [frame1, frame0];
}
override public function update():Void {
super.update();
var t = value.config.type;
var h = value.hits;
var p = value.protect.active;
var f = value.freezing.active;
if (t != type || h != hits || p != protected || f != frozen) {
this.type = t;
this.hits = h;
this.protected = p;
this.frozen = f;
redraw();
}
tankView.playing = !value.freezing.active && (value.mx !=0 || value.my != 0);
}
override public function dispose():Void {
if (tankView != null) {
tankView.dispose();
tankView = null;
}
}
}
class BulletItem extends BitmapItem<Bullet> {
override private function getImage():String {
var type:String = 'normal';
if (value.config.piercing > 0) type = 'piercing';
return 'resources/image/bullet/${type}.png';
}
}
class EagleItem extends BitmapItem<Eagle> {
private var death:Bool;
private var protected:Bool;
override public function update():Void {
super.update();
var d = value.death;
var p = value.protect.active;
if (d != death || p != protected) {
death = d;
protected = p;
redraw();
}
}
override private function getImage():String {
var suffix = value.death ? '-death' : value.protect.active ? '-protected' : '';
return 'resources/image/eagle/eagle${suffix}.png';
}
}
class BonusItem extends AnimateItem<Bonus> {
public function new(value:Bonus) {
super(value);
redraw();
}
override public function redraw():Void {
var image = Assets.getBitmapData('resources/image/bonus/${value.config.type}.png');
view.frames = AnimateBundle.bonusFrames(value.config.type);
view.playing = true;
}
}

View File

@@ -0,0 +1,33 @@
package ru.m.tankz.render.item;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.PixelSnapping;
import openfl.Assets;
import ru.m.geom.Rectangle;
class BitmapRenderItem extends RenderItem {
public var image(default, set):String;
private var bitmapData:BitmapData;
private var bitmap:Bitmap;
public function new(rect:Rectangle) {
super(rect);
this.bitmap = new Bitmap(null, PixelSnapping.AUTO, true);
}
override private function get_view():DisplayObject {
return bitmap;
}
private function set_image(value:String):String {
if (image != value) {
image = value;
bitmapData = Assets.getBitmapData(image);
bitmap.bitmapData = bitmapData;
}
return image;
}
}

View File

@@ -0,0 +1,34 @@
package ru.m.tankz.render.item;
import ru.m.geom.Rectangle;
import ru.m.tankz.Type;
class BonusRenderItem extends BitmapRenderItem {
public var type(default, set):BonusType;
private var d = -0.05;
private var alpha = 1.0;
public function new(rect:Rectangle, type:BonusType) {
super(rect);
this.type = type;
move(rect.position);
}
private function set_type(value:BonusType):BonusType {
if (type != value) {
type = value;
image = 'resources/image/bonus/${type}.png';
}
return type;
}
override public function update():Void {
super.update();
alpha += d;
view.alpha = alpha;
if (alpha <= 0 || alpha >= 1.5) {
d = -d;
}
}
}

View File

@@ -0,0 +1,91 @@
package ru.m.tankz.render.item;
import flash.display.BitmapData;
import flash.display.Shape;
import openfl.Assets;
import openfl.display.DisplayObject;
import ru.m.geom.Point;
import ru.m.geom.Rectangle;
import ru.m.tankz.Type.BrickType;
enum BrickState {
UNBROKEN;
BROKEN;
DESTROYED;
}
class BrickRenderItem extends RenderItem {
public var type(default, set):BrickType;
public var state(get, never):BrickState;
private var image:BitmapData;
private var shape:Shape;
private var cells:Array<Point>;
public function new(rect:Rectangle, type:BrickType) {
super(rect);
this.shape = new Shape();
cells = [
new Point(0, 0),
new Point(0, 1),
new Point(1, 0),
new Point(1, 1),
];
this.type = type;
move(rect.position);
}
private function get_state():BrickState {
return switch cells.length {
case 0: DESTROYED;
case 4: UNBROKEN;
case _: BROKEN;
}
}
override private function get_view():DisplayObject {
return shape;
}
private function set_type(value:BrickType):BrickType {
if (type != value) {
type = value;
image = Assets.getBitmapData('resources/image/map/${type}.png');
redraw();
}
return type;
}
public function destroyCell(x:Int, y:Int):Void {
cells = cells.filter(function(point) return !(point.x == x && point.y == y));
redraw();
}
public function destroy():Void {
cells = [];
redraw();
}
public function redraw():Void {
shape.graphics.clear();
if (type == "none") return;
switch state {
case UNBROKEN:
shape.graphics.beginBitmapFill(image);
shape.graphics.drawRect(0, 0, rect.width, rect.height);
shape.graphics.endFill();
case BROKEN:
shape.graphics.beginBitmapFill(image);
for (point in cells) {
var x = point.x * (rect.width / 2);
var y = point.y * (rect.width / 2);
var width = rect.width / 2;
var height = rect.height / 2;
shape.graphics.drawRect(x, y, width, height);
}
shape.graphics.endFill();
case DESTROYED:
}
}
}

View File

@@ -0,0 +1,22 @@
package ru.m.tankz.render.item;
import ru.m.geom.Rectangle;
class BulletRenderItem extends BitmapRenderItem {
public var piercing(default, set):Int = -1;
public function new(rect:Rectangle, piercing:Int) {
super(rect);
this.piercing = piercing;
move(rect.position);
}
private function set_piercing(value:Int):Int {
if (piercing != value) {
piercing = value;
var type = piercing > 0 ? 'piercing' : 'normal';
image = 'resources/image/bullet/${type}.png';
}
return piercing;
}
}

View File

@@ -0,0 +1,58 @@
package ru.m.tankz.render.item;
import flash.display.DisplayObject;
import flash.display.Sprite;
import haxework.color.Color;
import haxework.view.utils.BitmapUtil;
import ru.m.animate.Animate;
import ru.m.geom.Rectangle;
class EagleRenderItem extends BitmapRenderItem {
public var color(default, default):Color;
public var death(default, set):Bool = true;
public var protect(default, set):Bool;
private var container:Sprite;
private var protectView:Animate;
public function new(rect:Rectangle, color:Color) {
super(rect);
this.color = color;
container = new Sprite();
container.addChild(bitmap);
protectView = AnimateBundle.tankProtect();
protectView.visible = false;
container.addChild(protectView);
death = false;
move(rect.position);
}
override private function get_view():DisplayObject {
return container;
}
private function set_protect(value:Bool):Bool {
if (protect != value) {
protect = value;
if (protect) {
protectView.x = (bitmapData.width - protectView.frames[0].image.width) / 2;
protectView.y = (bitmapData.height - protectView.frames[0].image.height) / 2;
}
protectView.visible = protect;
protectView.playing = protect;
}
return protect;
}
private function set_death(value:Bool):Bool {
if (death != value) {
death = value;
var suffix = death ? '-death' : '';
image = 'resources/image/eagle/eagle${suffix}.png';
if (!color.zero) {
bitmap.bitmapData = bitmapData = BitmapUtil.colorize(bitmapData, color);
}
}
return death;
}
}

View File

@@ -0,0 +1,13 @@
package ru.m.tankz.render.item;
import flash.display.DisplayObject;
import ru.m.geom.Position;
import ru.m.geom.Rectangle;
interface IRenderItem {
public var view(get, null):DisplayObject;
public var rect(default, null):Rectangle;
public function move(position:Position):Void;
public function update():Void;
public function dispose():Void;
}

View File

@@ -0,0 +1,46 @@
package ru.m.tankz.render.item;
import flash.display.DisplayObject;
import ru.m.geom.Position;
import ru.m.geom.Rectangle;
class RenderItem implements IRenderItem {
public var view(get, null):DisplayObject;
public var content(get, null):DisplayObject;
public var rect(default, null):Rectangle;
public function new(rect:Rectangle) {
this.rect = rect.clone();
}
private function get_view():DisplayObject {
throw "Not Implemented";
}
private function get_content():DisplayObject {
return null;
}
public function move(position:Position):Void {
view.x = rect.x = position.x;
view.y = rect.y = position.y;
if (position.direction != null) {
rect.direction = position.direction;
if (content != null) {
content.rotation = rect.direction.angle;
content.x = - rect.width * (rect.direction.x + 1) / 2 + rect.width * (rect.direction.y + 1) / 2 + 0.5 * rect.width;
content.y = - rect.height * (rect.direction.x + 1) / 2 - rect.height * (rect.direction.y + 1) / 2 + 1.5 * rect.height;
} else {
view.rotation = rect.direction.angle;
view.x = rect.x - rect.width * (rect.direction.x + 1) / 2 + rect.width * (rect.direction.y + 1) / 2 + 0.5 * rect.width;
view.y = rect.y - rect.height * (rect.direction.x + 1) / 2 - rect.height * (rect.direction.y + 1) / 2 + 1.5 * rect.height;
}
}
}
public function update():Void {}
public function dispose():Void {}
}

View File

@@ -0,0 +1,150 @@
package ru.m.tankz.render.item;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import haxework.color.Color;
import haxework.text.BitmapTextField;
import haxework.view.utils.BitmapUtil;
import openfl.Assets;
import ru.m.animate.Animate;
import ru.m.geom.Rectangle;
class TankRenderItem extends BitmapRenderItem {
public var color(default, default):Color;
public var skin(default, set):String;
public var hits(default, set):Int;
public var bonus(default, set):Bool;
public var moves(default, set):Bool;
public var protect(default, set):Bool;
public var name(default, set):String;
private var container:Sprite;
private var images:Array<BitmapData>;
private var frame:Int;
private var protectView:Animate;
private var nameView:TextField;
public function new(rect:Rectangle) {
super(rect);
container = new Sprite();
container.addChild(bitmap);
protectView = AnimateBundle.tankProtect();
protectView.visible = false;
container.addChild(protectView);
nameView = buildNameView();
container.addChild(nameView);
move(rect.position);
}
private function buildNameView():TextField {
var result = new BitmapTextField();
result.defaultTextFormat = new TextFormat(Style.fontFamily, 10, 0xffffff);
result.embedFonts = Style.fontEmbed;
result.autoSize = TextFieldAutoSize.LEFT;
result.shadowColor = 0x000000;
result.stroke = true;
return result;
}
override private function get_view():DisplayObject {
return container;
}
override private function get_content():DisplayObject {
return bitmap;
}
private function redraw():Void {
var image1 = Assets.getBitmapData('resources/image/tank/${skin}-0.png');
var image2 = Assets.getBitmapData('resources/image/tank/${skin}-1.png');
var color1:Color = switch hits {
case 1: 0x869C43;
case 2: 0xDEAF80;
case 3: 0x5EA67A;
case _: color;
}
var color2:Color = color1;
if (bonus) {
color1 = 0xff00aa;
}
if (!color1.zero) {
image1 = BitmapUtil.colorize(image1, color1);
}
if (!color1.zero) {
image2 = BitmapUtil.colorize(image2, color2);
}
images = [for (i in 0...6) image1].concat([for (i in 0...6) image2]);
frame = 0;
bitmap.bitmapData = images[frame];
}
private function set_skin(value:String):String {
if (skin != value) {
skin = value;
redraw();
}
return skin;
}
private function set_hits(value:Int):Int {
if (hits != value) {
hits = value;
redraw();
}
return hits;
}
private function set_bonus(value:Bool):Bool {
if (bonus != value) {
bonus = value;
redraw();
}
return bonus;
}
private function set_protect(value:Bool):Bool {
if (protect != value) {
protect = value;
if (protect) {
protectView.x = (images[0].width - protectView.frames[0].image.width) / 2;
protectView.y = (images[0].height - protectView.frames[0].image.height) / 2;
}
protectView.visible = protect;
protectView.playing = protect;
}
return protect;
}
private function set_moves(value:Bool):Bool {
if (moves != value) {
moves = value;
bitmap.bitmapData = images[0];
}
return moves;
}
private function set_name(value:String):String {
if (name != value) {
name = value;
nameView.text = name;
nameView.x = (rect.width - nameView.width) / 2;
nameView.y = -nameView.height / 2; //(rect.height - nameView.height) / 2;
}
return name;
}
override public function update():Void {
super.update();
if (moves) {
frame++;
if (frame > images.length - 1) {
frame = 0;
}
bitmap.bitmapData = images[frame];
}
}
}

View File

@@ -0,0 +1,128 @@
package ru.m.tankz.sound;
import flash.events.Event;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundTransform;
import openfl.utils.Assets;
import ru.m.tankz.config.Config;
import ru.m.tankz.game.GameEvent;
import ru.m.tankz.game.IGame;
class SoundManager implements GameListener {
private static var TAG(default, never):String = "SoundManager";
#if flash
private static var type:String = "mp3";
#else
private static var type:String = "ogg";
#end
public var config(default, default):Config;
public var volume(default, set):Float = 1;
public var mute(default, set):Bool = false;
private var channels:Array<SoundChannel>;
private var transform:SoundTransform;
private var humanTanks:Array<Int>;
private var humanBullets:Array<Int>;
private var liveBonuses:Array<Int>;
public function new() {
channels = [];
updateSoundTransform();
}
private function updateSoundTransform():Void {
transform = new SoundTransform(mute ? 0 : volume);
for (channel in channels) {
channel.soundTransform = transform;
}
}
private function set_volume(value:Float):Float {
if (volume != value) {
volume = value;
updateSoundTransform();
}
return volume;
}
private function set_mute(value:Bool):Bool {
if (mute != value) {
mute = value;
updateSoundTransform();
}
return mute;
}
public function play(id:String):Void {
//L.d(TAG, 'play: ${id}');
var sound:Sound = Assets.getSound('resources/sounds/${id}.${type}');
if (sound != null) {
var channel = sound.play(0, 0, transform);
channel.addEventListener(Event.SOUND_COMPLETE, onSoundComplete);
channels.push(channel);
} else {
L.w(TAG, 'Sound "${id}" not found');
}
}
public function stopAll():Void {
for (channel in channels) {
channel.stop();
}
channels = [];
}
private function onSoundComplete(event:Event):Void {
channels.remove(event.currentTarget);
}
public function onGameEvent(event:GameEvent):Void {
switch event {
case START(_):
play("start");
humanTanks = [];
liveBonuses = [];
humanBullets = [];
case SPAWN(BULLET(id, _, playerId, _)):
if (config.isHuman(playerId)) {
play("shot");
humanBullets.push(id);
}
case SPAWN(TANK(id, _, playerId, _)):
if (config.isHuman(playerId)) {
humanTanks.push(id);
}
case SPAWN(BONUS(id, _, type)):
play("bonus_add");
if (type == "live") {
liveBonuses.push(id);
}
case HIT(TANK(_, _)):
play("bullet_hit");
case HIT(CELL(_, _, shot)):
if (humanBullets.indexOf(shot.bulletId) > -1) {
//play("bullet_block");
}
case DESTROY(TANK(id, _)):
if (humanTanks.indexOf(id) > -1) {
play("boom_player");
} else {
play("boom_bot");
}
case DESTROY(EAGLE(_, _)):
play("boom_player");
case DESTROY(BONUS(id, _)):
play("bonus_get");
if (liveBonuses.indexOf(id) > -1) {
play("live");
} else {
play("bonus_get");
}
case _:
}
}
}

View File

@@ -0,0 +1,22 @@
package ru.m.tankz.storage;
import haxework.storage.SharedObjectStorage;
import ru.m.tankz.game.PackProgress;
import ru.m.tankz.Type;
class GameStorage extends SharedObjectStorage {
private static inline var VERSION = 1;
public function new() {
super('game_${VERSION}');
}
public function get(id:PackId):PackProgress {
return exists(id) ? read(id) : new PackProgress(id);
}
public function set(progress:PackProgress):Void {
write(progress.id, progress);
}
}

View File

@@ -0,0 +1,21 @@
package ru.m.tankz.storage;
import haxework.storage.SharedObjectStorage;
class NetworkStorage extends SharedObjectStorage {
public var user(get, set):User;
public function new() {
super("network");
}
private inline function get_user():User {
return read("user");
}
private inline function set_user(value:User):User {
write("user", value);
return value;
}
}

View File

@@ -0,0 +1,39 @@
package ru.m.tankz.storage;
import haxe.DynamicAccess;
import haxework.storage.SharedObjectStorage;
import ru.m.tankz.game.record.GameRecord;
@:yield class RecordStorage extends SharedObjectStorage {
private static inline var VERSION = 1;
public function new() {
super('record_${VERSION}');
}
public function save(record:GameRecord):Void {
L.d("RecordStorage", 'save $record');
write('${record.info.id}.info', record.info);
write(record.info.id, record);
}
override public function delete(id:String):Void {
super.delete(id);
super.delete('${id}.info');
}
public function iterator():Iterator<GameRecordInfo> {
var data:DynamicAccess<String> = so.data;
for (id in data.keys()) {
try {
if (StringTools.endsWith(id, '.info')) {
@yield return read(id);
}
} catch (error:Dynamic) {
L.w("RecordStorage", 'read ', error);
delete(id);
}
}
}
}

View File

@@ -1,33 +0,0 @@
package ru.m.tankz.storage;
import flash.net.SharedObject;
import ru.m.tankz.Type;
import ru.m.tankz.game.GameSave;
class SaveStorage {
private static var TAG(default, never):String = 'SaveStorage';
private var so:SharedObject;
public function new() {
so = SharedObject.getLocal('tankz');
}
public function read(type:GameType):Null<GameSave> {
var data:String = Reflect.getProperty(so.data, type);
L.d(TAG, 'read: ${data}');
if (data != null) {
return GameSave.fromYaml(data);
}
return null;
}
public function write(save:GameSave):Void {
var data:String = save.toYaml();
L.d(TAG, 'write: ${data}');
so.setProperty(save.state.type, data);
so.flush();
}
}

Some files were not shown because too many files have changed in this diff Show More