C#初学者向け:プレイヤーのHPが増えるイメージ

初学者が「変数の値を変える」ことをストーリー仕立てで理解できる内容になっています。


◆ シチュエーション:回復アイテムを使った!

RPGゲームの中で、プレイヤーがポーション(回復アイテム)を使ってHPを回復する場面を考えます。


◆ サンプルコード

using System;

class Program
{
    static void Main()
    {
        int playerHP = 70;         // 現在のHP
        int healAmount = 30;       // ポーションの回復量

        Console.WriteLine("回復前のHP:" + playerHP);

        // 回復する
        playerHP = playerHP + healAmount;

        Console.WriteLine("回復後のHP:" + playerHP);
    }
}

◆ 実行結果

回復前のHP:70  
回復後のHP:100

◆ 解説

コード説明
int playerHP = 70;プレイヤーの現在HPを70に設定
int healAmount = 30;ポーションの回復量は30
playerHP = playerHP + healAmount;現在のHPに回復量を加えて、再びHPに代入する(上書き)

◆ 複合代入で書き換えると…

playerHP += healAmount;

意味は同じです。


◆ ゲームらしい応用:HPの最大値を超えないようにする

int maxHP = 100;
playerHP += healAmount;

if (playerHP > maxHP)
{
    playerHP = maxHP;
}

✅ 回復してもHPは最大値で止まる!


◆ ビジュアルイメージ(テキスト)

[ HPバー ]
回復前:■■■■■■□□□(70/100)
回復後:■■■■■■■■■■(100/100)

◆ 練習問題(初級)

次のコードの最終HPはいくつ?

int hp = 40;
int potion = 50;
int max = 80;

hp += potion;
if (hp > max) hp = max;

Console.WriteLine(hp);

✅ 答え:

80(→ 回復しすぎた分はカットされる)

訪問数 35 回, 今日の訪問数 1回

C#

Posted by hidepon