source: 2010/23/hniemi/BlockPusher/Blockpusher/Blockpusher/Blockpusher.cs @ 2641

Revision 2641, 9.1 KB checked in by hniemi, 11 years ago (diff)

Nyt pelitilanteen jatkaminen säilyttää myös liikutusten määrän ja kestää pelin sammuttamisen.

Line 
1using System;
2using System.Collections.Generic;
3using Jypeli;
4using Jypeli.Assets;
5using Jypeli.Controls;
6using Jypeli.Effects;
7using Jypeli.Widgets;
8using System.IO;
9
10/// <summary>
11/// Blockpusher-game
12///
13/// TODO: clones needed from levels
14/// </summary>
15public class Blockpusher : Game
16{
17    public static readonly int BlockSize = 20;
18
19    private readonly Color playerColor = Color.Blue;
20    private readonly Color satisfyColor = Color.Green;
21    private readonly Color unsatisfyColor = Color.Red;
22
23    private int currentLevelIndex = 0;
24    private BlockLevel currentLevel;
25    private List<BlockLevel> levels = new List<BlockLevel>();
26
27    private bool gameSaved = false;
28    private IList<string> savedLevel;
29
30    private List<String> testLevel = new List<string>(new String[]
31                                 {"xxxxxxxxx",
32                                  "x  x  xmx",
33                                  "xb p  xbx",
34                                  "xm x    x",
35                                  "x  xxxxxx",
36                                  "x      xx",
37                                  "xxxxxxxxx"});
38
39    /// <summary>
40    /// Starts the game
41    /// </summary>
42    public override void Begin()
43    {
44        gameSaved = SaveExist();
45        Menu();
46        LoadLevels();
47    }
48
49    /// <summary>
50    /// Checks if save exists
51    /// </summary>
52    /// <returns>true, if savefile exists</returns>
53    public bool SaveExist() 
54    {
55        return DataStorage.Exists("CurrentSave.txt");
56    }
57
58    /// <summary>
59    /// Starts new game
60    /// </summary>
61    public void NewGame(int levelIndex) 
62    {
63        ClearAll();
64        currentLevelIndex = levelIndex;
65        currentLevel = levels[levelIndex].Clone();
66        currentLevel.Victory += VictorySplash;
67        currentLevel.AddToGame();
68        SetControls();
69    }
70
71    /// <summary>
72    /// Loads levels from directory
73    /// </summary>
74    /// <param name="directory">Not in use</param>
75    public void LoadLevels(string directory=@"Data\Levels")
76    {
77        //TODO: Tee lukeminen valmiiksi
78
79        IEnumerable<string> folders = Directory.EnumerateDirectories(directory,"*");
80
81        foreach (string s in folders)
82        {
83            //Exludes hidden folder (with . before name)
84            if (s.Length != 0 && s[s.LastIndexOf('\\')+1] != '.')
85            {
86                //MessageDisplay.Add(s);
87                LoadLevels(s);
88            }
89        }
90
91        IEnumerable<string> files = Directory.EnumerateFiles(directory, "*");
92        foreach (string file in files)
93        {
94            BlockLevel level = new BlockLevel(this);
95            level.CreateField(ReadFile(file));
96
97            //level.Name = file.Substring(file.LastIndexOf('\\')+1, file.LastIndexOf('.') - file.LastIndexOf('\\')-1);
98            levels.Add(level);
99        }
100    }
101
102    #region Menu
103    /// <summary>
104    /// Creates startmenu for game
105    /// </summary>
106    public void Menu()
107    {
108        int labelHeighth = 50;
109
110        ClearAll();
111        IsMouseVisible = true;
112        PhoneBackButton.Listen(ConfirmExit, "Lopeta peli");
113        Keyboard.Listen(Key.Escape, ButtonState.Pressed, ConfirmExit, "Lopeta peli");
114
115        List<Tuple<string, Action>> labels = new List<Tuple<string, Action>>();
116        if (gameSaved) labels.Add(new Tuple<string, Action>("Continue", ContinueGame));
117        labels.Add(new Tuple<string, Action>("New game", delegate { LevelSelectionMenu(); }));
118        labels.Add(new Tuple<string, Action>("Quit?", ConfirmExit));
119
120        for (int i = 0; i < labels.Count; i++)
121        {
122            PushButton button = new PushButton(200, labelHeighth);
123            button.Text = labels[i].Item1;
124            button.Y = -(i * labelHeighth);
125            button.Clicked += labels[i].Item2;
126            Add(button);
127        }
128    }
129
130    /// <summary>
131    /// Asks if you want to go to main menu or continue playing
132    /// </summary>
133    public void ConfirmMenu()
134    {
135        ClearControls();
136        MultiSelectWindow w = new MultiSelectWindow("Back to menu?", new String[] { "Yes", "No!" });
137        w.AddItemHandler(0, delegate { MakeContinuable(); Menu(); });
138        w.AddItemHandler(1, delegate { SetControls(); w.Close(); });
139        Add(w);
140    }
141
142    /// <summary>
143    /// Shows "Victory"-label
144    /// </summary>
145    public void VictorySplash() 
146    {
147        Label victory = new Label("Victory!");
148        victory.Color = Color.DarkCyan;
149        victory.TextColor = Color.Fuchsia;
150
151        Add(victory);
152
153        Timer.SingleShot(1, Victory);
154    }
155
156    /// <summary>
157    /// Eventhandler for victory
158    /// </summary>
159    public void Victory()
160    {
161        IsMouseVisible = true;
162        MultiSelectWindow w = new MultiSelectWindow("Conratulations, you cleared level with "+ currentLevel.Moves +" moves! Do you want to:", new String[] { "Retry", "Next Level", "Main menu" });
163        w.AddItemHandler(0, delegate { NewGame(currentLevelIndex); });
164        w.AddItemHandler(1, delegate { NewGame((currentLevelIndex+1) % levels.Count); });
165        w.AddItemHandler(2, Menu);
166       
167        Add(w);
168    }
169
170    /// <summary>
171    /// Shows levelselection menu
172    /// </summary>
173    public void LevelSelectionMenu(int current = 0)
174    {
175        ClearAll();
176        int buttonheight = 50;
177
178        Label topic = new Label("Levels");
179
180        Widget buttons = new Widget(new HorizontalLayout());
181        Widget bottomButtons = new Widget(new HorizontalLayout());
182
183        PushButton previous = new PushButton(150, buttonheight, "Previous");
184        buttons.Add(previous);
185
186        PushButton next = new PushButton(150, buttonheight, "Next");
187        buttons.Add(next);
188
189        Label name = new Label(levels[current].Name);
190
191        PushButton back = new PushButton(150, buttonheight, "Back");
192        bottomButtons.Add(back);
193
194        PushButton play = new PushButton(150, buttonheight, "Select");
195        bottomButtons.Add(play);
196
197        topic.Top = Screen.Top;
198        buttons.Top = topic.Bottom;
199        name.Y = buttons.Bottom - (name.Height / 2);
200
201        bottomButtons.Bottom = Screen.Bottom;
202       
203        Add(topic);
204        Add(buttons);
205        Add(name);
206        Add(bottomButtons);
207
208        levels[current].AddToGame();
209
210        previous.Clicked += delegate { LevelSelectionMenu((current-1 + levels.Count) % levels.Count); };
211        next.Clicked += delegate { LevelSelectionMenu((current + 1) % levels.Count); };
212        play.Clicked += delegate { NewGame(current); };
213        back.Clicked += Menu;
214
215    }
216    #endregion
217
218    /// <summary>
219    /// Continues game from current save
220    /// </summary>
221    public void ContinueGame() 
222    {
223        ClearAll();
224        currentLevel = new BlockLevel(this);
225        currentLevel.Victory += VictorySplash;
226
227        List<string> lines = ReadFile("Data/CurrentSave.txt");
228        File.Delete("Data/CurrentSave.txt");
229        gameSaved = false;
230        //DataStorage.Delete("CurrentSave.txt");
231
232        currentLevel.Moves = int.Parse(lines[lines.Count - 1]);
233        lines.RemoveAt(lines.Count - 1);
234        currentLevelIndex = int.Parse(lines[lines.Count - 1]);
235        lines.RemoveAt(lines.Count - 1);
236
237        currentLevel.CreateField(lines);
238        currentLevel.AddToGame();
239        SetControls();
240    }
241
242    /// <summary>
243    /// Saves game
244    /// </summary>
245    public void MakeContinuable()
246    {
247        gameSaved = true;
248        savedLevel = currentLevel.CurrentState();
249        savedLevel.Add(currentLevelIndex + "");
250        savedLevel.Add(currentLevel.Moves + "");
251
252        File.WriteAllLines("Data/CurrentSave.txt", savedLevel);
253    }
254
255    /// <summary>
256    /// Reads lines from file
257    /// </summary>
258    /// <param name="file">Sourcefile</param>
259    public List<String> ReadFile(string file) 
260    {
261        List<String> lines = new List<string>();
262        try
263        {
264            using (StreamReader sr = new StreamReader(file))
265            {
266                String line;
267                while ((line = sr.ReadLine()) != null)
268                {
269                    lines.Add(line);
270                }
271            }
272        }
273        catch (Exception e)
274        {
275            return null;
276        }
277        return lines;
278    }
279
280    /// <summary>
281    /// Moves player in current level
282    /// </summary>
283    /// <param name="xMov">X-movement</param>
284    /// <param name="yMov">Y-movement</param>
285    public void MovePlayer(int xMov, int yMov)
286    {
287        currentLevel.MovePlayer(xMov, yMov);
288    }
289
290    /// <summary>
291    /// Sets controllisteners for keyboard
292    /// </summary>
293    public void SetControls() 
294    {
295        Keyboard.Listen(Key.Up, ButtonState.Pressed, MovePlayer, null, 0, -1);
296        Keyboard.Listen(Key.Down, ButtonState.Pressed, MovePlayer, null, 0, 1);
297        Keyboard.Listen(Key.Left, ButtonState.Pressed, MovePlayer, null, -1, 0);
298        Keyboard.Listen(Key.Right, ButtonState.Pressed, MovePlayer, null, 1, 0);
299
300        Keyboard.Listen(Key.Escape, ButtonState.Pressed, ConfirmMenu, "Lopeta peli");
301    }
302}
Note: See TracBrowser for help on using the repository browser.