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

Revision 6278, 21.1 KB checked in by empaheik, 8 years ago (diff)

Ei pitäisi enää kaatua kuolemassa (laitan sormet ristiin).

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
235    void Initializing()
236    {
237        crawl = LoadAnimation("crawl");
238        blaze = LoadAnimation("flame");
239        pitchforkAttack = LoadAnimation("attack");
240        pitchforkWalk = LoadAnimation("hanko");
241        milkThrow = LoadAnimation("heitto");
242        milkWalk = LoadAnimation("tonkka");
243        normalWalk = LoadAnimation("pwalk");
244        playerIdle = LoadAnimation("idle");
245        playerJump = LoadAnimation("jump");
246        playerFall = LoadAnimation("fall");
247    }
248
249    void ScreenSettings()
250    {
251        Window.Width = 1800;
252        Window.Height = 900;
253
254        leftCamLimit = Level.Left + Window.Width / 2.0;
255        rightCamLimit = Level.Right - Window.Width / 2.0;
256        bottomCamLimit = Level.Bottom + Window.Height / 2.0;
257
258        Camera.X = cameraTargetX = leftCamLimit;
259
260        Timer cameraTimer = new Timer();
261        cameraTimer.Interval = 1 / 30.0;
262        cameraTimer.Timeout += UpdateCamera;
263        cameraTimer.Start();
264    }
265
266    #region LevelCreation
267    void CreateLevel()
268    {
269        //Background
270        GameObject forestBackground = new GameObject(Level.Width, Level.Height);
271        forestBackground.Image = forestBackgroundImage;
272        forestBackground.TextureWrapSize = new Vector(5, 1);
273        Add(forestBackground, -3);
274        Layers[-3].RelativeTransition = new Vector(0.5, 1.0);
275        Level.Background.CreateGradient(Color.Black, Color.SkyBlue);
276
277        Gravity = new Vector(0, -1000);
278
279        //Tilemap
280        ColorTileMap level = ColorTileMap.FromLevelAsset("level" + levelNumber);
281        level.SetTileMethod(Color.Black, CreateGroundTop);
282        level.SetTileMethod(Color.Brown, CreateGround);
283
284        level.SetTileMethod(Color.Cyan, CreateHouse);
285        level.SetTileMethod(Color.PaintDotNetBlue, CreateBurnedHouse);
286
287        level.SetTileMethod(Color.Gold, CreatePlayer);
288        level.SetTileMethod(Color.Harlequin, CreateCart);
289        level.SetTileMethod(Color.White, CreateBlockObject);
290        level.SetTileMethod(Color.DarkGray, CreateMilk);
291        level.SetTileMethod(Color.Gray, CreateCrawly);
292        level.SetTileMethod(Color.Red, CreateDummy, Color.Red);    //TODO: CreateWitch
293        level.SetTileMethod(Color.Rose, CreateFlame);
294        //level.SetTileMethod(Color.Azure, CreateDummy, Color.Azure);   //TODO: CreateSmoke
295        //level.SetTileMethod(Color.Orange, CreateDummy, Color.Orange); //TODO: CreateTombstone
296        level.Optimize(Color.Black, Color.Brown);
297        level.Execute(TILE_SIZE, TILE_SIZE);
298
299        SetControls();
300    }
301
302    void CreateFlame(Vector position, double width, double height)
303    {
304        PhysicsObject flame = PhysicsObject.CreateStaticObject(width, height * 2);
305        //flame.Image = flameImage;
306        flame.Color = Color.Red;
307        double hieman = height * 0.3;
308        flame.Position = position - new Vector(0, hieman);
309        flame.CollisionIgnoreGroup = 3;
310        flame.Tag = "burn";
311        flame.Animation = new Animation(blaze) { FPS = RandomGen.NextInt(20, 26) };
312        flame.Animation.Step(RandomGen.NextInt(0, 12));
313        flame.Animation.Resume();
314        Add(flame);
315
316        Smoke savu = new Smoke();
317        savu.ParticleImage = smokeImage1;
318        savu.OuterParticleImage = smokeImage2;
319        savu.MaxLifetime = 1.0;
320        savu.MaxScale = 200;
321        savu.MinScale = 10;
322        savu.Position = flame.Position;
323        Wind = new Vector(-10, 0);
324        Add(savu);
325    }
326
327    void CreateBlockObject(Vector position, double width, double height)
328    {
329        // Säädin vähän tätä jotta laatikko näkyy hyvin. Pitää ehkä tehdä laatikolle ihan oma metodi.
330        PhysicsObject block = PhysicsObject.CreateStaticObject(width, height);
331        block.IsVisible = false;
332        //block.Image = blockImages[levelNumber];
333        block.Position = position;
334        block.Y -= height / 2.0;
335        Add(block, 1);
336
337        GameObject visibleBlock = new GameObject(width, height * 1.5);
338        visibleBlock.Position = position;
339        visibleBlock.Image = blockImages[levelNumber];
340        visibleBlock.Y -= height / 2.0;
341        Add(visibleBlock, -1);
342    }
343
344    void CreateMilk(Vector position, double width, double height)
345    {
346        double size = 30;
347        double ratio = milkImage.Height / milkImage.Width;
348        PhysicsObject milk = new PhysicsObject(size, size * ratio);
349        milk.Image = milkImage;
350        milk.Position = position;
351        milk.Tag = "milk";
352        Add(milk);
353    }
354
355    void CreateCrawly(Vector position, double width, double height)
356    {
357        PlatformCharacter crawly = new PlatformCharacter(width * 2, height * 0.6);
358        crawly.Position = position;
359        crawly.Color = Color.Gray;
360        crawly.Animation = new Animation(crawl);
361        crawly.Animation.FPS = RandomGen.NextInt(18, 24);
362        crawly.Animation.Step(RandomGen.NextInt(0, 16));
363        crawly.Animation.Resume();
364        crawly.Tag = "burn";
365        crawly.CollisionIgnoreGroup = 3;
366        Add(crawly, 1);
367
368        GameObject flame = new GameObject(width * 1.4, height * 2);
369        flame.Animation = new Animation(blaze) { FPS = RandomGen.NextInt(20, 26) };
370        flame.Animation.Step(RandomGen.NextInt(0, 12));
371        flame.Animation.Resume();
372        Add(flame);
373
374        // Pakko liikutella näin koska lapsioliona liekki näkyisi ryömijän päällä.
375        Timer flameMover = new Timer { Interval = 0.05 };
376        flameMover.Timeout += delegate
377        {
378            double hieman = height * 0.75;
379            flame.Position = crawly.Position + new Vector(0, hieman);
380        };
381        flameMover.Start();
382
383        PlatformWandererBrain brain = new PlatformWandererBrain();
384        brain.Speed = 20;
385        brain.FallsOffPlatforms = true;
386
387        crawly.Brain = brain;
388
389        // Sammuu törmätessään maitoon.
390        AddCollisionHandler(crawly, "milkparticle", delegate(PhysicsObject c, PhysicsObject particle)
391        {
392            particle.Destroy();
393            crawly.Brain = null;
394            crawly.Tag = "";
395            flame.Destroy();
396        });
397    }
398
399    void CreateHouse(Vector position, double width, double height)
400    {
401        // Näkyvä talo
402        GameObject house = new GameObject(width * 10, height * 8);
403        house.Image = houseImages[0];
404        house.Position = position - new Vector(0, height * 2.5);
405        Add(house, -2);
406
407        //Seisottava tasanne
408        PhysicsObject platform = PhysicsObject.CreateStaticObject(house.Width - (TILE_SIZE * 3.25), 1);     //Tätä kohtaa on nyt vähän hakemalla haettu.
409        platform.IsVisible = false;
410        platform.Position = new Vector(house.X + (TILE_SIZE * 0.5), house.Top);
411        Add(platform);
412    }
413
414    void CreateBurnedHouse(Vector position, double width, double height)
415    {
416        GameObject house = new GameObject(width * 10, height * 8);
417        house.Image = houseImages[1];
418        house.Position = position - new Vector(0, height * 2.5);
419        Add(house, -2);
420
421        PhysicsObject platform = PhysicsObject.CreateStaticObject(house.Width * 0.25, 1);
422        platform.IsVisible = false;
423        platform.Position = new Vector(house.X + platform.Width * 0.5, house.Top);
424        Add(platform);
425    }
426
427    private void CreateCart(Vector position, double width, double height)
428    {
429        double size = 0.7;
430        PhysicsObject cart = new PhysicsObject(400 * size, 80 * size);
431        cart.Position = position;
432        cart.Image = cartImage;
433        cart.CollisionIgnoreGroup = 2;
434        Add(cart);
435        PhysicsObject cartWheel = new PhysicsObject(160 * size, 160 * size, Shape.Circle);
436        cartWheel.Image = cartWheelImage;
437        cartWheel.Position = cart.Position + new Vector(-110, -30) * size;
438        cartWheel.CollisionIgnoreGroup = 2;
439        Add(cartWheel);
440        AxleJoint joint = new AxleJoint(cart, cartWheel);
441        Add(joint);
442    }
443
444    private void CreateDummy(Vector position, double width, double height, Color color)
445    {
446        PhysicsObject dummy = PhysicsObject.CreateStaticObject(width, height);
447        dummy.Position = position;
448        dummy.Color = color;
449        Add(dummy);
450    }
451
452    void CreatePlayer(Vector position, double width, double height)
453    {
454        HillBilly player = new HillBilly(width, height * 2);
455        player.Shape = Shape.Rectangle;
456        player.Position = position + new Vector(0, height * 0.5);
457        player.Color = Color.White;
458        player.AnimWalk = new Animation(normalWalk);
459        player.AnimIdle = new Animation(playerIdle);
460        player.AnimJump = new Animation(playerJump);
461        player.AnimFall = new Animation(playerFall);
462        player.AnimFall.StopOnLastFrame = true;
463        players.Add(player);
464        startingPlayers.Add(player);
465        Add(player);
466        AddCollisionHandler(player, "burn", delegate(PhysicsObject p, PhysicsObject t)
467        {
468            HillBilly billy = p as HillBilly;
469            billy.Life.Value--;
470
471        });
472
473        player.Life.LowerLimit += delegate
474        {
475            if (players.Count < 2)
476            {
477                Loss();
478            }
479            else { players.Remove(player); player.Destroy(); }
480        };
481
482        AddCollisionHandler(player, "milk", CollectMilk);
483    }
484
485    void CreateGroundTop(Vector position, double width, double height)
486    {
487        // Puolet pienempi näkymätön palikka alla johon törmää.
488        PhysicsObject ground = PhysicsObject.CreateStaticObject(width, height / 2.0);
489        ground.IsVisible = false;
490        ground.Position = position - new Vector(0.0, TILE_SIZE / 4.0);
491        Add(ground);
492
493        // Maanpinnan näkyvä osa.
494        GameObject visibleGround = new GameObject(width, height);
495        visibleGround.Image = groundImages[levelNumber];
496        visibleGround.Position = position;
497        visibleGround.TextureWrapSize = new Vector(width / TILE_SIZE, height / TILE_SIZE);
498        Add(visibleGround, -1);
499
500        int probability = RandomGen.NextInt(100);
501        bool wheat = probability < 20;
502
503        if (wheat)
504        {
505            GameObject wheatBlock = new GameObject(width * 1.5, height * 2);
506            wheatBlock.Image = foregroundDecorations[0];
507            wheatBlock.X = visibleGround.X;
508            wheatBlock.Bottom = visibleGround.Bottom;
509            wheatBlock.TextureWrapSize = new Vector(width / TILE_SIZE, height / TILE_SIZE);
510            Add(wheatBlock, 2);
511        }
512    }
513
514    void CreateGround(Vector position, double width, double height)
515    {
516        PhysicsObject ground = PhysicsObject.CreateStaticObject(width, height);
517        ground.Image = groundTopImages[levelNumber];
518        ground.Position = position;
519        ground.TextureWrapSize = new Vector(width / TILE_SIZE, height / TILE_SIZE);
520        Add(ground);
521    }
522    #endregion
523
524    void SetControls()
525    {
526        Keyboard.Listen(Key.A, ButtonState.Down, delegate { startingPlayers[0].Walk(-PLAYER_SPEED); }, "Player 1 moves left");
527        Keyboard.Listen(Key.D, ButtonState.Down, delegate { startingPlayers[0].Walk(PLAYER_SPEED); }, "Player 1 moves right");
528        Keyboard.Listen(Key.W, ButtonState.Down, delegate { startingPlayers[0].Jump(PLAYER_SPEED); }, "Player 1 jumps");
529
530        Keyboard.Listen(Key.Left, ButtonState.Down, delegate { startingPlayers[1].Walk(-PLAYER_SPEED); }, "Player 2 moves left");
531        Keyboard.Listen(Key.Right, ButtonState.Down, delegate { startingPlayers[1].Walk(PLAYER_SPEED); }, "Player 2 moves right");
532        Keyboard.Listen(Key.Up, ButtonState.Down, delegate { startingPlayers[1].Jump(PLAYER_SPEED); }, "Player 2 jumps");
533
534        Keyboard.Listen(Key.F1, ButtonState.Pressed, ShowControlHelp, "Show help");
535        Keyboard.Listen(Key.Escape, ButtonState.Pressed, ConfirmExit, "Exit game");
536    }
537
538    void Loss()
539    {
540        //TODO: Sumthin' flashy for our fallen friends.
541        Exit();
542    }
543
544    void CollectMilk(PhysicsObject player, PhysicsObject milk)
545    {
546        HillBilly billy = player as HillBilly;
547        if (billy == null)
548            return;
549
550        milk.Destroy();
551        billy.AnimWalk = new Animation(milkWalk);
552        billy.AnimIdle = new Animation(milkWalk.CurrentFrame);
553    }
554
555    #region Camera
556    void UpdateCamera()
557    {
558        double minY = players.Min(p => p.Y);
559        double maxY = players.Max(p => p.Y);
560        double minX = players.Min(p => p.X) + cameraOffset;
561
562        Vector minPosition = new Vector(Math.Max(minX, cameraTargetX), minY);
563        Vector maxPosition = new Vector(minX, maxY);
564
565        cameraTarget = (minPosition + maxPosition) * 0.5;
566        cameraTarget.X = Math.Max(cameraTargetX, minX);     //Lellllll.
567
568        //cameraTarget.Y = Math.Max(cameraTarget.X, Level.Bottom + Window.Height/2.0);
569
570        cameraTargetX = Math.Max(cameraTargetX, minX);
571
572        cameraTarget.X = Math.Min(cameraTargetX, rightCamLimit);
573        cameraTarget.Y = Math.Max(cameraTarget.Y, bottomCamLimit);
574
575        double windowMax = Camera.ScreenToWorld(new Vector(Window.Width / 2.0, 0)).X;
576        double windowMin = Camera.ScreenToWorld(new Vector(-Window.Width / 2.0, 0)).X;
577        foreach (var player in players)
578        {
579            player.Left = Math.Max(player.Left, windowMin);
580            player.Right = Math.Min(player.Right, windowMax);
581        }
582    }
583
584    protected override void Update(Time time)
585    {
586        Camera.Position += (cameraTarget - Camera.Position) * time.SinceLastUpdate.TotalSeconds * cameraSpeed;
587        //Camera.X += (cameraTargetX - Camera.X) * time.SinceLastUpdate.TotalSeconds * cameraSpeed;
588
589
590        base.Update(time);
591    }
592
593    /// <summary>
594    /// Yritän leikkiä kameralla. Vielä varmaan hetken pidempään.
595    /// </summary>
596    /// <param name="gameTime"></param>
597    /*
598    protected override void Update(Microsoft.Xna.Framework.GameTime gameTime)
599    {
600        foreach(HillBilly player in players)
601        {
602            playerPositionsX.Add(player.Position.X);
603            playerPositionsY.Add(player.Position.Y);
604        }
605
606        double maxX = playerPositionsX.Max();
607        double maxY = playerPositionsY.Max();
608        double minX = playerPositionsX.Min();
609        double minY = playerPositionsY.Min();
610
611        Vector minPosition = new Vector(minX, minY);
612        Vector maxPosition = new Vector(maxX, maxY);
613
614        Camera.Position = (minPosition + maxPosition) * 0.5;
615
616        playerPositionsX.Clear();
617        playerPositionsY.Clear();
618
619        base.Update(gameTime);
620    }
621     */
622    #endregion
623}
Note: See TracBrowser for help on using the repository browser.