XNA開發一個2D的小遊戲

c979170768發表於2011-11-05
 

這是我大一下半年時,寫的一個程式,覺得現在這個在wp上也有在用,所以和大家一起分享了下,程式寫的不好,請大家多多指教

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace WindowsGame2
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Texture2D background;
        Rectangle rect;                             //正方形
        Texture2D canon;
        float canon_rotation;
        List<gameobject> UFOs = new List<gameobject>();
        Random rd = new Random();
        List<gameobject> balls = new List<gameobject>();
        List<gameobject> exploreok = new List<gameobject>();
        KeyboardState prevkeyboarStart;
        const int explorerwidth = 320;
        const int explorerheith = 240;
         Point explorersize = new Point(4,5);
        float timer = 0;
        float interal = 1000f/60;
        AudioEngine engine;   //建立AudioEngine
        SoundBank soundbank;  //建立SoundBank對像
        WaveBank wavebank;   //建立WaveBank對像
        Cue mycue;   //這主要用於播放意思的對像
        float bump = 0;  //記錄使用炸彈的個數
        float score = 0;  //記錄擊中飛機的個數
        SpriteFont  gamefont; //建立遊戲字型(這環境不支撐中文)
        string sin ="1";  //標記

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }  

        protected override void Initialize()
        {
            base.Initialize();
        } 
        Form1 f1 = new Form1();
        protected override void LoadContent()
        {
            
            f1.ShowDialog();
            canon_rotation = 0;
            spriteBatch = new SpriteBatch(GraphicsDevice);
            background = Content.Load<Texture2D>("mypic//7132481");   //載入2D的圖片背景
            rect =
                new Rectangle(0,0,graphics.GraphicsDevice.Viewport.Width,
                graphics.GraphicsDevice.Viewport.Height);
            canon = Content.Load<Texture2D>("cannon");    //載入炮
            canon_rotation = -MathHelper.PiOver2;   //炮的位置
           
           
            for (int i = 0; i < Convert.ToInt16(f1.a); i++)   //隨機產生n個
            {
                gameobject ufo = new gameobject();
                ufo.sprite = Content.Load<Texture2D>("mypic//f-16c04");
                ufo.position=new Vector2(
                    0,MathHelper.Lerp(0f,200f,(float)rd.NextDouble()));
                ufo.velocity = new Vector2(MathHelper.Lerp(Convert.ToSingle(f1.pd), Convert.ToSingle(f1.pg), (float)rd.NextDouble()),
                    0);
                UFOs.Add(ufo);
            }
            for (int i = 0; i <Convert.ToInt16(f1.ps); i++)  //隨機產生5枚炮彈
            {
                gameobject ball = new gameobject();
                ball.sprite = Content.Load<Texture2D>("cannonball");
                ball.alive = false;
                balls.Add(ball);
            }
            for (int i = 0; i < 5; i++)
            {
                gameobject ex = new gameobject();
                ex.alive = false;
                ex.currenexplosionx = 0;
                ex.currentexplosiony = 0;
                ex.sprite = Content.Load<Texture2D>("mypic//explosion");
                exploreok.Add(ex);

            }
            engine = new AudioEngine("Content/AudioProject.xgs");
            wavebank = new WaveBank(engine, "Content/Wave Bank.xwb");
            soundbank = new SoundBank(engine, "Content/Sound Bank.xsb");
            mycue = soundbank.GetCue("background");
            mycue.Play();
            gamefont = Content.Load<SpriteFont>("gamefont");

         } 

        protected override void UnloadContent()
        {
      
        }
        bool ok = true;
        //Form1 f2 = new Form1();
        protected override void Update(GameTime gameTime)
        {
                          
            if (f1.i == "1")
            {
                sin = "1";
                bump = 0;
                score = 0;
                f1.i = "0";
                ok = true;
               
            }

                if (score==Convert.ToSingle(f1.jbb)*10-1)
                {
                    Form2 f2 =  new Form2();
                    f2.Show();
                    sin = "0";
                    //bump = 0;
                    score +=1;
                    f1.i = "0";
                    ok = true;
                }
              
           if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            KeyboardState keyboar = Keyboard.GetState();
            if ((keyboar.IsKeyDown(Keys.Left) || keyboar.IsKeyDown(Keys.A))&&sin=="1")
            {
                canon_rotation -= 0.1f;
            }
            if ((keyboar.IsKeyDown(Keys.Right) || keyboar.IsKeyDown(Keys.D)) && sin=="1")
            {
                canon_rotation += 0.1f;
            }
            canon_rotation = MathHelper.Clamp(
                canon_rotation,
               -MathHelper.Pi, 0);
            Updateufo();
            if (keyboar.IsKeyDown(Keys.Space)
               && !prevkeyboarStart.IsKeyDown(Keys.Space) && sin=="1")
            {
               
                foreach (var ball in balls)
                {
                    if (!ball.alive)
                    {    
                          ball.alive = true;
                          ball.position=new Vector2(390, 440) ;
                          ball.velocity = new Vector2
                         ((float)Math.Cos(canon_rotation) * 5,
                         (float)Math.Sin(canon_rotation) * 5);
                           soundbank.PlayCue("fire");
                           bump += 1;
                        

                        break;
                    }
    
                }
           
            }

            updateba();

            timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
            if (timer > interal)
            {
                upxiguo();
              
                timer = 0;
            }
          
            prevkeyboarStart = keyboar;
            base.Update(gameTime);
        } 
     
        private void upxiguo()
        {
            foreach (var ex in exploreok)
            {
                if (ex.alive)
                {
                    ex.currenexplosionx++;
                    if (ex.currenexplosionx> explorersize.X)
                    {
                        ex.currenexplosionx = 0;
                        ex.currentexplosiony++;
                        if (ex.currentexplosiony > explorersize.Y)
                        {
                            ex.currentexplosiony = 0;

                        }
                    }
                    if (ex.currenexplosionx == 0 && ex.currentexplosiony == 0)
                    {
                        ex.alive = false;
                    }
                    else
                    {
                        ex.sourcerect = new Rectangle(ex.currenexplosionx * explorerwidth, ex.currentexplosiony * explorerheith,
                            explorerwidth,
                            explorerheith);
                    }
                }
            }
        }

        protected override void Draw(GameTime gameTime)
        {

            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin();
            spriteBatch.Draw(background,rect,Color.White);
            spriteBatch.Draw(canon,
                new Vector2(400, 450),
                null,
                Color.White,
              canon_rotation,
                new Vector2(canon.Width / 2, canon.Height / 2),
                1f,
                SpriteEffects.None,
                0f);
            foreach (var item in UFOs)
            {
                if(item.alive)
                spriteBatch.Draw(item.sprite,item.position,Color.White);
            }
            foreach (var ball in balls)
            {
                if(ball.alive)
                spriteBatch.Draw(ball.sprite,ball.position,Color.White
                   
                    );
            }
            foreach (var ex in exploreok)
            {
                spriteBatch.Draw(ex.sprite, ex.position, ex.sourcerect, Color.White);
            }
            spriteBatch.DrawString(gamefont,"score:"+score.ToString(),new Vector2( 50,50),Color.Blue);
            spriteBatch.DrawString(gamefont, "bump:" +bump.ToString(), new Vector2(50, 80), Color.Red);
            spriteBatch.End();
            base.Draw(gameTime);
        }

        private void Updateufo()
        {
            //throw new NotImplementedException();
            foreach (var item in UFOs)
            {
                if (item.alive)
                {
                    item.position += item.velocity;
                    if (item.position.X > 800)
                        item.alive = false;
                }
                if (!item.alive)
                {
                    item.alive = true;
                    item.position = new Vector2(
                       0, MathHelper.Lerp(0f, 200f, (float)rd.NextDouble()));
                    item.velocity = new Vector2(MathHelper.Lerp(0.1f, 1f, (float)rd.NextDouble()),
                     0);
                }
            }

        }

        private void updateba()
        {
            foreach (var ball in balls)
            {
                if (ball.alive==true)
                {
                    ball.position += ball.velocity;
                    if (!rect.Contains(new Point((int)ball.position.X, (int)ball.position.Y)))
                    {
                        ball.alive = false;
                    }
                    else
                    {
                        Rectangle rectball = new Rectangle(
                       (int) ball.position.X,
                       (int)ball.position.Y,
                        ball.sprite.Width,
                        ball.sprite.Height);
                        foreach (var ufo in UFOs)
                        {
                            if (ufo.alive)
                            {
                                Rectangle recufo = new Rectangle(
                                (int)ufo.position.X,
                                (int)ufo.position.Y,
                                ufo.sprite.Width,
                                ufo.sprite.Height);
                                if (rectball.Intersects(recufo))
                                {
                                    ball.alive = false;
                                    ufo.alive = false;
                                    foreach (var ex in exploreok)
                                    {
                                        if (!ex.alive)
                                        {
                                            ex.alive = true;
                                            ex.currentexplosiony = 0;
                                            ex.currenexplosionx = 0;

                                            ex.position = new Vector2(
                                                ufo.position.X - (explorerwidth - ufo.sprite.Width) / 2,
                                                ufo.position.Y - (explorerheith - ufo.sprite.Height) / 2);
                                             soundbank.PlayCue("bao");
                                             score += 1;
                                            break;
                                        }
                                    }
                                    break;
                                }

                           
                           
                            }
                        }
                   
                    }
                }
            }
        }
    }
}

相關文章