source: 2015/26/ohjaajat/HillbillyRun/HillbillyRun/HillbillyRun/HillbillyRun/HillbillyRun.cs @ 6219

Revision 6219, 21.1 KB checked in by sieerinn, 5 years ago (diff)

Alkutarinassa voi olla nyt useampi viesti.

Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using Jypeli;
5using Jypeli.Assets;
6using Jypeli.Controls;
7using Jypeli.Effects;
8using Jypeli.Widgets;
9
10/* Muistutuksia.
11 *
12 * Layerit
13 *   3 -
14 *   2 -
15 *   1 -
16 *   0 -
17 *  -1 - Näkyvä maanpinta.
18 *  -2 - Talot taustalla.
19 * 
20 * CollisionIgnoreGroupit
21 *  3 - Ryömivät ja liekit. //TODO: lisätä noidatkin tänne
22 *  2 - Kärry.
23 *
24*/
25
26
27//Luokka maajussien erikoisuuksille.
28class HillBilly : PlatformCharacter
29{
30    private IntMeter lifeCounter = new IntMeter(2, 0, 2);
31    public IntMeter Life
32    {
33        set { lifeCounter = value; }
34        get { return lifeCounter; }
35    }
36
37
38
39    public HillBilly(double leveys, double korkeus)
40        : base(leveys, korkeus)
41    {
42
43    }
44}
45
46/// <summary>
47/// An MMO where you go to war with mages in the lava kingdom.
48/// </summary>
49public class HillbillyRun : PhysicsGame
50{
51    private List<HillBilly> players = new List<HillBilly>();
52    private List<HillBilly> startingPlayers = new List<HillBilly>();
53
54    //private List<double> playerPositionsX = new List<double>();
55    //private List<double> playerPositionsY = new List<double>();
56
57    private const double PLAYER_SPEED = 180;
58    private const double TILE_SIZE = 70;
59
60    private double cameraTargetX; // Sijainti jossa kameran pitäisi olla.
61    private Vector cameraTarget;
62
63    private double cameraOffset = 400; // TODO: Tämän voisi ehkä laskea jostain (esim. ikkunan leveydestä kolmasosa tai jotain).
64    private double cameraSpeed = 2.0; // Kameran liikkumisnopeus.
65
66    # region Images
67    private Image[] groundImages = LoadImages("ground");    //Näitä ei tosin kaikkia kenties jaksa tehdä erilaisiksi levelistä riippuen
68    private Image[] groundTopImages = LoadImages("ground_top");
69    private Image[] foregroundDecorations = LoadImages("viljaa");
70    private Image[] blockImages = LoadImages("box2");
71
72    private Image[] houseImages = LoadImages("house", "houseburned");
73
74    private Image cartImage = LoadImage("cart");
75    private Image milkImage = LoadImage("tonkkaitem");
76
77    private Image cartWheelImage = LoadImage("cartwheel");
78
79    private Image smokeImage1 = LoadImage("smoke1");
80    private Image smokeImage2 = LoadImage("smoke2");
81
82    private Image forestBackgroundImage = LoadImage("forestbackground");
83
84    private Animation crawl;
85    private Animation blaze;
86
87    private Animation pitchforkAttack;
88    private Animation pitchforkWalk;
89    private Animation milkThrow;
90    private Animation milkWalk;
91    private Animation normalWalk;
92    private Animation playerIdle;
93    private Animation playerJump;
94    private Animation playerFall;
95    #endregion
96
97    private double leftCamLimit;
98    private double rightCamLimit;
99    private double bottomCamLimit;
100
101    private int levelNumber = 0;
102
103    public override void Begin()
104    {
105        IntroSequence();
106        //MainMenu();
107        //StartGame();
108    }
109
110    #region Intro
111    void IntroSequence()
112    {
113        Level.Background.Color = Color.Black;
114
115        Keyboard.Listen(Key.Escape, ButtonState.Pressed, SkipIntro, "Skip");
116
117        ShowMadeWithJypeli();
118
119        Timer.SingleShot(4.0, delegate // TODO get rid of fixed amount of seconds
120        {
121            ShowBackgroundStory();
122        });
123
124
125
126    }
127
128    void ShowMadeWithJypeli()
129    {
130        Image madewithImage = LoadImage("madewithjypeli");
131
132        double w = Window.Width / 4;
133        double h = w * (madewithImage.Height / (double)madewithImage.Width); // take aspect ratio from the picture
134
135        GameObject madewithjypeliObject = new GameObject(w, h);
136        madewithjypeliObject.Image = madewithImage;
137        Add(madewithjypeliObject);
138
139        // Tässä oli jotain epätehokasta feidailua tuolle Made with Jypeli -kuvalle. Ei tunnu päivittyvän joka framella tai on muuten vain tosi raskas...
140
141        //fadeTimer = new Timer();
142        //fadeTimer.Interval = 0.5;
143        //fadeTimer.Timeout += delegate
144        //{
145        //    madewithjypeliObject.Image = LerpImage(madewithjypeliObject.Image, Color.Black, 0.6);
146        //};
147        //fadeTimer.Start(5);
148
149        Timer.SingleShot(1.2, delegate
150        {
151            madewithjypeliObject.Destroy();
152        });
153
154    }
155
156    Image LerpImage(Image original, Color targetColor, double ratio)
157    {
158        Image newImage = new Image(original.Width, original.Height, Color.Transparent);
159        for (int y = 0; y < original.Height; y++)
160        {
161            for (int x = 0; x < original.Width; x++)
162            {
163                newImage[y, x] = Color.Lerp(original[y, x], targetColor, ratio);
164            }
165        }
166        return newImage;
167    }
168
169    void ShowBackgroundStory()
170    {
171        ShowStoryText(new Queue<string>(new[] { "Once upon a time...", "...blaa blaa blaa.", "Blaa." }));
172    }
173
174    void ShowStoryText(Queue<string> messages)
175    {
176        // Mennään alkuvalikkoon jos ei ole enää viestejä.
177        if (messages.Count == 0)
178        {
179            MainMenu();
180            return;
181        }
182
183        // Näytetään nykyinen viesti.
184        var storyLabel = new Label(messages.Dequeue()) { TextColor = Color.Black, TextScale = new Vector(3, 3) };
185        Add(storyLabel);
186
187        var textTimer = new Timer { Interval = 0.05 };
188        textTimer.Timeout += () => storyLabel.TextColor = Color.Lerp(storyLabel.TextColor, Color.White, 0.05);
189        textTimer.Start();
190
191        // Näytetään seuraava viesti muutaman sekunnin päästä.
192        Timer.SingleShot(4, delegate { storyLabel.Destroy(); ShowStoryText(messages); });
193    }
194
195    void SkipIntro()
196    {
197        ClearTimers();
198        ClearAll();
199        Keyboard.Clear();
200        MainMenu();
201    }
202
203    void MainMenu()
204    {
205        Level.Background.Color = Color.DarkBlue;
206
207        MultiSelectWindow mainmenu = new MultiSelectWindow("Main menu",
208"Start game", "Credits", "Exit");
209        mainmenu.AddItemHandler(0, StartGame);
210        mainmenu.AddItemHandler(1, ShowCredits);
211        mainmenu.AddItemHandler(2, Exit);
212        mainmenu.DefaultCancel = 2;
213        Add(mainmenu);
214    }
215
216    void ShowCredits()
217    {
218        MessageWindow win = new MessageWindow("This game was made in one week by\nSimo Rinne,\nEmma Heikura,\n and Jouni Potila\n using University of Jyväskylä's\n game programming library Jypeli");
219        win.Closed += delegate
220        {
221            ClearAll();
222            MainMenu();
223        };
224        Add(win);
225    }
226    #endregion
227
228    void StartGame()
229    {
230        Initializing();
231        CreateLevel();
232        ScreenSettings();
233
234        // Taustatestailua.
235        GameObject forestBackground = new GameObject(Level.Width, Level.Height);
236        forestBackground.Image = forestBackgroundImage;
237        forestBackground.TextureWrapSize = new Vector(5, 1);
238        Add(forestBackground, -3);
239        Layers[-3].RelativeTransition = new Vector(0.5, 1.0);
240        Level.Background.CreateGradient(Color.Black, Color.SkyBlue);
241
242        // Testailen tässä kärryn luomista.
243        //double size = 0.7;
244        //PhysicsObject cart = new PhysicsObject(400 * size, 80 * size);
245        //cart.X = -1600;
246        //cart.Y = 200;
247        //cart.Image = cartImage;
248        //cart.CollisionIgnoreGroup = 2;
249        //Add(cart);
250        //PhysicsObject cartWheel = new PhysicsObject(160 * size, 160 * size, Shape.Circle);
251        //cartWheel.Image = cartWheelImage;
252        //cartWheel.Position = cart.Position + new Vector(-110, -30) * size;
253        //cartWheel.CollisionIgnoreGroup = 2;
254        //Add(cartWheel);
255        //AxleJoint joint = new AxleJoint(cart, cartWheel);
256        //Add(joint);
257    }
258
259    void Initializing()
260    {
261        crawl = LoadAnimation("crawl");
262        blaze = LoadAnimation("flame");
263        pitchforkAttack = LoadAnimation("attack");
264        pitchforkWalk = LoadAnimation("hanko");
265        milkThrow = LoadAnimation("heitto");
266        milkWalk = LoadAnimation("tonkka");
267        normalWalk = LoadAnimation("pwalk");
268        playerIdle = LoadAnimation("idle");
269        playerJump = LoadAnimation("jump");
270        playerFall = LoadAnimation("fall");
271    }
272
273    void ScreenSettings()
274    {
275        Window.Width = 1800;
276        Window.Height = 900;
277
278        leftCamLimit = Level.Left + Window.Width / 2.0;
279        rightCamLimit = Level.Right - Window.Width / 2.0;
280        bottomCamLimit = Level.Bottom + Window.Height / 2.0;
281
282        //Camera.X = cameraTargetX = players[0].X;
283        //Camera.ZoomToLevel();
284        Camera.X = cameraTargetX = leftCamLimit;
285
286        Timer cameraTimer = new Timer();
287        cameraTimer.Interval = 1 / 30.0;
288        cameraTimer.Timeout += UpdateCamera;
289        cameraTimer.Start();
290    }
291
292    #region LevelCreation
293    void CreateLevel()
294    {
295        Gravity = new Vector(0, -1000);
296
297        ColorTileMap level = ColorTileMap.FromLevelAsset("level" + levelNumber);
298        level.SetTileMethod(Color.Black, CreateGroundTop);
299        level.SetTileMethod(Color.Brown, CreateGround);
300
301        level.SetTileMethod(Color.Cyan, CreateHouse);
302        level.SetTileMethod(Color.PaintDotNetBlue, CreateBurnedHouse);
303
304        level.SetTileMethod(Color.Gold, CreatePlayer);
305        level.SetTileMethod(Color.Harlequin, CreateCart);
306        level.SetTileMethod(Color.White, CreateBlockObject);
307        level.SetTileMethod(Color.DarkGray, CreateMilk);
308        level.SetTileMethod(Color.Gray, CreateCrawly);
309        level.SetTileMethod(Color.Red, CreateDummy, Color.Red);    //TODO: CreateWitch
310        level.SetTileMethod(Color.Rose, CreateFlame);
311        //level.SetTileMethod(Color.Azure, CreateDummy, Color.Azure);   //TODO: CreateSmoke
312        //level.SetTileMethod(Color.Orange, CreateDummy, Color.Orange); //TODO: CreateTombstone
313        level.Optimize(Color.Black, Color.Brown);
314        level.Execute(TILE_SIZE, TILE_SIZE);
315
316
317        //TileMap level = TileMap.FromLevelAsset("level" + levelNumber);
318        //level.SetTileMethod('P', CreatePlayer);
319        //level.SetTileMethod('#', CreateGroundTop);
320        //level.SetTileMethod('%', CreateGround);
321        //level.Optimize('#', '%');
322        //level.Execute(TILE_SIZE, TILE_SIZE);
323        //Level.CreateBorders(true);
324
325        SetControls();
326    }
327
328    void CreateFlame(Vector position, double width, double height)
329    {
330        PhysicsObject flame = PhysicsObject.CreateStaticObject(width, height * 2);
331        //flame.Image = flameImage;
332        flame.Color = Color.Red;
333        double hieman = height * 0.3;
334        flame.Position = position - new Vector(0, hieman);
335        flame.CollisionIgnoreGroup = 3;
336        flame.Tag = "burn";
337        flame.Animation = new Animation(blaze) { FPS = RandomGen.NextInt(20, 26) };
338        flame.Animation.Step(RandomGen.NextInt(0, 12));
339        flame.Animation.Resume();
340        Add(flame);
341
342        Smoke savu = new Smoke();
343        savu.ParticleImage = smokeImage1;
344        savu.OuterParticleImage = smokeImage2;
345        savu.MaxLifetime = 1.0;
346        savu.MaxScale = 200;
347        savu.MinScale = 10;
348        savu.Position = flame.Position;
349        Wind = new Vector(-10, 0);
350        Add(savu);
351    }
352
353    void CreateBlockObject(Vector position, double width, double height)
354    {
355        // Säädin vähän tätä jotta laatikko näkyy hyvin. Pitää ehkä tehdä laatikolle ihan oma metodi.
356
357        PhysicsObject block = PhysicsObject.CreateStaticObject(width, height);
358        block.IsVisible = false;
359        //block.Image = blockImages[levelNumber];
360        block.Position = position;
361        block.Y -= height / 2.0;
362        Add(block, 1);
363
364        GameObject visibleBlock = new GameObject(width, height * 1.5);
365        visibleBlock.Position = position;
366        visibleBlock.Image = blockImages[levelNumber];
367        visibleBlock.Y -= height / 2.0;
368        Add(visibleBlock, -1);
369    }
370
371    void CreateMilk(Vector position, double width, double height)
372    {
373        double size = 30;
374        double ratio = milkImage.Height / milkImage.Width;
375        PhysicsObject milk = new PhysicsObject(size, size * ratio);
376        milk.Image = milkImage;
377        milk.Position = position;
378        milk.Tag = "milk";
379        Add(milk);
380    }
381
382    void CreateCrawly(Vector position, double width, double height)
383    {
384        PlatformCharacter crawly = new PlatformCharacter(width * 2, height);
385        crawly.Position = position;
386        crawly.Color = Color.Gray;
387        crawly.Animation = crawl;
388        crawly.Animation.Start();
389        crawly.Tag = "burn";
390        crawly.CollisionIgnoreGroup = 3;
391        Add(crawly);
392
393        PlatformWandererBrain brain = new PlatformWandererBrain();
394        brain.Speed = 20;
395        brain.FallsOffPlatforms = true;
396
397        crawly.Brain = brain;
398    }
399
400    void CreateHouse(Vector position, double width, double height)
401    {
402        // Näkyvä talo
403        GameObject house = new GameObject(width * 10, height * 8);
404        house.Image = houseImages[0];
405        house.Position = position - new Vector(0, height * 2.5);
406        Add(house, -2);
407
408        //Seisottava tasanne
409        PhysicsObject platform = PhysicsObject.CreateStaticObject(house.Width - (TILE_SIZE * 3.25), 1);     //Tätä kohtaa on nyt vähän hakemalla haettu.
410        platform.IsVisible = false;
411        platform.Position = new Vector(house.X + (TILE_SIZE * 0.5), house.Top);
412        Add(platform);
413    }
414
415    void CreateBurnedHouse(Vector position, double width, double height)
416    {
417        GameObject house = new GameObject(width * 10, height * 8);
418        house.Image = houseImages[1];
419        house.Position = position - new Vector(0, height * 2.5);
420        Add(house, -2);
421
422        PhysicsObject platform = PhysicsObject.CreateStaticObject(house.Width * 0.25, 1);
423        platform.IsVisible = false;
424        platform.Position = new Vector(house.X + platform.Width * 0.5, house.Top);
425        Add(platform);
426    }
427
428    private void CreateCart(Vector position, double width, double height)
429    {
430        double size = 0.7;
431        PhysicsObject cart = new PhysicsObject(400 * size, 80 * size);
432        cart.Position = position;
433        cart.Image = cartImage;
434        cart.CollisionIgnoreGroup = 2;
435        Add(cart);
436        PhysicsObject cartWheel = new PhysicsObject(160 * size, 160 * size, Shape.Circle);
437        cartWheel.Image = cartWheelImage;
438        cartWheel.Position = cart.Position + new Vector(-110, -30) * size;
439        cartWheel.CollisionIgnoreGroup = 2;
440        Add(cartWheel);
441        AxleJoint joint = new AxleJoint(cart, cartWheel);
442        Add(joint);
443    }
444
445
446    private void CreateDummy(Vector position, double width, double height, Color color)
447    {
448        PhysicsObject dummy = PhysicsObject.CreateStaticObject(width, height);
449        dummy.Position = position;
450        dummy.Color = color;
451        Add(dummy);
452    }
453
454    void CreatePlayer(Vector position, double width, double height)
455    {
456        HillBilly player = new HillBilly(width, height * 2);
457        player.Shape = Shape.Rectangle;
458        player.Position = position + new Vector(0, height * 0.5);
459        player.Color = Color.White;
460        player.AnimWalk = new Animation(normalWalk);
461        player.AnimIdle = new Animation(playerIdle);
462        player.AnimJump = new Animation(playerJump);
463        player.AnimFall = new Animation(playerFall);
464        player.AnimFall.StopOnLastFrame = true;
465        players.Add(player);
466        startingPlayers.Add(player);
467        Add(player);
468        AddCollisionHandler(player, "burn", delegate(PhysicsObject p, PhysicsObject t)
469        {
470            HillBilly billy = p as HillBilly;
471            billy.Life.Value--;
472
473        });
474
475        player.Life.LowerLimit += delegate
476        {
477            if (players.Count < 2)
478            {
479                Loss();
480            }
481            players.Remove(player); player.Destroy();
482        };
483
484        AddCollisionHandler(player, "milk", CollectMilk);
485    }
486
487    void CreateGroundTop(Vector position, double width, double height)
488    {
489        // Puolet pienempi näkymätön palikka alla johon törmää.
490        PhysicsObject ground = PhysicsObject.CreateStaticObject(width, height / 2.0);
491        ground.IsVisible = false;
492        ground.Position = position - new Vector(0.0, TILE_SIZE / 4.0);
493        Add(ground);
494
495        // Maanpinnan näkyvä osa.
496        GameObject visibleGround = new GameObject(width, height);
497        visibleGround.Image = groundImages[levelNumber];
498        visibleGround.Position = position;
499        visibleGround.TextureWrapSize = new Vector(width / TILE_SIZE, height / TILE_SIZE);
500        Add(visibleGround, -1);
501
502        int probability = RandomGen.NextInt(100);
503        bool wheat = probability < 20;
504
505        if (wheat)
506        {
507            GameObject wheatBlock = new GameObject(width * 1.5, height * 2);
508            wheatBlock.Image = foregroundDecorations[0];
509            wheatBlock.X = visibleGround.X;
510            wheatBlock.Bottom = visibleGround.Bottom;
511            wheatBlock.TextureWrapSize = new Vector(width / TILE_SIZE, height / TILE_SIZE);
512            Add(wheatBlock, 2);
513        }
514    }
515
516    void CreateGround(Vector position, double width, double height)
517    {
518        PhysicsObject ground = PhysicsObject.CreateStaticObject(width, height);
519        ground.Image = groundTopImages[levelNumber];
520        ground.Position = position;
521        ground.TextureWrapSize = new Vector(width / TILE_SIZE, height / TILE_SIZE);
522        Add(ground);
523    }
524    #endregion
525
526    void SetControls()
527    {
528        Keyboard.Listen(Key.A, ButtonState.Down, delegate { startingPlayers[0].Walk(-PLAYER_SPEED); }, "Player 1 moves left");
529        Keyboard.Listen(Key.D, ButtonState.Down, delegate { startingPlayers[0].Walk(PLAYER_SPEED); }, "Player 1 moves right");
530        Keyboard.Listen(Key.W, ButtonState.Down, delegate { startingPlayers[0].Jump(1000); }, "Player 1 jumps");
531
532        Keyboard.Listen(Key.Left, ButtonState.Down, delegate { startingPlayers[1].Walk(-PLAYER_SPEED); }, "Player 2 moves left");
533        Keyboard.Listen(Key.Right, ButtonState.Down, delegate { startingPlayers[1].Walk(PLAYER_SPEED); }, "Player 2 moves right");
534        Keyboard.Listen(Key.Up, ButtonState.Down, delegate { startingPlayers[1].Jump(1000); }, "Player 2 jumps");
535
536        Keyboard.Listen(Key.F1, ButtonState.Pressed, ShowControlHelp, "Show help");
537        Keyboard.Listen(Key.Escape, ButtonState.Pressed, ConfirmExit, "Exit game");
538    }
539
540    void Loss()
541    {
542        //TODO: Sumthin' flashy for our fallen friends.
543        Exit();
544    }
545
546    void CollectMilk(PhysicsObject player, PhysicsObject milk)
547    {
548        HillBilly billy = player as HillBilly;
549        if (billy == null)
550            return;
551
552        milk.Destroy();
553        billy.AnimWalk = new Animation(milkWalk);
554        billy.AnimIdle = new Animation(milkWalk.CurrentFrame);
555    }
556
557    #region Camera
558    void UpdateCamera()
559    {
560        double minY = players.Min(p => p.Y);
561        double maxY = players.Max(p => p.Y);
562        double minX = players.Min(p => p.X) + cameraOffset;
563
564        Vector minPosition = new Vector(Math.Max(minX, cameraTargetX), minY);
565        Vector maxPosition = new Vector(minX, maxY);
566
567        cameraTarget = (minPosition + maxPosition) * 0.5;
568        cameraTarget.X = Math.Max(cameraTargetX, minX);     //Lellllll.
569
570        //cameraTarget.Y = Math.Max(cameraTarget.X, Level.Bottom + Window.Height/2.0);
571
572        cameraTargetX = Math.Max(cameraTargetX, minX);
573
574        cameraTarget.X = Math.Min(cameraTargetX, rightCamLimit);
575        cameraTarget.Y = Math.Max(cameraTarget.Y, bottomCamLimit);
576
577        double windowMax = Camera.ScreenToWorld(new Vector(Window.Width / 2.0, 0)).X;
578        double windowMin = Camera.ScreenToWorld(new Vector(-Window.Width / 2.0, 0)).X;
579        foreach (var player in players)
580        {
581            player.Left = Math.Max(player.Left, windowMin);
582            player.Right = Math.Min(player.Right, windowMax);
583        }
584    }
585
586    protected override void Update(Time time)
587    {
588        Camera.Position += (cameraTarget - Camera.Position) * time.SinceLastUpdate.TotalSeconds * cameraSpeed;
589        //Camera.X += (cameraTargetX - Camera.X) * time.SinceLastUpdate.TotalSeconds * cameraSpeed;
590
591
592        base.Update(time);
593    }
594
595    /// <summary>
596    /// Yritän leikkiä kameralla. Vielä varmaan hetken pidempään.
597    /// </summary>
598    /// <param name="gameTime"></param>
599    /*
600    protected override void Update(Microsoft.Xna.Framework.GameTime gameTime)
601    {
602        foreach(HillBilly player in players)
603        {
604            playerPositionsX.Add(player.Position.X);
605            playerPositionsY.Add(player.Position.Y);
606        }
607
608        double maxX = playerPositionsX.Max();
609        double maxY = playerPositionsY.Max();
610        double minX = playerPositionsX.Min();
611        double minY = playerPositionsY.Min();
612
613        Vector minPosition = new Vector(minX, minY);
614        Vector maxPosition = new Vector(maxX, maxY);
615
616        Camera.Position = (minPosition + maxPosition) * 0.5;
617
618        playerPositionsX.Clear();
619        playerPositionsY.Clear();
620
621        base.Update(gameTime);
622    }
623     */
624    #endregion
625}
Note: See TracBrowser for help on using the repository browser.