--
はじめに
Xを眺めていたらこんなキャンペーンがあることを先日知りました。すでにキャンペーンに参加している人のブログ等を見ると簡単に作れそう!っていうのとAmazonQ使ったことないということもありチャレンジしました。
加えて作業ログをGoogle AI Studioに張り付けて以下の手順書を作成した。
今回はLinux(Ubuntu)環境でAWSコマンドラインインターフェース(AWS CLI)と、Amazon Qをセットアップし、簡単なPythonゲームを対話形式で作成するまでの一連の流れを手順書化。
前提
- Ubuntu 22.04(または類似のDebian系Linux)を使用していること。
- ターミナル(コマンドライン)の基本的な操作に慣れていること。
-
sudo
を使った管理者権限でのコマンド実行が可能であること。 - 今回はProxmoxにUbuntu22.04の仮想マシンを新規で作成して試してみた。
ステップ1: AWS CLIをインストール
最初に、AWSの各種サービスをコマンドラインから操作するための公式ツール「AWS CLI」をインストール。
1-1. 必要なツールを準備する
AWS CLIはZIP形式で配布されているため、展開(解凍)用のツールが必要。今回はunzipを使った。
# unzipをインストールします
# sudo は管理者権限でコマンドを実行するという意味です
# apt はUbuntuのパッケージ管理ツールです
sudo apt install unzip
ログでは、最初の unzip
コマンドが Command 'unzip' not found
とエラーになったため、このコマンドで解決。
1-2. AWS CLIのファイルをダウンロードする
curl
コマンドを使って、AWS CLIのインストールファイルをダウンロードします。
# curlコマンドで指定したURLからファイルをダウンロードします
# -o オプションで保存するファイル名を "awscliv2.zip" に指定しています
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
1-3. ダウンロードしたファイルを展開する
ダウンロードしたZIPファイルを unzip
コマンドで展開します。
# "awscliv2.zip" を展開します。これにより 'aws' というディレクトリが作成されます
unzip awscliv2.zip
1-4. AWS CLIをインストールする
展開してできた aws
ディレクトリの中にあるインストーラーを実行します。
# 管理者権限で 'aws' ディレクトリ内の 'install' スクリプトを実行します
sudo ./aws/install
1-5. インストールを確認する
最後に、バージョン情報を表示するコマンドを実行して、正しくインストールされたか確認します。
# awsコマンドのバージョンを表示します
aws --version
aws-cli/2.27.45 ...
のような表示が出れば、インストール成功です。
ステップ2: AmazonQのインストール
2-1. Pythonのパッケージ管理ツール pip
を準備する
Amazon Qのツールは、一部Pythonライブラリに依存することがあります。その管理ツールであるpip
をインストールしておきましょう。
# Pythonのパッケージ管理ツール 'pip' をインストールします
sudo apt install python3-pip
ログでは、このコマンド実行時に多くの依存パッケージも一緒にインストールされています。
2-2. Amazon Qのインストールパッケージをダウンロードする
Amazon Qは .deb
というDebian系Linux用のパッケージ形式で配布されています。wget
コマンドでダウンロードします。
# wgetコマンドでAmazon Qの.debパッケージをダウンロードします
wget https://desktop-release.q.us-east-1.amazonaws.com/latest/amazon-q.deb
2-3. 依存関係の解決とインストール
.deb
パッケージをインストールする際に、必要な他のライブラリが不足しているとエラーが出ます。ログでも実際にエラーが発生しています。
# まず、dpkgでインストールを試みます
sudo dpkg -i amazon-q.deb
# → 依存関係のエラーが表示されます
# 次に、以下のコマンドで不足している依存関係を自動的に解決・インストールします
sudo apt-get install -f
# 依存関係が解決された後、もう一度インストールコマンドを実行します
sudo dpkg -i amazon-q.deb
apt-get install -f
は、壊れた依存関係を「修正(fix)」してくれる非常に便利なコマンドです。
2-4. インストールを確認する
q
コマンドでバージョン情報を表示し、インストールが成功したか確認しましょう。
q --version
q 1.12.1
のような表示が出れば成功です。
ステップ3: Amazon Qのセットアップと基本的な使い方
インストールが完了したので、実際にAmazon Qを使ってみましょう。
3-1. Amazon Qにログインする
初めて使う際にはログインが必要です。以下のコマンドを実行してください。
q login
実行すると、認証用のコードとURLがターミナルに表示されます。
- 表示されたURLをブラウザで開きます。
- ブラウザに、ターミナルに表示された認証コードを入力します。
- 画面の指示に従い、AWS Builder IDなどでログインを完了させます。
ターミナルに「Logged in successfully」と表示されたらログイン完了です。
3-2. チャット機能を開始する
ログインできたら、チャットを開始します。
q chat
このコマンドを実行すると、Amazon Qとの対話モードに入ります。
ステップ4: Amazon Qとの対話によるプログラミング
ここでは、Qに指示を出して簡単なPythonゲームを作成してもらいます。
4-1. 開発の準備と最初の依頼
まず、ゲーム開発に必要なPythonライブラリ pygame
をインストールします。
# pipを使ってpygameをインストールします
python3 -m pip install -U pygame --user
次に、q chat
で対話モードに入り、ゲームを作りたいと伝えます。
> 何かゲームを作りたいです
するとQがいくつかのゲーム案を提示し、ball_bounce_game.py
というファイルにサンプルコードを書き込むことを提案してきます。y
(はい)か t
(信頼して常に許可)を入力すると、ファイルが作成されます。
ボールバウンスゲームを起動してみました。
4-2. エラー発生とAIによるデバッグ
作成されたボールバウンスゲームを起動してみましょう。
> ゲームを起動して
Qは python3 ball_bounce_game.py
を実行しようとしますが、以下のエラーメッセージが出力されてしまいました。
error: XDG_RUNTIME_DIR not set in the environment.
ALSA lib confmisc.c:855:(parse_card) cannot find card '0'
ALSA lib conf.c:5178:(_snd_config_evaluate) function snd_func_card_inum returned error: No such file or directory
ALSA lib confmisc.c:422:(snd_func_concat) error evaluating strings
ALSA lib conf.c:5178:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory
ALSA lib confmisc.c:1334:(snd_func_refer) error evaluating name
ALSA lib conf.c:5178:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory
ALSA lib conf.c:5701:(snd_config_expand) Evaluate error: No such file or directory
ALSA lib pcm.c:2664:(snd_pcm_open_noupdate) Unknown PCM default
このエラーを解決できるか尋ねてみましょう。
> エラーメッセージが出力されているけど解決できる?
Qはエラーログを分析し、調査をします。
エラーの詳細を確認して解決しましょう!まず、どのようなエラーが発生しているか確認させてください。
?? Using tool: execute_bash (trusted)
?
● I will run the following shell command: python3 --version
?
? Purpose: Pythonのバージョンを確認
Python 3.10.12
?
● Completed in 0.10s
?? Using tool: execute_bash (trusted)
?
● I will run the following shell command:
python3 -c "import pygame; print('Pygame version:', pygame.version.ver)"
?
? Purpose: Pygameがインストールされているか確認
pygame 2.6.1 (SDL 2.28.4, Python 3.10.12)
Hello from the pygame community. https://www.pygame.org/contribute.html
Pygame version: 2.6.1
?
● Completed in 0.612s
Pygameは正常にインストールされていますね。ゲームを実行してみて、具体的なエラーメッセージを確認しましょう:
?? Using tool: execute_bash (trusted)
?
● I will run the following shell command:
ls -la /home/test/ball_bounce_game.py
?
? Purpose: ゲームファイルが存在するか確認
-rw-r--r-- 1 root root 1802 Jun 29 05:14 /home/test/ball_bounce_game.py
?
● Completed in 0.13s
?? Using tool: execute_bash (trusted)
?
● I will run the following shell command:
cd /home/test && timeout 5 python3 ball_bounce_game.py 2>&1 || echo "実行完了またはタイムアウト"
?
? Purpose: ゲームを実行してエラーメッセージを確認
error: XDG_RUNTIME_DIR not set in the environment.
ALSA lib confmisc.c:855:(parse_card) cannot find card '0'
ALSA lib conf.c:5178:(_snd_config_evaluate) function snd_func_card_inum returned error: No such file or directory
ALSA lib confmisc.c:422:(snd_func_concat) error evaluating strings
ALSA lib conf.c:5178:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory
ALSA lib confmisc.c:1334:(snd_func_refer) error evaluating name
ALSA lib conf.c:5178:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory
ALSA lib conf.c:5701:(snd_config_expand) Evaluate error: No such file or directory
ALSA lib pcm.c:2664:(snd_pcm_open_noupdate) Unknown PCM default
pygame 2.6.1 (SDL 2.28.4, Python 3.10.12)
Hello from the pygame community. https://www.pygame.org/contribute.html
実行完了またはタイムアウト
?
● Completed in 5.158s
エラーの原因が分かりました!これはLinux環境でGUIアプリケーションを実行する際によくある問題です。主に以下の問題があります:
1. XDG_RUNTIME_DIR が設定されていない
2. DISPLAY 環境変数が設定されていない可能性
3. オーディオデバイス の問題(ALSA関連)
これらを解決するために、環境変数を設定してゲームを実行してみましょう:
?? Using tool: execute_bash (trusted)
?
● I will run the following shell command:
cd /home/test && XDG_RUNTIME_DIR=/tmp DISPLAY=:0 SDL_AUDIODRIVER=dummy timeout 5 python3 ball_bounce_game.py 2>&1 || echo "実行完了またはタイムアウト"
?
? Purpose: 環境変数を設定してゲームを実行
pygame 2.6.1 (SDL 2.28.4, Python 3.10.12)
Hello from the pygame community. https://www.pygame.org/contribute.html
実行完了またはタイムアウト
?
● Completed in 5.176s
「GUI環境がないことが原因」だと突き止めます。そして、この環境でも動作する「コンソールベースのゲーム」を作成する代替案を提示してくれます。
良い感じです!エラーメッセージが大幅に減りました。
ただし、GUI環境がない可能性があるので、より簡単なテスト用のコンソールベースのゲームも作成しましょう。
4-3. コンソールゲームの作成と実行
Qの提案に従い、コンソールで動くゲームを作成。今回は数当てゲームとじゃんけんゲームを作りました。
Qが umber_guess_game.pyというファイルにコードを生成してくれます。承認するとファイルが作成され、以下のコマンドで実行できます。
# q chatモードの中で、Qに実行を依頼するか、
# /quit でチャットを抜けてから手動で実行します。
python3 umber_guess_game.py
?? Using tool: fs_write (trusted)
?
● Path: /home/test/number_guess_game.py
+ 1: import random
+ 2:
+ 3: def number_guess_game():
+ 4: print("=== 数当てゲーム ===")
+ 5: print("1から100までの数字を当ててください!")
+ 6:
+ 7: # ランダムな数字を生成
+ 8: target_number = random.randint(1, 100)
+ 9: attempts = 0
+ 10: max_attempts = 7
+ 11:
+ 12: while attempts < max_attempts:
+ 13: try:
+ 14: # ユーザーの入力を取得
+ 15: guess = int(input(f"\n残り{max_attempts - attempts}回: 数字を入力してください (1-100): "))
+ 16: attempts += 1
+ 17:
+ 18: if guess < 1 or guess > 100:
+ 19: print("1から100の間で入力してください!")
+ 20: continue
+ 21:
+ 22: if guess == target_number:
+ 23: print(f"\n? 正解! {target_number} でした!")
+ 24: print(f"{attempts}回で当てました!")
+ 25: break
+ 26: elif guess < target_number:
+ 27: print("もっと大きい数字です!")
+ 28: else:
+ 29: print("もっと小さい数字です!")
+ 30:
+ 31: except ValueError:
+ 32: print("数字を入力してください!")
+ 33:
+ 34: else:
+ 35: print(f"\n? 残念!正解は {target_number} でした。")
+ 36:
+ 37: # もう一度プレイするか確認
+ 38: play_again = input("\nもう一度プレイしますか? (y/n): ").lower()
+ 39: if play_again == 'y' or play_again == 'yes':
+ 40: number_guess_game()
+ 41: else:
+ 42: print("ゲーム終了!ありがとうございました!")
+ 43:
+ 44: if __name__ == "__main__":
+ 45: number_guess_game()
Creating: /home/test/number_guess_game.py
?
● Completed in 0.2s
?? Using tool: execute_bash (trusted)
?
● I will run the following shell command:
cd /home/test && python3 number_guess_game.py
?
? Purpose: 数当てゲームを起動
実際の和当てゲームはこんな感じでした。
=== 数当てゲーム ===
1から100までの数字を当ててください!
残り7回: 数字を入力してください (1-100): 数字を入力してください!
100
残り7回: 数字を入力してください (1-100): もっと小さい数字です!
1^H^H^H
残り6回: 数字を入力してください (1-100): 数字を入力してください!
30
残り6回: 数字を入力してください (1-100): もっと大きい数字です!
33
残り5回: 数字を入力してください (1-100): もっと大きい数字です!
38
残り4回: 数字を入力してください (1-100): もっと小さい数字です!
34
残り3回: 数字を入力してください (1-100):
? 正解! 34 でした!
5回で当てました!
もう一度プレイしますか? (y/n): ゲーム終了!ありがとうございました!
同じようにじゃんけんゲームも作成を依頼。janken_game.pyというファイルを自動生成。
※大昔に大学の課題でVisual Basicでじゃんけんゲームを作ったことがあるのですがこんなに簡単になるなんて!!
?? Using tool: fs_write (trusted)
?
● Path: /home/test/janken_game.py
+ 1: import random
+ 2:
+ 3: def janken_game():
+ 4: print("=== じゃんけんゲーム ===")
+ 5: print("コンピューターとじゃんけんで勝負しましょう!")
+ 6: print("グー: 1, チョキ: 2, パー: 3")
+ 7:
+ 8: # 選択肢の辞書
+ 9: choices = {1: "グー", 2: "チョキ", 3: "パー"}
+ 10: choices_emoji = {1: "?", 2: "??", 3: "?"}
+ 11:
+ 12: # スコア管理
+ 13: player_wins = 0
+ 14: computer_wins = 0
+ 15: draws = 0
+ 16:
+ 17: while True:
+ 18: print(f"\n--- 現在のスコア ---")
+ 19: print(f"あなた: {player_wins}勝 | コンピューター: {computer_wins}勝 | 引き分け: {draws}回")
+ 20: print("-" * 30)
+ 21:
+ 22: try:
+ 23: # プレイヤーの選択
+ 24: player_choice = int(input("\n選択してください (1:グー, 2:チョキ, 3:パー, 0:終了): "))
+ 25:
+ 26: if player_choice == 0:
+ 27: break
+ 28:
+ 29: if player_choice not in [1, 2, 3]:
+ 30: print("1, 2, 3のいずれかを選択してください!")
+ 31: continue
+ 32:
+ 33: # コンピューターの選択
+ 34: computer_choice = random.randint(1, 3)
+ 35:
+ 36: # 結果表示
+ 37: print(f"\nあなた: {choices[player_choice]} {choices_emoji[player_choice]}")
+ 38: print(f"コンピューター: {choices[computer_choice]} {choices_emoji[computer_choice]}")
+ 39:
+ 40: # 勝敗判定
+ 41: if player_choice == computer_choice:
+ 42: print("? 引き分けです!")
+ 43: draws += 1
+ 44: elif (player_choice == 1 and computer_choice == 2) or \
+ 45: (player_choice == 2 and computer_choice == 3) or \
+ 46: (player_choice == 3 and computer_choice == 1):
+ 47: print("? あなたの勝ちです!")
+ 48: player_wins += 1
+ 49: else:
+ 50: print("? コンピューターの勝ちです!")
+ 51: computer_wins += 1
+ 52:
+ 53: except ValueError:
+ 54: print("数字を入力してください!")
+ 55: except KeyboardInterrupt:
+ 56: print("\nゲームを中断します...")
+ 57: break
+ 58:
+ 59: # 最終結果
+ 60: print(f"\n=== 最終結果 ===")
+ 61: print(f"あなた: {player_wins}勝")
+ 62: print(f"コンピューター: {computer_wins}勝")
+ 63: print(f"引き分け: {draws}回")
+ 64:
+ 65: total_games = player_wins + computer_wins + draws
+ 66: if total_games > 0:
+ 67: win_rate = (player_wins / total_games) * 100
+ 68: print(f"勝率: {win_rate:.1f}%")
+ 69:
+ 70: if player_wins > computer_wins:
+ 71: print("? 総合勝利!おめでとうございます!")
+ 72: elif player_wins < computer_wins:
+ 73: print("? 総合敗北...次回頑張りましょう!")
+ 74: else:
+ 75: print("? 総合引き分け!いい勝負でした!")
+ 76:
+ 77: print("ゲーム終了!ありがとうございました!")
+ 78:
+ 79: def show_rules():
+ 80: print("\n=== じゃんけんのルール ===")
+ 81: print("? グー は ?? チョキ に勝つ")
+ 82: print("?? チョキ は ? パー に勝つ")
+ 83: print("? パー は ? グー に勝つ")
+ 84: print("同じ手は引き分け")
+ 85: print("-" * 25)
+ 86:
+ 87: if __name__ == "__main__":
+ 88: show_rules()
+ 89: janken_game()
Creating: /home/test/janken_game.py
?
● Completed in 0.1s
?? Using tool: execute_bash (trusted)
?
● I will run the following shell command:
cd /home/test && python3 janken_game.py
?
? Purpose: じゃんけんゲームを起動
Qが janken_game.py
というファイルにコードを生成してくれます。承認するとファイルが作成され、以下のコマンドで実行できます。
# q chatモードの中で、Qに実行を依頼するか、
# /quit でチャットを抜けてから手動で実行します。
python3 janken_game.py
じゃんけんゲームはこんな感じでした。
=== じゃんけんのルール ===
? グー は ?? チョキ に勝つ
?? チョキ は ? パー に勝つ
? パー は ? グー に勝つ
同じ手は引き分け
-------------------------
=== じゃんけんゲーム ===
コンピューターとじゃんけんで勝負しましょう!
グー: 1, チョキ: 2, パー: 3
--- 現在のスコア ---
あなた: 0勝 | コンピューター: 0勝 | 引き分け: 0回
------------------------------
1
選択してください (1:グー, 2:チョキ, 3:パー, 0:終了):
あなた: グー ?
コンピューター: パー ?
? コンピューターの勝ちです!
--- 現在のスコア ---
あなた: 0勝 | コンピューター: 1勝 | 引き分け: 0回
------------------------------
2
選択してください (1:グー, 2:チョキ, 3:パー, 0:終了):
あなた: チョキ ??
コンピューター: チョキ ??
? 引き分けです!
--- 現在のスコア ---
あなた: 0勝 | コンピューター: 1勝 | 引き分け: 1回
------------------------------
上記2件はどちらかというとQの提案に沿って作ったゲームでしたが、最後にネットワーク転送時間の計算をするクイズを作りました。
>ファイルサイズ、回線速度をランダムに出力し、転送時間を3択で充てるゲームを作ってください。
また、正解、不正解どちらのケースも正しい算出式を解説してください
以下のコードを生成。
Using tool: fs_write (trusted)
?
● Path: /home/test/transfer_time_quiz.py
+ 1: #!/usr/bin/env python3
+ 2: # -*- coding: utf-8 -*-
+ 3: """
+ 4: ファイル転送時間当てゲーム(計算式解説付き)
+ 5: File Transfer Time Quiz Game with Formula Explanation
+ 6: """
+ 7:
+ 8: import random
+ 9: import math
+ 10:
+ 11: def format_file_size(size_bytes):
+ 12: """ファイルサイズを読みやすい形式に変換"""
+ 13: if size_bytes < 1024:
+ 14: return f"{size_bytes} B"
+ 15: elif size_bytes < 1024**2:
+ 16: return f"{size_bytes/1024:.1f} KB"
+ 17: elif size_bytes < 1024**3:
+ 18: return f"{size_bytes/(1024**2):.1f} MB"
+ 19: else:
+ 20: return f"{size_bytes/(1024**3):.2f} GB"
+ 21:
+ 22: def format_speed(speed_bps):
+ 23: """回線速度を読みやすい形式に変換"""
+ 24: if speed_bps < 1024:
+ 25: return f"{speed_bps} bps"
+ 26: elif speed_bps < 1024**2:
+ 27: return f"{speed_bps/1024:.1f} Kbps"
+ 28: elif speed_bps < 1024**3:
+ 29: return f"{speed_bps/(1024**2):.1f} Mbps"
+ 30: else:
+ 31: return f"{speed_bps/(1024**3):.2f} Gbps"
+ 32:
+ 33: def format_time(seconds):
+ 34: """時間を読みやすい形式に変換"""
+ 35: if seconds < 1:
+ 36: return f"{seconds*1000:.0f}ミリ秒"
+ 37: elif seconds < 60:
+ 38: return f"{seconds:.1f}秒"
+ 39: elif seconds < 3600:
+ 40: minutes = seconds / 60
+ 41: return f"{minutes:.1f}分"
+ 42: else:
+ 43: hours = seconds / 3600
+ 44: return f"{hours:.2f}時間"
+ 45:
+ 46: def calculate_transfer_time(file_size_bytes, speed_bps):
+ 47: """転送時間を計算(秒)"""
+ 48: # ファイルサイズをビットに変換
+ 49: file_size_bits = file_size_bytes * 8
+ 50: # 転送時間 = ファイルサイズ(bits) / 回線速度(bps)
+ 51: return file_size_bits / speed_bps
+ 52:
+ 53: def explain_calculation(file_size_bytes, speed_bps, transfer_time):
+ 54: """計算式の詳細解説"""
+ 55: file_size_bits = file_size_bytes * 8
+ 56:
+ 57: print("\n? 計算式の解説:")
+ 58: print("=" * 40)
+ 59: print("転送時間の計算公式:")
+ 60: print("転送時間(秒) = ファイルサイズ(ビット) ÷ 回線速度(bps)")
+ 61: print()
+ 62: print("ステップ1: ファイルサイズをビットに変換")
+ 63: print(f" {format_file_size(file_size_bytes)} = {file_size_bytes:,} バイト")
+ 64: print(f" {file_size_bytes:,} バイト × 8 = {file_size_bits:,} ビット")
+ 65: print()
+ 66: print("ステップ2: 転送時間を計算")
+ 67: print(f" {file_size_bits:,} ビット ÷ {speed_bps:,} bps = {transfer_time:.3f} 秒")
+ 68: print(f" = {format_time(transfer_time)}")
+ 69: print("=" * 40)
+ 70:
+ 71: def generate_random_file_size():
+ 72: """ランダムなファイルサイズを生成(バイト)"""
+ 73: size_patterns = [
+ 74: # 小さなファイル (1KB - 1MB)
+ 75: lambda: random.randint(1024, 1024**2),
+ 76: # 中程度のファイル (1MB - 100MB)
+ 77: lambda: random.randint(1024**2, 100 * 1024**2),
+ 78: # 大きなファイル (100MB - 2GB)
+ 79: lambda: random.randint(100 * 1024**2, 2 * 1024**3),
+ 80: # 動画ファイル (500MB - 5GB)
+ 81: lambda: random.randint(500 * 1024**2, 5 * 1024**3)
+ 82: ]
+ 83:
+ 84: return random.choice(size_patterns)()
+ 85:
+ 86: def generate_random_speed():
+ 87: """ランダムな回線速度を生成(bps)"""
+ 88: speed_patterns = [
+ 89: # ダイヤルアップ
+ 90: lambda: random.randint(28800, 56000),
+ 91: # ADSL
+ 92: lambda: random.randint(1024**2, 24 * 1024**2),
+ 93: # 光回線
+ 94: lambda: random.randint(10 * 1024**2, 100 * 1024**2),
+ 95: # 高速光回線
+ 96: lambda: random.randint(100 * 1024**2, 1024**3),
+ 97: # 超高速回線
+ 98: lambda: random.randint(1024**3, 10 * 1024**3)
+ 99: ]
+ 100:
+ 101: return random.choice(speed_patterns)()
+ 102:
+ 103: def generate_choices(correct_time):
+ 104: """正解と2つの間違った選択肢を生成"""
+ 105: choices = [correct_time]
+ 106:
+ 107: # より現実的な間違った選択肢を生成
+ 108: wrong_factors = [
+ 109: random.uniform(0.1, 0.5), # 正解より短い時間
+ 110: random.uniform(2.0, 10.0) # 正解より長い時間
+ 111: ]
+ 112:
+ 113: for factor in wrong_factors:
+ 114: wrong_time = correct_time * factor
+ 115: choices.append(wrong_time)
+ 116:
+ 117: # シャッフル
+ 118: random.shuffle(choices)
+ 119:
+ 120: # 正解のインデックスを見つける
+ 121: correct_index = choices.index(correct_time)
+ 122:
+ 123: return choices, correct_index
+ 124:
+ 125: def play_single_question(question_num, total_questions):
+ 126: """1問を実行"""
+ 127: print(f"\n問題 {question_num}/{total_questions}")
+ 128: print("=" * 50)
+ 129:
+ 130: # ランダムなファイルサイズと回線速度を生成
+ 131: file_size = generate_random_file_size()
+ 132: speed = generate_random_speed()
+ 133:
+ 134: # 転送時間を計算
+ 135: transfer_time = calculate_transfer_time(file_size, speed)
+ 136:
+ 137: # 問題を表示
+ 138: print(f"? ファイルサイズ: {format_file_size(file_size)}")
+ 139: print(f"? 回線速度: {format_speed(speed)}")
+ 140: print()
+ 141: print("? このファイルの転送にかかる時間は?")
+ 142: print()
+ 143:
+ 144: # 選択肢を生成
+ 145: choices, correct_index = generate_choices(transfer_time)
+ 146:
+ 147: # 選択肢を表示
+ 148: for i, choice in enumerate(choices):
+ 149: print(f" {i+1}. {format_time(choice)}")
+ 150:
+ 151: print()
+ 152:
+ 153: # ユーザーの回答を取得
+ 154: while True:
+ 155: try:
+ 156: answer = int(input("答えを選んでください (1-3): ")) - 1
+ 157: if 0 <= answer <= 2:
+ 158: break
+ 159: else:
+ 160: print("? 1, 2, 3のいずれかを入力してください。")
+ 161: except ValueError:
+ 162: print("? 数字を入力してください。")
+ 163:
+ 164: # 正解判定と解説
+ 165: if answer == correct_index:
+ 166: print("\n? 正解!")
+ 167: print(f"? あなたの答え: {format_time(choices[answer])}")
+ 168: explain_calculation(file_size, speed, transfer_time)
+ 169: return True
+ 170: else:
+ 171: print(f"\n? 不正解...")
+ 172: print(f"? あなたの答え: {format_time(choices[answer])}")
+ 173: print(f"? 正解: {format_time(transfer_time)}")
+ 174: explain_calculation(file_size, speed, transfer_time)
+ 175: return False
+ 176:
+ 177: def play_game():
+ 178: """ゲームを実行"""
+ 179: print("?" * 25)
+ 180: print("? ファイル転送時間当てゲーム ?")
+ 181: print("?" * 25)
+ 182: print("\n? ルール:")
+ 183: print("・ファイルサイズと回線速度から転送時間を推測")
+ 184: print("・3つの選択肢から正解を選んでください")
+ 185: print("・各問題の後に詳しい計算式を解説します")
+ 186:
+ 187: score = 0
+ 188: total_questions = 5
+ 189:
+ 190: for question_num in range(1, total_questions + 1):
+ 191: is_correct = play_single_question(question_num, total_questions)
+ 192: if is_correct:
+ 193: score += 1
+ 194:
+ 195: if question_num < total_questions:
+ 196: input("\n?? 次の問題に進むにはEnterキーを押してください...")
+ 197:
+ 198: # 最終結果
+ 199: print("\n" + "?" * 50)
+ 200: print(f"? 最終結果: {score}/{total_questions} 問正解!")
+ 201:
+ 202: percentage = (score / total_questions) * 100
+ 203:
+ 204: if score == total_questions:
+ 205: print("? パーフェクト!転送時間計算のエキスパートですね!")
+ 206: elif percentage >= 80:
+ 207: print("? 素晴らしい!ネットワークの知識が豊富ですね!")
+ 208: elif percentage >= 60:
+ 209: print("? 良い成績です!もう少しで上級者レベルです!")
+ 210: elif percentage >= 40:
+ 211: print("? まずまずです!計算式を覚えて練習しましょう!")
+ 212: else:
+ 213: print("? 頑張りましょう!基本的な計算式から復習してみてください!")
+ 214:
+ 215: print("?" * 50)
+ 216:
+ 217: def show_formula_reference():
+ 218: """計算式の参考資料を表示"""
+ 219: print("\n? 転送時間計算の基礎知識")
+ 220: print("=" * 50)
+ 221: print("基本公式:")
+ 222: print(" 転送時間(秒) = ファイルサイズ(ビット) ÷ 回線速度(bps)")
+ 223: print()
+ 224: print("単位変換:")
+ 225: print(" 1バイト = 8ビット")
+ 226: print(" 1KB = 1,024バイト")
+ 227: print(" 1MB = 1,024KB = 1,048,576バイト")
+ 228: print(" 1GB = 1,024MB")
+ 229: print()
+ 230: print("回線速度の例:")
+ 231: print(" ダイヤルアップ: 56Kbps")
+ 232: print(" ADSL: 1-24Mbps")
+ 233: print(" 光回線: 100Mbps-1Gbps")
+ 234: print("=" * 50)
+ 235:
+ 236: def main():
+ 237: """メイン関数"""
+ 238: while True:
+ 239: print("\n? ファイル転送時間クイズ ?")
+ 240: print("1. ゲームを開始")
+ 241: print("2. 計算式の説明を見る")
+ 242: print("3. 終了")
+ 243:
+ 244: choice = input("\n選択してください (1-3): ")
+ 245:
+ 246: if choice == "1":
+ 247: play_game()
+ 248: elif choice == "2":
+ 249: show_formula_reference()
+ 250: elif choice == "3":
+ 251: print("? ゲームを終了します。お疲れ様でした!")
+ 252: break
+ 253: else:
+ 254: print("? 1, 2, 3のいずれかを入力してください。")
+ 255:
+ 256: if __name__ == "__main__":
+ 257: main()
Creating: /home/test/transfer_time_quiz.py
Qが transfer_time_quiz.py
というファイルにコードを生成してくれます。承認するとファイルが作成され、以下のコマンドで実行できます。
# q chatモードの中で、Qに実行を依頼するか、
# /quit でチャットを抜けてから手動で実行します。
python3 transfer_time_quiz.py
こんな感じのゲームができました。
ファイル転送時間当てゲームを作成しました!このゲームには以下の特徴があります:
主な機能
ランダム生成:
~ ファイルサイズ: 1KB~5GBの様々なサイズ
~ 回線速度: ダイヤルアップから超高速回線まで
詳細な解説機能:
~ 正解・不正解どちらの場合も計算式を詳しく解説
~ ステップバイステップで計算過程を表示
~ 単位変換の説明も含む
ゲーム機能:
~ 5問の3択クイズ
~ スコア表示と詳細な評価
~ 計算式の参考資料も閲覧可能
計算式の解説内容
各問題の後に以下の内容を解説します:
-
基本公式の説明
~ 転送時間(秒) = ファイルサイズ(ビット) ÷ 回線速度(bps) -
ステップ1: 単位変換
~ バイトからビットへの変換 (×8)
~ 具体的な数値での計算例 -
ステップ2: 実際の計算
~ 数値を代入した計算過程
~ 最終結果の表示
ルール:
・ファイルサイズと回線速度から転送時間を推測
・3つの選択肢から正解を選んでください
・各問題の後に詳しい計算式を解説します
問題 1/5
==================================================
? ファイルサイズ: 676.8 MB
? 回線速度: 1.92 Gbps
? このファイルの転送にかかる時間は?
1. 16.0秒
2. 2.8秒
3. 1.0秒
2
答えを選んでください (1-3):
? 正解!
? あなたの答え: 2.8秒
? 計算式の解説:
========================================
転送時間の計算公式:
転送時間(秒) = ファイルサイズ(ビット) ÷ 回線速度(bps)
ステップ1: ファイルサイズをビットに変換
676.8 MB = 709,705,655 バイト
709,705,655 バイト × 8 = 5,677,645,240 ビット
ステップ2: 転送時間を計算
5,677,645,240 ビット ÷ 2,061,185,998 bps = 2.755 秒
= 2.8秒
========================================
思いつきで浮かんだこんなクイズも作ってくれました。
Google AI Studioを使った手順書作成
最後に上記の作業ログのファイルをGoogle AI Studioに参照させて手順をまとめてもらいました。
AWS CLIのセットアップからの一連の作業ログファイルを添付して以下の依頼を実施。
若干手直ししてますがほぼ上の文章はGoogle AI Studioにお任せしています。
ネットワーク機器の設定手順なんかも作業ログをAI Studioに食わせて作ってもらえそうだなと思いました。
Linuxターミナルでの操作ログを元に、初心者向けのステップバイステップの手順書を作成してください。
各コマンドが何をしているのか、簡単な説明も加えてください。
まとめ
今回以下のことが実施しました。業務にも生かせそうなポイントもところどころにあり、学びになりました。
- AWS CLIとAmazon Q CLIのインストールとセットアップ
- パッケージの依存関係エラーへの対処法
- AIアシスタント「Amazon Q」との対話によるコーディング
- エラー発生時のAIとの協調的なデバッグ
- Google AI Studioを使った手順の整理