23314f85e1a617299c77b1d53dfdef896b68498c
[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 is
19 app_version(0, 2, git_revision)
20 app_name("mnit Dino")
21 end
22
23 import mnit
24 import realtime
25
26 import graphism
27 import fancy_dino
28 import splash
29
30 redef class App
31 var cavemen_at_first_level = 6
32 var cavemen_incr = 4
33
34 var target_dt = 12000000
35
36 var game : nullable Game = null
37 var score = new Container[Int](0)
38 var imgs : nullable ImageSet = null
39 var splash : nullable SplashScreen = null
40
41 redef fun window_created
42 do
43 super
44
45 var display = display
46 assert display != null
47
48 # load only splash images
49 splash = new SplashScreen( self )
50 splash.draw( display, false )
51
52 # load other images
53 imgs = new ImageSet( self )
54
55 splash.draw( display, true )
56 end
57
58 redef fun frame_core( display )
59 do
60 var game = game
61 if game != null then
62 var clock = new Clock
63
64 var turn = game.do_turn
65 game.draw( display, imgs.as(not null), turn )
66
67 var dt = clock.lapse
68 if dt.sec == 0 and dt.nanosec < target_dt then
69 var sleep_t = target_dt - dt.nanosec
70 sys.nanosleep(0, sleep_t)
71 end
72 else
73 splash.draw( display, true )
74 end
75 end
76
77 redef fun input( input_event )
78 do
79 if input_event isa QuitEvent then # close window button
80 quit = true # orders system to quit
81 return true # this event has been handled
82
83 else if input_event isa PointerEvent then
84 if game == null then
85 # start from splash
86 game = new Game( cavemen_at_first_level, score )
87 else if game.over and game.ready_to_start_over then
88 # play next game
89 var next_nbr_caveman = game.nbr_wanted_cavemen
90 if game.won then
91 next_nbr_caveman += cavemen_incr
92 else
93 score = new Container[Int](0)
94 next_nbr_caveman = cavemen_at_first_level
95 end
96 game = new Game( next_nbr_caveman, score )
97 else
98 # normal play
99 game.dino.going_to = (new ScreenPos( input_event.x, input_event.y )).to_game( display.as(not null) )
100 end
101 return true
102
103 else if input_event isa KeyEvent then
104 return false
105 end
106
107 return false # unknown event, can be handled by something else
108 end
109 end