Merge: Nitgs optims
[nit.git] / examples / mnit_dino / src / dino.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2012-2013 Alexis Laferrière <alexis.laf@xymus.net>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # App for the Dino game, manages App lifecyle and inputs
18 module dino
19
20 import mnit
21 import realtime
22
23 import graphism
24 import fancy_dino
25 import splash
26
27 class DinoApp
28 super App
29
30 var cavemen_at_first_level = 6
31 var cavemen_incr = 4
32
33 var target_dt = 12000000
34
35 var game : nullable Game = null
36 var score = new Container[Int](0)
37 var imgs : nullable ImageSet = null
38 var splash : nullable SplashScreen = null
39
40 init do super
41
42 redef fun init_window
43 do
44 super
45
46 var display = display
47 assert display != null
48
49 # load only splash images
50 splash = new SplashScreen( self )
51 splash.draw( display, false )
52
53 # load other images
54 imgs = new ImageSet( self )
55
56 splash.draw( display, true )
57 end
58
59 redef fun frame_core( display )
60 do
61 var game = game
62 if game != null then
63 var clock = new Clock
64
65 var turn = game.do_turn
66 game.draw( display, imgs.as(not null), turn )
67
68 var dt = clock.lapse
69 if dt.sec == 0 and dt.nanosec < target_dt then
70 var sleep_t = target_dt - dt.nanosec
71 sys.nanosleep(0, sleep_t)
72 end
73 else
74 splash.draw( display, true )
75 end
76 end
77
78 redef fun input( input_event )
79 do
80 if input_event isa QuitEvent then # close window button
81 quit = true # orders system to quit
82 return true # this event has been handled
83
84 else if input_event isa PointerEvent then
85 if game == null then
86 # start from splash
87 game = new Game( cavemen_at_first_level, score )
88 else if game.over and game.ready_to_start_over then
89 # play next game
90 var next_nbr_caveman = game.nbr_wanted_cavemen
91 if game.won then
92 next_nbr_caveman += cavemen_incr
93 else
94 score = new Container[Int](0)
95 next_nbr_caveman = cavemen_at_first_level
96 end
97 game = new Game( next_nbr_caveman, score )
98 else
99 # normal play
100 game.dino.going_to = (new ScreenPos( input_event.x, input_event.y )).to_game( display.as(not null) )
101 end
102 return true
103
104 else if input_event isa KeyEvent then
105 return false
106 end
107
108 return false # unknown event, can be handled by something else
109 end
110 end
111
112 var app = new DinoApp
113 app.main_loop
114