~ubuntu-branches/ubuntu/lucid/gbrainy/lucid

« back to all changes in this revision

Viewing changes to src/Core/Main/GameSession.cs

  • Committer: Bazaar Package Importer
  • Author(s): Robert Ancell
  • Date: 2010-01-12 11:21:24 UTC
  • mfrom: (13.1.1 sid)
  • Revision ID: james.westby@ubuntu.com-20100112112124-o4ztomxa0xfh2ulj
Tags: 1.30-1ubuntu1
* debian/control:
  - Revert build-depends to lucid versions

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 * Copyright (C) 2007 Jordi Mas i Hernàndez <jmas@softcatala.org>
 
3
 *
 
4
 * This program is free software; you can redistribute it and/or
 
5
 * modify it under the terms of the GNU General Public License as
 
6
 * published by the Free Software Foundation; either version 2 of the
 
7
 * License, or (at your option) any later version.
 
8
 *
 
9
 * This program is distributed in the hope that it will be useful,
 
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 
12
 * General Public License for more details.
 
13
 *
 
14
 * You should have received a copy of the GNU General Public
 
15
 * License along with this program; if not, write to the
 
16
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 
17
 * Boston, MA 02111-1307, USA.
 
18
 */
 
19
 
 
20
using System;
 
21
using Mono.Unix;
 
22
using System.Timers;
 
23
using System.ComponentModel;
 
24
 
 
25
using gbrainy.Core.Views;
 
26
using gbrainy.Core.Libraries;
 
27
 
 
28
namespace gbrainy.Core.Main
 
