Python環境構築とゲームプログラミングの実験
本記事では、Pythonを用いた開発環境のセットアップと簡単なゲームプログラムの作成方法について説明します。また、バージョン管理システムであるGitを使用してコードをリモートリポジトリにアップロードする手順も紹介します。
1. 実験目的
- Pythonの開発環境(PythonおよびPyCharm)をインストールし、動作確認を行う。
- Pythonで簡単なゲームプログラムを作成し、変数やデータ型、条件分岐などの基礎知識を学ぶ。
- Gitを用いてコードをリモートリポジトリに保存する方法を習得する。
2. 実験手順
(1) Python環境のセットアップ
Python公式サイトから最新版をダウンロードし、正常にインストールされているか確認してください。以下のコマンドを実行することで、Pythonが正しくインストールされていることを検証できます。
python --version
(2) PyCharmのインストール
PyCharm Community Editionを公式サイトからダウンロードし、インストールを行います。その後、いくつかのPythonパッケージをインストールしてみましょう。
pip install requests numpy
(3) ゲームプログラムの作成
以下は「じゃんけん」ゲームのサンプルコードです。プレイヤーが5回勝負を行い、最終的な勝敗を表示します。
import random
def main():
choices = ["グー", "チョキ", "パー"]
player_wins = 0
computer_wins = 0
rounds = 5
for _ in range(rounds):
print("選んでください: グー, チョキ, パー")
player_choice = input().strip()
if player_choice not in choices:
print("無効な入力です。もう一度やり直してください。")
continue
computer_choice = random.choice(choices)
print(f"コンピュータの選択: {computer_choice}")
if player_choice == computer_choice:
print("引き分け!")
elif (player_choice == "グー" and computer_choice == "チョキ") or \
(player_choice == "チョキ" and computer_choice == "パー") or \
(player_choice == "パー" and computer_choice == "グー"):
print("あなたの勝ち!")
player_wins += 1
else:
print("あなたの負け!")
computer_wins += 1
print("\n結果:")
if player_wins > computer_wins:
print(f"あなたが勝ちました!勝利数: {player_wins}")
elif player_wins < computer_wins:
print(f"あなたが負けました!敗北数: {computer_wins}")
else:
print("引き分けでした!")
if __name__ == "__main__":
main()
(4) Gitでのコード管理
作成したスクリプトをGiteeまたはGitHubにアップロードするためには、以下のコマンドを使用します。
git init
git add .
git commit -m "初回コミット"
git branch -M main
git remote add origin https://gitee.com/your-repository-url.git
git push -u origin main
3. 問題点と解決策
実験中、以下の問題が発生しました。
- 問題: Pythonスクリプトをexeファイルに変換できなかった。
- 解決策: PyInstallerをインストールし、次のコマンドを実行しました。
pip install pyinstaller
pyinstaller --onefile your_script.py
4. 感想
PythonはC言語に比べて非常に簡潔で分かりやすい言語であり、初心者にとって非常に学びやすいと言えます。今後も積極的に練習を行い、スキル向上を目指したいと考えています。
5. 参考文献
- 『ゼロから始めるPythonプログラミング』