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?

天気クイズゲームを作ってみた

Last updated at Posted at 2024-12-23

Pythonで「天気クイズゲーム」を作成するコードを取得します。このコードでは、OpenWeatherMap APIを使用して指定した都市の天気情報を取得し、それを基にクイズを出題します。

必要な準備

1.OpenWeatherMap APIに登録し、APIキーを取得してください(無料プランで十分)。
2.Pythonで以下のライブラリをインストールします

bash
pip install requests

コード(Python)

import random
import requests
#天気を当てる都市のリスト
cities = ["Tokyo", "New York", "London", "Paris", "Berlin"]

OpenWeatherMapから天気を取得する関数(シミュレーション)
def get_weather(city):
    api_key = "c15c353303fb9b465207ddfdaf8f3c24"  # ここにあなたのAPIキーを記入
    url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
    response = requests.get(url)
    data = response.json()
    return data["weather"][0]["main"]  # 天気を取得


#天気当てゲームをプレイする関数
def play_weather_game():
    city = random.choice(cities)
    print(f"Guess the weather in {city}!")

#実際の天気を取得
    actual_weather = get_weather(city)

#ユーザーの推測を取得
    user_guess = input("Enter your guess (Thunderstorm,Drizzle,Clear, Rain, Atmosphere, Clouds, Snow): ")

#推測が正しいか確認
    if user_guess == actual_weather:
        print("Correct! You guessed the weather.")
    else:
        print(f"Wrong! The actual weather in {city} is {actual_weather}.")

#ゲームを開始
play_weather_game()

最後に

クイズを出題し、スコアを集計します。
実行方法
API_KEYに自分のAPIキーを設定してください。
プログラムを実行して、クイズに挑戦します!
APIキーを取得後、動作させてみてください。不明点や追加機能についてもお気軽にご相談ください!



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?