29
{
 
30
        public class GameSession : IDrawable, IDrawRequest
 
31
        {
 
32
                [Flags]
 
33
                public enum Types
 
34
                {       
 
35
                        None                    = 0,
 
36
                        LogicPuzzles            = 2,
 
37
                        MemoryTrainers          = 4,
 
38
                        CalculationTrainers     = 8,
 
39
                        VerbalAnalogies         = 16,
 
40
                        Custom                  = 32,
 
41
                        TrainersOnly            = MemoryTrainers | CalculationTrainers,
 
42
                        AllGames                = MemoryTrainers | CalculationTrainers | LogicPuzzles
 
43
                }
 
44
 
 
45
                private enum ScoresType
 
46
                {
 
47
                        None = 0,
 
48
                        LogicPuzzles,
 
49
                        MemoryTrainers,
 
50
                        CalculationTrainers,
 
51
                        VerbalAnalogies,
 
52
                        Last                    
 
53
                }
 
54
 
 
55
                public enum SessionStatus
 
56
                {
 
57
                        NotPlaying,
 
58
                        Playing,
 
59
                        Answered,
 
60
                        Finished,
 
61
                }
 
62
 
 
63
                // Data kept for every game type in raw data (processed with a formula after)
 
64
                public class Statistics
 
65
                {
 
66
                        public int Played { get; set; }
 
67
                        public int Won { get; set; }
 
68
                        public int Scored { get; set; }
 
69
                }
 
70
 
 
71
                private TimeSpan game_time;
 
72
                private int games_played;
 
73
                private int games_won;
 
74
                private Game current_game;
 
75
                private GameManager game_manager;
 
76
                private System.Timers.Timer timer;
 
77
                private bool paused;
 
78
                private string current_time;
 
79
                private TimeSpan one_sec = TimeSpan.FromSeconds (1);
 
80
                private int total_score;
 
81
                private bool scored_game;
 
82
                private SessionStatus status;
 
83
                private ViewsControler controler;
 
84
                private ISynchronizeInvoke synchronize;
 
85
                private PlayerHistory history;
 
86
                private Statistics [] statistics;
 
87
                private int id;
 
88
 
 
89
                public event EventHandler DrawRequest;
 
90
                public event EventHandler <UpdateUIStateEventArgs> UpdateUIElement;
 
91
        
 
92
                public GameSession ()
 
93
                {
 
94
                        id = 0;
 
95
                        game_manager = new GameManager ();
 
96
                        game_time = TimeSpan.Zero;
 
97
 
 
98
                        timer = new System.Timers.Timer ();
 
99
                        timer.Elapsed += TimerUpdater;
 
100
                        timer.Interval = (1 * 1000); // 1 second
 
101
 
 
102
                        statistics = new Statistics [(int) ScoresType.Last];
 
103
 
 
104
                        for (int i = 0; i < (int) ScoresType.Last; i++)
 
105
                                statistics [i] = new Statistics ();
 
106
 
 
107
                        controler = new ViewsControler (this);
 
108
                        Status = SessionStatus.NotPlaying;
 
109
                        history = new PlayerHistory ();
 
110
                }
 
111
 
 
112
                public int ID {
 
113
                        get {return id;}
 
114
                }
 
115
 
 
116
                public PlayerHistory PlayerHistory { 
 
117
                        set { history = value; }
 
118
                        get { return history; }
 
119
                }
 
120
 
 
121
                public ISynchronizeInvoke SynchronizingObject { 
 
122
                        set { synchronize = value; }
 
123
                        get { return synchronize; }
 
124
                }
 
125
        
 
126
                public Types Type {
 
127
                        get {return game_manager.GameType; }
 
128
                        set {game_manager.GameType = value; }
 
129
                }
 
130
 
 
131
                public Game.Difficulty Difficulty {
 
132
                        get {return game_manager.Difficulty; }
 
133
                        set {game_manager.Difficulty = value; }
 
134
                }
 
135
        
 
136
                public TimeSpan GameTime {
 
137
                        get {return game_time; }
 
138
                        set {game_time = value; }
 
139
                }
 
140
 
 
141
                public int GamesPlayed {
 
142
                        get {return games_played; }
 
143
                        set { games_played = value;}
 
144
                }
 
145
                
 
146
                public int GamesWon {
 
147
                        get {return games_won; }
 
148
                        set {games_won = value; }
 
149
                }
 
150
 
 
151
                public bool Paused {
 
152
                        get {return paused; }
 
153
                        set {paused = value; }
 
154
                }
 
155
 
 
156
                public Game CurrentGame {
 
157
                        get {return current_game; }
 
158
                        set {
 
159
                                current_game = value; 
 
160
                                controler.Game = value;
 
161
                        }
 
162
                }
 
163
 
 
164
                public bool EnableTimer {
 
165
                        get {return timer.Enabled; }
 
166
                        set {timer.Enabled = value; }
 
167
                }
 
168
 
 
169
                public SessionStatus Status {
 
170
                        get {return status; }
 
171
                        set {
 
172
                                status = value;
 
173
                                controler.Status = value;
 
174
                        }
 
175
                }
 
176
 
 
177
                public GameManager GameManager {
 
178
                        get {return  game_manager;}
 
179
                }
 
180
 
 
181
                public int TotalScore {
 
182
                        get {return total_score;}
 
183
                }
 
184
 
 
185
                public int LogicScore {
 
186
                        get {
 
187
                                if (statistics [(int) ScoresType.LogicPuzzles].Played == 0)
 
188
                                        return -1;
 
189
 
 
190
                                return ScoreFormula (statistics [(int) ScoresType.LogicPuzzles]);
 
191
                        }
 
192
                }
 
193
 
 
194
                public int MemoryScore {
 
195
                        get {
 
196
                                if (statistics [(int) ScoresType.MemoryTrainers].Played == 0)
 
197
                                        return -1;
 
198
        
 
199
                                return ScoreFormula (statistics [(int) ScoresType.MemoryTrainers]);
 
200
                        }
 
201
                }
 
202
 
 
203
                public int MathScore {
 
204
                        get {
 
205
                                if (statistics [(int) ScoresType.CalculationTrainers].Played == 0)
 
206
                                        return -1;
 
207
 
 
208
                                return ScoreFormula (statistics [(int) ScoresType.CalculationTrainers]);
 
209
                        }
 
210
                }
 
211
 
 
212
                public int VerbalScore {
 
213
                        get {   
 
214
                                if (statistics [(int) ScoresType.VerbalAnalogies].Played == 0)
 
215
                                        return -1;
 
216
        
 
217
                                return ScoreFormula (statistics [(int) ScoresType.VerbalAnalogies]);
 
218
                        }
 
219
                }
 
220
 
 
221
                public string TimePlayed {
 
222
                        get {
 
223
                                return (current_time == null) ? TimeSpanToStr (TimeSpan.FromSeconds (0)) : current_time;
 
224
                        }
 
225
                }
 
226
 
 
227
                public string TimePerGame {
 
228
                        get {
 
229
                                TimeSpan average;
 
230
 
 
231
                                average = (games_played > 0) ? TimeSpan.FromSeconds (game_time.TotalSeconds / games_played) : game_time;
 
232
                                return TimeSpanToStr (average);
 
233
                        }
 
234
                }
 
235
 
 
236
                public string StatusText {
 
237
                        get {
 
238
                                if (Status == SessionStatus.NotPlaying)
 
239
                                        return string.Empty;
 
240
 
 
241
                                String text;
 
242
                                text = String.Format (Catalog.GetString ("Games played: {0} ({1}% score)"),games_played, total_score);
 
243
                                text += String.Format (Catalog.GetString (" - Time: {0}"), current_time);
 
244
 
 
245
                                if (CurrentGame != null)
 
246
                                        text += " " + String.Format (Catalog.GetString ("- Game: {0}"), CurrentGame.Name);
 
247
        
 
248
                                return text;
 
249
                        }
 
250
                }
 
251
        
 
252
                public void NewSession ()
 
253
                {
 
254
                        id++;
 
255
                        if (Status != SessionStatus.NotPlaying)
 
256
                                EndSession ();
 
257
 
 
258
                        current_time = TimeSpanToStr (game_time);
 
259
 
 
260
                        for (int i = 0; i < (int) ScoresType.Last; i++)
 
261
                                statistics [i] = new Statistics ();
 
262
 
 
263
                        total_score = 0;
 
264
                        games_played = 0;
 
265
                        games_won = 0;
 
266
                        game_time = TimeSpan.Zero;
 
267
                        timer.SynchronizingObject = SynchronizingObject;
 
268
                        EnableTimer = true;
 
269
                }
 
270
 
 
271
                public void EndSession ()
 
272
                {
 
273
                        history.SaveGameSession (this);
 
274
 
 
275
                        if (CurrentGame != null)
 
276
                                CurrentGame.Finish ();
 
277
 
 
278
                        EnableTimer = false;
 
279
                        timer.SynchronizingObject = null;
 
280
 
 
281
                        paused = false;
 
282
                        CurrentGame = null;
 
283
                        Status = SessionStatus.Finished;
 
284
                }
 
285
 
 
286
                public void NextGame ()
 
287
                {       
 
288
                        if (CurrentGame != null)
 
289
                                CurrentGame.Finish ();
 
290
 
 
291
                        games_played++;
 
292
                        CurrentGame = game_manager.GetPuzzle ();
 
293
                        CurrentGame.SynchronizingObject = SynchronizingObject;
 
294
                        CurrentGame.DrawRequest += GameDrawRequest;
 
295
                        CurrentGame.UpdateUIElement += GameUpdateUIElement;
 
296
 
 
297
                        CurrentGame.Initialize ();
 
298
 
 
299
                        CurrentGame.GameTime = TimeSpan.Zero;
 
300
                        scored_game = false;
 
301
                        Status = SessionStatus.Playing;
 
302
                }
 
303
 
 
304
                public void Pause ()
 
305
                {
 
306
                        EnableTimer = false;
 
307
                        paused = true;
 
308
                        current_time = Catalog.GetString ("Paused");
 
309
                }
 
310
 
 
311
                public void Resume ()
 
312
                {
 
313
                        EnableTimer = true;
 
314
                        paused = false;
 
315
                }
 
316
 
 
317
                /*
 
318
                        How the game session is scored
 
319
 
 
320
                        * Every game has a scoring algorithm that scores the player performance within the game.
 
321
                          This takes into account time used and tips (result is from 0 to 10)
 
322
                        * The results are added to the games and scores arrays where we store the results for
 
323
                          the different game types (verbal, logic, etc)
 
324
                        * We apply a ScoreFormula function that balances the total result with the number of
 
325
                          games played (is not the same 100% games won playing 2 than 10 games) and the difficulty
 
326
                        
 
327
                        The final result is a number from 0 to 100
 
328
                */
 
329
 
 
330
                public bool ScoreGame (string answer)
 
331
                {
 
332
                        int score;
 
333
                        bool won;
 
334
                        int components = 0;
 
335
 
 
336
                        if (CurrentGame == null || scored_game == true)
 
337
                                return false;
 
338
 
 
339
                        score = CurrentGame.Score (answer);
 
340
                        if (score > 0) {
 
341
                                GamesWon++;
 
342
                                won = true;
 
343
                        } else
 
344
                                won = false;
 
345
 
 
346
                        switch (CurrentGame.Type) {
 
347
                        case Game.Types.LogicPuzzle:
 
348
                                statistics [(int) ScoresType.LogicPuzzles].Scored += score;
 
349
                                statistics [(int) ScoresType.LogicPuzzles].Played++;
 
350
                                if (won) statistics [(int) ScoresType.LogicPuzzles].Won++;
 
351
                                break;
 
352
                        case Game.Types.MemoryTrainer:
 
353
                                statistics [(int) ScoresType.MemoryTrainers].Scored += score;
 
354
                                statistics [(int) ScoresType.MemoryTrainers].Played++;
 
355
                                if (won) statistics [(int) ScoresType.MemoryTrainers].Won++;
 
356
                                break;
 
357
                        case Game.Types.MathTrainer:
 
358
                                statistics [(int) ScoresType.CalculationTrainers].Scored += score;
 
359
                                statistics [(int) ScoresType.CalculationTrainers].Played++;
 
360
                                if (won) statistics [(int) ScoresType.CalculationTrainers].Won++;
 
361
                                break;
 
362
                        case Game.Types.VerbalAnalogy:
 
363
                                statistics [(int) ScoresType.VerbalAnalogies].Scored += score;
 
364
                                statistics [(int) ScoresType.VerbalAnalogies].Played++;
 
365
                                if (won) statistics [(int) ScoresType.VerbalAnalogies].Won++;
 
366
                                break;
 
367
                        default:
 
368
                                break;
 
369
                        }
 
370
 
 
371
                        total_score = 0;
 
372
 
 
373
                        // Updates total score taking only into account played game types
 
374
                        if (LogicScore >= 0) {
 
375
                                total_score += LogicScore;
 
376
                                components++;
 
377
                        }
 
378
 
 
379
                        if (MemoryScore >= 0) {
 
380
                                total_score += MemoryScore;
 
381
                                components++;
 
382
                        }
 
383
 
 
384
                        if (MathScore >= 0) {
 
385
                                total_score += MathScore;
 
386
                                components++;
 
387
                        }
 
388
 
 
389
                        if (VerbalScore >= 0) {
 
390
                                total_score += VerbalScore;
 
391
                                components++;
 
392
                        }
 
393
 
 
394
                        total_score = total_score / components;
 
395
 
 
396
                        scored_game = true;
 
397
                        return won;
 
398
                }
 
399
 
 
400
                //
 
401
                // Applies scoring formula to the session
 
402
                //
 
403
                int ScoreFormula (Statistics stats)
 
404
                {
 
405
                        int logbase;
 
406
                        double score, factor;
 
407
 
 
408
                        switch (Difficulty) {
 
409
                        case Game.Difficulty.Easy:
 
410
                                logbase = 10;
 
411
                                break;
 
412
                        case Game.Difficulty.Medium:
 
413
                                logbase = 20;
 
414
                                break;
 
415
                        case Game.Difficulty.Master:
 
416
                                logbase = 30;
 
417
                                break;
 
418
                        default:
 
419
                                throw new InvalidOperationException ("Invalid switch value");
 
420
                        }
 
421
 
 
422
                        // Simple percentage of games won vs played
 
423
                        score = stats.Scored > 0 ? stats.Scored / stats.Played * 10 : 0;
 
424
 
 
425
                        // Puts score of the game in prespective for the whole game
 
426
                        factor = Math.Log (stats.Won + 2, logbase); // +2 to avoid log 0
 
427
 
 
428
                        score = score * factor;
 
429
 
 
430
                        if (score > 100) score = 100;
 
431
 
 
432
                        return (int) score;
 
433
                }
 
434
 
 
435
                private void TimerUpdater (object source, ElapsedEventArgs e)
 
436
                {
 
437
                        lock (this) {
 
438
                                if (CurrentGame == null)
 
439
                                        return;
 
440
 
 
441
                                game_time = game_time.Add (one_sec);
 
442
                                CurrentGame.GameTime = CurrentGame.GameTime + one_sec;
 
443
                                current_time = TimeSpanToStr (game_time);
 
444
                        }
 
445
 
 
446
                        if (UpdateUIElement == null)
 
447
                                return;
 
448
 
 
449
                        UpdateUIElement (this, new UpdateUIStateEventArgs (UpdateUIStateEventArgs.EventUIType.Time, null));
 
450
                }
 
451
 
 
452
                static private string TimeSpanToStr (TimeSpan time)
 
453
                {
 
454
                        string fmt = time.ToString ();
 
455
                        int i = fmt.IndexOf ('.');
 
456
                        if (i > 0 && fmt.Length - i > 2)
 
457
                                fmt = fmt.Substring (0, i);
 
458
 
 
459
                        return fmt;
 
460
                }
 
461
 
 
462
                public void GameUpdateUIElement (object obj, UpdateUIStateEventArgs args)
 
463
                {
 
464
                        if (UpdateUIElement != null)
 
465
                                UpdateUIElement (this, args);
 
466
                }
 
467
 
 
468
                // A game has requested a redraw, scale the request to the object
 
469
                // subscribed to GameSession.GameDrawRequest
 
470
                public void GameDrawRequest (object o, EventArgs args)
 
471
                {
 
472
                        if (DrawRequest != null)
 
473
                                DrawRequest (this, EventArgs.Empty);
 
474
                }
 
475
 
 
476
                public virtual void Draw (CairoContextEx gr, int width, int height, bool rtl)
 
477
                {
 
478
                        controler.CurrentView.Draw (gr, width, height, rtl);
 
479
                }
 
480
 
 
481
        }
 
482
}