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

Revision 6218, 21.2 KB checked in by sieerinn, 4 years ago (diff)

Putoamis- ja hyppyanimaatio.

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