じゃんけんゲーム


MonoGameでシンプルなじゃんけんゲームを作ってみましょう。


画像ダウンロード

画像リソースをここからダウンロードし、zipファイルを解凍してください。
https://github.com/ymotoyama/Samples/raw/master/Janken%20Resources.zip



プロジェクトの作成

VisualStudioから新規プロジェクトを作成します。

画像の追加

VisualStudioのソリューションエクスプローラーからMonoGame Pipeline Toolを開き、画像を登録し、ビルドしてください。






ソースコード

今回はキーボード操作のゲームです。
1:グー
2:チョキ
3:パー
です。
わかりやすさのために、内部でもグー/チョキ/パーを同じ整数で管理するようにしました。
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System; // Randomを使うのに必要

namespace Janken
{
    // ゲームの状態種別
    enum State
    {
        // じゃんけん前
        Ready,
        // じゃんけん後
        Result,
    }

    // 勝敗種別
    enum Result
    {
        Win,
        Lose,
        Aiko,
    }

    /// <summary>
    /// This is the main type for your game.
    /// </summary>
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Texture2D textureAnata; // 「あなた」
        Texture2D textureAite; // 「あいて」
        Texture2D textureSetsumei; // 操作説明
        Texture2D textureGu; // グーの画像
        Texture2D textureChoki; // チョキの画像
        Texture2D texturePa; // パーの画像
        Texture2D textureKachi; // 「勝ち!」
        Texture2D textureMake; // 「負け…」
        Texture2D textureAiko; // 「あいこ」

        Random rand = new Random();

        // 現在のゲームの状態
        State state = State.Ready;

        // 勝敗を格納するための変数
        Result result;

        // 自分の手。1:グー, 2:チョキ, 3:パー
        int jibun = 0;

        // 相手の手
        int aite = 0;

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

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here

            // テクスチャーの読み込み
            textureAnata    = Content.Load<Texture2D>("anata");
            textureAite     = Content.Load<Texture2D>("aite");
            textureSetsumei = Content.Load<Texture2D>("setsumei");
            textureGu       = Content.Load<Texture2D>("janken_gu");
            textureChoki    = Content.Load<Texture2D>("janken_choki");
            texturePa       = Content.Load<Texture2D>("janken_pa");
            textureKachi    = Content.Load<Texture2D>("kachi");
            textureMake     = Content.Load<Texture2D>("make");
            textureAiko     = Content.Load<Texture2D>("aiko");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// game-specific content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            // TODO: Add your update logic here

            // じゃんけん前
            if (state == State.Ready)
            {
                if (Keyboard.GetState().IsKeyDown(Keys.D1)) // グー
                {
                    jibun = 1;
                }
                else if (Keyboard.GetState().IsKeyDown(Keys.D2)) // チョキ
                {
                    jibun = 2;
                }
                else if (Keyboard.GetState().IsKeyDown(Keys.D3)) // パー
                {
                    jibun = 3;
                }

                // ボタンが押されたか?
                if (jibun != 0)
                {
                    // 相手の手を決める
                    aite = rand.Next(1, 4);

                    // 勝敗を判定する
                    if (jibun == aite)
                    {
                        result = Result.Aiko; // あいこ
                    }
                    else if ((jibun == 1 && aite == 2) ||
                        (jibun == 2 && aite == 3) ||
                        (jibun == 3 && aite == 1))
                    {
                        result = Result.Win; // 勝ち
                    }
                    else
                    {
                        result = Result.Lose; // 負け
                    }

                    state = State.Result; // 結果状態に
                }
            }
            // じゃんけん後
            else if (state == State.Result)
            {
                // 何もしない
            }

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here

            spriteBatch.Begin();

            // 「あいて」の描画
            spriteBatch.Draw(textureAite, new Vector2(20, 20), Color.White);

            // 「あなた」の描画
            spriteBatch.Draw(textureAnata, new Vector2(20, 210), Color.White);

            // じゃんけん前の描画処理
            if (state == State.Ready)
            {
                // 操作説明の描画
                spriteBatch.Draw(textureSetsumei, new Vector2(330, 160), Color.White);
            }
            // じゃんけん後の描画処理
            else if (state == State.Result)
            {
                // あいての手の描画
                spriteBatch.Draw(GetTeTexture(aite), new Vector2(330, 20), Color.White);

                // 自分の手の描画
                spriteBatch.Draw(GetTeTexture(jibun), new Vector2(330, 210), Color.White);

                // 結果の描画
                Texture2D resultTexture;

                if (result == Result.Win)
                    resultTexture = textureKachi;
                else if (result == Result.Lose)
                    resultTexture = textureMake;
                else
                    resultTexture = textureAiko;

                spriteBatch.Draw(resultTexture, new Vector2(480, 210), Color.White);
            }

            spriteBatch.End();

            base.Draw(gameTime);
        }

        // 番号を元にテクスチャを返却する
        Texture2D GetTeTexture(int te)
        {
            if (te == 1)
                return textureGu;
            else if (te == 2)
                return textureChoki;
            else
                return texturePa;
        }
    }
}

練習問題

以下の練習問題に挑戦してみましょう!

  • スペースキーを押すとリトライするようにする
  • グー=1, チョキ=2, パー=3…となっている部分を定数またはenumを使って書き直す。
  • 以下のような感じにする




画像リソースはいらすとやに借りました。

0 件のコメント:

コメントを投稿