projects: update some short descriptions
[nit.git] / examples / clock.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Example of a simple wall clock class with generalized getters and setters.
16 #
17 # A beefed-up module is available in clock_more
18 module clock
19
20 # A simple wall clock with 60 minutes and 12 hours.
21 class Clock
22 # total number of minutes from 0 to 719
23 var total_minutes: Int is noinit
24 # Note: only the read acces is public, the write access is private.
25
26 # number of minutes in the current hour (from 0 to 59)
27 fun minutes: Int do return self.total_minutes % 60
28
29 # set the number of minutes in the current hour.
30 # if m < 0 or m >= 60, the hour will be changed accordinlgy
31 fun minutes=(m: Int) do self.total_minutes = self.hours * 60 + m
32
33 # number of hours (from 0 to 11)
34 fun hours: Int do return self.total_minutes / 60
35
36 # set the number of hours
37 # the minutes will not be updated
38 fun hours=(h: Int) do self.total_minutes = h * 60 + minutes
39
40 # the position of the hour arrow in the [0..60[ interval
41 fun hour_pos: Int do return total_minutes / 12
42
43 # replace the arrow of hours (from 0 to 59).
44 # the hours and the minutes will be updated.
45 fun hour_pos=(h: Int) do self.total_minutes = h * 12
46
47 redef fun to_s do return "{hours}:{minutes}"
48
49 fun reset(hours, minutes: Int) is autoinit do self.total_minutes = hours*60 + minutes
50
51 redef fun ==(o)
52 do
53 # Note: o is a nullable Object, a type test is required
54 # Thanks to adaptive typing, there is no downcast
55 # i.e. the code is safe!
56 return o isa Clock and self.total_minutes == o.total_minutes
57 end
58 end
59
60 var c = new Clock(10,50)
61 print "It's {c} o'clock."
62
63 c.minutes += 22
64 print "Now it's {c} o'clock."
65
66 print "The short arrow in on the {c.hour_pos/5} and the long arrow in on the {c.minutes/5}."
67
68 c.hours -= 2
69 print "Now it's {c} o'clock."
70
71 var c2 = new Clock(9, 11)
72 print "It's {c2} on the second clock."
73 print "The two clocks are synchronized: {c == c2}."
74 c2.minutes += 1
75 print "It's now {c2} on the second clock."
76 print "The two clocks are synchronized: {c == c2}."