import pygame
import sys
import requests

# 初始化
pygame.init()
WIDTH, HEIGHT = 520, 360
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("pygame 天气查询")

font = pygame.font.SysFont("simhei", 26)
clock = pygame.time.Clock()

# 颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (220, 220, 220)
BLUE = (90, 140, 255)

# 天气查询函数
def get_weather(city):
    try:
        url = f"http://wttr.in/{city}?format=%C|%t|%w"
        r = requests.get(url, timeout=5)
        if r.status_code != 200:
            return "查询失败"
        data = r.text.strip().split("|")
        return f"天气：{data[0]}  温度：{data[1]}  风力：{data[2]}"
    except:
        return "网络错误或城市无效"

# 输入框
class InputBox:
    def __init__(self, x, y, w, h, text=''):
        self.rect = pygame.Rect(x, y, w, h)
        self.text = text
        self.active = False

    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            self.active = self.rect.collidepoint(event.pos)
        if event.type == pygame.KEYDOWN and self.active:
            if event.key == pygame.K_BACKSPACE:
                self.text = self.text[:-1]
            else:
                self.text += event.unicode

    def draw(self, screen):
        pygame.draw.rect(screen, BLUE if self.active else GRAY, self.rect, 2)
        txt_surf = font.render(self.text, True, BLACK)
        screen.blit(txt_surf, (self.rect.x + 8, self.rect.y + 8))

# 按钮
class Button:
    def __init__(self, x, y, w, h, text):
        self.rect = pygame.Rect(x, y, w, h)
        self.text = text

    def draw(self, screen):
        pygame.draw.rect(screen, BLUE, self.rect)
        txt = font.render(self.text, True, WHITE)
        screen.blit(txt, (self.rect.x + 20, self.rect.y + 10))

    def is_clicked(self, pos):
        return self.rect.collidepoint(pos)

# UI 元素
input_city = InputBox(80, 80, 260, 45)
btn = Button(360, 80, 100, 45, "查询")
result_text = ""

# 主循环
running = True
while running:
    screen.fill(WHITE)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        input_city.handle_event(event)

        if event.type == pygame.MOUSEBUTTONDOWN:
            if btn.is_clicked(event.pos):
                city = input_city.text.strip()
                if city:
                    result_text = get_weather(city)
                else:
                    result_text = "请输入城市名称"

    # 标题
    title = font.render("城市天气查询（wttr.in）", True, BLACK)
    screen.blit(title, (140, 25))

    # 提示
    hint = font.render("请输入城市：", True, BLACK)
    screen.blit(hint, (80, 55))

    input_city.draw(screen)
    btn.draw(screen)

    # 显示结果
    if result_text:
        lines = result_text.split(" ")
        for i, line in enumerate(lines):
            surf = font.render(line, True, BLACK)
            screen.blit(surf, (60, 180 + i * 35))

    pygame.display.flip()
    clock.tick(30)

pygame.quit()
sys.exit()