新年のプログラミング教室ブログは、楽しく学べるテーマがおすすめです。今回は、初心者でも簡単にできる**Luaで作る「じゃんけんゲーム」**をご紹介します。Luaは軽量でシンプルなスクリプト言語で、ゲーム開発や組み込み用途で人気があります。
なぜLuaでじゃんけん?
・コードが短くてわかりやすい
・条件分岐や乱数など、基本構文を学べる
・コンソールで動くので環境構築が簡単
サンプルコード
— じゃんけんゲーム
math.randomseed(os.time()) — 乱数初期化
local hands = {“グー”, “チョキ”, “パー”}
print(“じゃんけんゲーム開始!”)
print(“選択: 1=グー, 2=チョキ, 3=パー”)
while true do
io.write(“あなたの手を選んでください (1-3): “)
local player = tonumber(io.read())
if player < 1 or player > 3 then
print(“1~3の数字を入力してください。”)
else
local computer = math.random(1, 3)
print(“あなた: ” .. hands[player] .. ” | コンピュータ: ” .. hands[computer])
if player == computer then
print(“あいこです!もう一度!”)
elseif (player == 1 and computer == 2) or
(player == 2 and computer == 3) or
(player == 3 and computer == 1) then
print(“あなたの勝ち!”)
break
else
print(“コンピュータの勝ち!”)
break
end
end
end
じゃんけんクイズ
Luaで乱数を生成する関数はどれでしょう?
① math.random ② io.read ③ os.time
じゃんけんの勝敗判定に使う構文は何でしょう?
① if文 ② for文 ③ repeat文
Luaで配列を定義する記号はどれでしょう?
① {} ② [] ③ ()
答え
① math.random
① if文
① {}
