学習目標
- random モジュールを使って乱数を生成できる
- ランダム性を活用したゲームプログラムを作成できる
- これまで学んだ知識を統合してゲームを設計できる
- オリジナルゲームのアイデアを実装できる
前回の復習
前回までに学んだ内容を簡単に確認しましょう:
# Variables, lists, functions
def greet(name):
return f"Hello, {name}!"
students = ["Taro", "Hanako", "Jiro"]
for student in students:
message = greet(student)
print(message)
復習問題:関数とリストを使って、3つの数値の中から最大値を返す関数を作ってみよう
1. 乱数の基本
プログラミングでは、予測できないランダムな値を生成することができます。これをゲームに活用すると、毎回違う展開が楽しめます。
random モジュールの使い方
import random
# Random integer between 1 and 6 (like a dice)
dice = random.randint(1, 6)
print("Dice:", dice)
# Random integer between 1 and 100
number = random.randint(1, 100)
print("Random number:", number)
# Random choice from a list
fruits = ["apple", "banana", "orange", "grape"]
chosen_fruit = random.choice(fruits)
print("Chosen fruit:", chosen_fruit)
# Random float between 0.0 and 1.0
random_float = random.random()
print("Random float:", random_float)
実習1:上のコードを何度か実行して、毎回違う値が出ることを確認してみよう
2. 簡単なゲーム
ゲーム1:サイコロゲーム
ゲーム説明:
- プレイヤーとコンピューターがサイコロを振る
- 大きい数を出した方が勝ち
import random
def roll_dice():
"""Roll a dice and return the result"""
return random.randint(1, 6)
def play_dice_game():
"""Play dice game"""
print("=== Dice Game ===")
input("Press Enter to roll the dice...")
player_roll = roll_dice()
computer_roll = roll_dice()
print(f"You rolled: {player_roll}")
print(f"Computer rolled: {computer_roll}")
if player_roll > computer_roll:
print("You win!")
elif player_roll < computer_roll:
print("Computer wins!")
else:
print("It's a tie!")
# Play the game
play_dice_game()
実習2:サイコロゲームを実行して、何度かプレイしてみよう
ゲーム2:数当てゲーム
ゲーム説明:
- コンピューターが1〜100の数字を考える
- プレイヤーが数字を当てる
- ヒント(大きい/小さい)をもらいながら当てる
import random
def number_guessing_game():
"""Number guessing game"""
print("=== Number Guessing Game ===")
print("I'm thinking of a number between 1 and 100")
secret_number = random.randint(1, 100)
attempts = 0
max_attempts = 10
while attempts < max_attempts:
try:
guess = int(input(f"Attempt {attempts + 1}/{max_attempts} - Enter your guess: "))
attempts += 1
if guess == secret_number:
print(f"Congratulations! You found it in {attempts} attempts!")
return
elif guess < secret_number:
print("Too low! Try a higher number.")
else:
print("Too high! Try a lower number.")
except ValueError:
print("Please enter a valid number")
attempts -= 1
print(f"Game over! The number was {secret_number}")
# Play the game
number_guessing_game()
実習3:数当てゲームをプレイして、戦略を考えてみよう
3. カードゲーム
ゲーム3:簡単なブラックジャック
ゲーム説明:
- カードを引いて、合計を21に近づける
- 21を超えたら負け
- コンピューターと対戦
import random
def draw_card():
"""Draw a random card (1-11)"""
return random.randint(1, 11)
def calculate_total(cards):
"""Calculate total of cards"""
return sum(cards)
def show_cards(name, cards, hide_first=False):
"""Display cards"""
if hide_first:
print(f"{name}'s cards: [??, {cards[1]}] Total: ??")
else:
total = calculate_total(cards)
print(f"{name}'s cards: {cards} Total: {total}")
def play_blackjack():
"""Play simple blackjack game"""
print("=== Simple Blackjack ===")
print("Try to get close to 21 without going over!")
# Initial cards
player_cards = [draw_card(), draw_card()]
computer_cards = [draw_card(), draw_card()]
# Player's turn
while True:
print("\n" + "-" * 30)
show_cards("Computer", computer_cards, hide_first=True)
show_cards("You", player_cards)
player_total = calculate_total(player_cards)
if player_total > 21:
print("Bust! You went over 21. You lose!")
return
choice = input("Hit (draw card) or Stand? (h/s): ").lower()
if choice == 'h':
player_cards.append(draw_card())
elif choice == 's':
break
else:
print("Please enter 'h' or 's'")
# Computer's turn
print("\n" + "-" * 30)
print("Computer's turn...")
while calculate_total(computer_cards) < 17:
computer_cards.append(draw_card())
print(f"Computer draws a card")
# Show final cards
print("\n" + "=" * 30)
print("FINAL RESULT")
print("=" * 30)
show_cards("You", player_cards)
show_cards("Computer", computer_cards)
player_total = calculate_total(player_cards)
computer_total = calculate_total(computer_cards)
# Determine winner
if computer_total > 21:
print("Computer bust! You win!")
elif player_total > computer_total:
print("You win!")
elif player_total < computer_total:
print("Computer wins!")
else:
print("It's a tie!")
# Play the game
play_blackjack()
実習4:ブラックジャックをプレイして、ゲームのルールを理解しよう
4. ゲーム設計のポイント
良いゲームを作るために大切なこと:
1. ゲームバランス
- 難しすぎず、簡単すぎない調整
- プレイヤーに選択肢を与える
- 運と戦略のバランス
2. フィードバック
- プレイヤーに結果をわかりやすく表示
- 進捗状況を見せる
- 勝敗の理由を明確にする
3. リプレイ性
- 毎回違う展開になる工夫
- スコアや記録の保存
- 難易度の調整
4. ユーザーインターフェース
- わかりやすいメニュー
- 明確な指示
- エラー処理
6. 課題
課題1:サイコロゲームの拡張
サイコロゲームを拡張して、以下の機能を追加してください:
- 3回勝負で勝敗を決める
- スコアを記録する
- 引き分けの場合は再度振る
課題2:コイントスゲーム
コインの表裏を当てるゲームを作成してください:
- プレイヤーが表か裏を予想
- 当たったら勝ち
- 連勝記録を表示
課題3:じゃんけんトーナメント
じゃんけんゲームを拡張してください:
- 5回勝負
- 勝ち数、負け数、引き分け数を記録
- 最後に統計を表示
発展課題:オリジナルゲーム
これまで学んだ知識を使って、オリジナルのゲームを作成してください。
アイデア例:
- 宝探しゲーム(マップ上で宝を探す)
- クイズゲーム(ランダムに問題を出題)
- スロットマシン
- ビンゴゲーム
- カードバトルゲーム
必須要素:
- random モジュールの使用
- 関数の活用
- 繰り返し処理
- 条件分岐
- スコアや記録の管理
まとめ
今日学んだこと:
- random モジュール:乱数の生成方法
- ゲームプログラミングの基本:ルール、バランス、フィードバック
- 様々なゲーム例:サイコロ、数当て、カード、RPG戦闘
- ゲーム設計:面白いゲームを作るためのポイント
プログラミングでゲームを作ることは、楽しみながら技術を磨く最高の方法です。ぜひオリジナルのゲームを作って、友達にも遊んでもらいましょう!
次回予告:AIを用いたアプリ作成にチャレンジします。
宿題:課題1〜3を完成させ、可能であれば発展課題でオリジナルゲームを作ってみましょう。
頑張ってください!🎮✨

コメント