Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

flaskを使って数当てゲームを作ろう

Posted at

必要な準備

  • Python
  • VScode

また、同時にVScodeに「Python」の拡張機能をダウンロードしておくと便利です。

Flaskのインストール

Flaskを使用するために、Flaskをインストールします。ターミナルを起動し、以下のコマンドを実行します。

pip install Flask

次に、Flaskを使ってサーバー側のコードを作ります。app.pyという名前で以下のコードを作成します。

from flask import Flask, request, jsonify
import random

app = Flask(__name__)
number_to_guess = random.randint(1, 100)

@app.route('/guess', methods=['POST'])
def guess_number():
    user_guess = request.json.get('guess')
    if user_guess < number_to_guess:
        return jsonify({"message": "もっと大きい数です。"}), 200
    elif user_guess > number_to_guess:
        return jsonify({"message": "もっと小さい数です。"}), 200
    else:
        return jsonify({"message": "おめでとうございます!正解です!"}), 200

if __name__ == '__main__':
    app.run(debug=True)

次に、クライエント側のコードを作ります。client.pyという名前でコードを作成します。

import requests

url = 'http://127.0.0.1:5000/guess'

while True:
    user_guess = int(input("1から100の間の数を予想してください: "))
    response = requests.post(url, json={'guess': user_guess})
    message = response.json().get('message')
    print(message)
    if "正解です" in message:
        break

ファイルの構造

ファイルの構造は以下のようになっています。

number_guessing_game/
├── app.py
└── client.py

プログラムを実行する

VScodeでapp.pyのファイルを開き、ターミナルを起動して以下のコマンドを実行します。

python app.py

次に、client.pyのファイルを開き、ターミナルで以下のコードを実行します。

python client.py

以上の手順で数当てゲームをプレイできます。1~100の範囲の数を予想して、打ち込み、送られてきたヒントをもとに正解の数を当てます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?