|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- import sys
- import random
- import re
- import itertools
- from pygame.locals import *
- import pygame
- pygame.init()
- # 窗口设置
- WIDTH, HEIGHT = 800, 700
- window = pygame.display.set_mode((WIDTH, HEIGHT))
- pygame.display.set_caption("24点游戏")
- # 颜色定义
- WHITE = (255, 255, 255)
- BLACK = (0, 0, 0)
- GRAY = (200, 100, 100)
- GREEN = (0, 255, 0)
- RED = (255, 0, 0)
- BLUE = (0, 100, 102)
- ABC = (55, 0, 125)
- CDE = (255, 125, 0)
- # 字体设置
- font = pygame.font.SysFont('kaiti', 36)
- class Button:
- """按钮类"""
- def __init__(self, x, y, width, height, text, color=GRAY, text_color=BLACK):
- self.rect = pygame.Rect(x, y, width, height)
- self.text = text
- self.color = color
- self.text_color = text_color
- self.enabled = True
- def draw(self, surface):
- """绘制按钮"""
- color = self.color if self.enabled else (150, 150, 150)
- pygame.draw.rect(surface, color, self.rect)
- text_surf = font.render(self.text, True, self.text_color if self.enabled else (100, 100, 100))
- text_rect = text_surf.get_rect(center=self.rect.center)
- surface.blit(text_surf, text_rect)
- def is_clicked(self, pos):
- """检测点击"""
- return self.rect.collidepoint(pos) and self.enabled
- def generate_numbers():
- """生成4个1-10的随机数字"""
- return [random.randint(1, 10) for _ in range(4)]
- def find_24_solutions(numbers):
- """AI寻找所有可能的24点解法"""
- solutions = []
- ops = ['+', '-', '*', '/']
- for nums in itertools.permutations(numbers):
- a, b, c, d = nums
- for op1, op2, op3 in itertools.product(ops, repeat=3):
- # 尝试不同的运算顺序结构
- expressions = [
- f"({a}{op1}{b}){op2}({c}{op3}{d})", # (a op b) op (c op d)
- f"(({a}{op1}{b}){op2}{c}){op3}{d}", # ((a op b) op c) op d
- f"({a}{op1}({b}{op2}{c})){op3}{d}", # (a op (b op c)) op d
- f"{a}{op1}(({b}{op2}{c}){op3}{d})", # a op ((b op c) op d)
- f"{a}{op1}({b}{op2}({c}{op3}{d}))" # a op (b op (c op d))
- ]
- for expr in expressions:
- try:
- # 验证使用的数字是否正确
- used = list(map(int, re.findall(r'\d+', expr)))
- if sorted(used) != sorted(numbers):
- continue
- result = eval(expr)
- if abs(result - 24) < 1e-6:
- solutions.append(expr)
- except ZeroDivisionError:
- continue
- # 去重并保留顺序
- seen = set()
- unique_solutions = []
- for expr in solutions:
- if expr not in seen:
- seen.add(expr)
- unique_solutions.append(expr)
- return unique_solutions if unique_solutions else None
- def main():
- # 初始化游戏元素
- numbers = generate_numbers()
- number_buttons = [
- Button(100 + i * 150, 70, 120, 50, str(numbers[i]), BLUE)
- for i in range(4)
- ]
- # 运算符和括号按钮
- operator_buttons = [
- Button(100 + i * 150, 170, 120, 50, op)
- for i, op in enumerate(['+', '-', '*', '/'])
- ]
- # 添加括号按钮到第二行
- operator_buttons.append(Button(100 + 0 * 150, 270, 120, 50, '('))
- operator_buttons.append(Button(100 + 1 * 150, 270, 120, 50, ')'))
- control_buttons = {
- "clear": Button(100, 370, 120, 50, "清除"),
- "submit": Button(250, 370, 120, 50, "提交"),
- "new_game": Button(400, 370, 120, 50, "新游戏"),
- "ai_hint": Button(550, 370, 120, 50, "AI提示", text_color=BLUE)
- }
- current_expression = ""
- selected_numbers = [] # 存储选中按钮的索引
- result_text = "结果显示:"
- result_color = BLACK
- game_numbers = numbers.copy()
- running = True
- while running:
- window.fill(ABC)
- for event in pygame.event.get():
- if event.type == QUIT:
- running = False
- elif event.type == MOUSEBUTTONDOWN:
- pos = pygame.mouse.get_pos()
- # 处理AI提示按钮点击
- if control_buttons["ai_hint"].is_clicked(pos):
- solutions = find_24_solutions(game_numbers)
- if solutions:
- max_display = 3 # 最多显示3个解法
- displayed = solutions[:max_display]
- remaining = len(solutions) - max_display
- solution_texts = [f"解法 {i + 1}: {expr}" for i, expr in enumerate(displayed)]
- if remaining > 0:
- solution_texts.append(f"还有{remaining}种解法未显示...")
- result_text = "\n".join(solution_texts)
- result_color = BLUE
- else:
- result_text = "当前数字无解"
- result_color = RED
- # 处理数字按钮点击(基于索引)
- for i, btn in enumerate(number_buttons):
- if btn.is_clicked(pos):
- if i not in selected_numbers:
- current_expression += str(game_numbers[i])
- selected_numbers.append(i)
- btn.enabled = False
- # 处理运算符和括号按钮点击
- for btn in operator_buttons:
- if btn.is_clicked(pos):
- op = btn.text
- if op in ['(', ')']:
- current_expression += op
- else:
- if current_expression:
- last_char = current_expression[-1]
- if last_char in '+-*/':
- current_expression = current_expression[:-1] + op
- else:
- current_expression += op
- # 处理功能按钮
- if control_buttons["clear"].is_clicked(pos):
- current_expression = ""
- selected_numbers = []
- result_text = "结果显示:"
- for b in number_buttons:
- b.enabled = True
- if control_buttons["submit"].is_clicked(pos):
- try:
- # 提取并验证数字
- input_nums = list(map(int, re.findall(r'\d+', current_expression)))
- if sorted(input_nums) != sorted(game_numbers):
- result_text = "必须使用全部4个数字!"
- result_color = RED
- else:
- # 计算并验证结果
- result = eval(current_expression)
- if abs(result - 24) < 1e-6:
- result_text = "正确!一百分!"
- result_color = GREEN
- else:
- result_text = f"错误,结果:{result:.2f}"
- result_color = RED
- except:
- result_text = "无效的表达式"
- result_color = RED
- if control_buttons["new_game"].is_clicked(pos):
- game_numbers = generate_numbers()
- for i in range(4):
- number_buttons[i].text = str(game_numbers[i])
- number_buttons[i].enabled = True
- current_expression = ""
- selected_numbers = []
- result_text = ""
- # 绘制所有界面元素
- for btn in number_buttons + operator_buttons + list(control_buttons.values()):
- btn.draw(window)
- # 显示表达式和结果
- pygame.draw.rect(window, WHITE, (100, 450, 600, 50)) # 调整表达式显示位置
- expr_surf = font.render(f"表达式: {current_expression}", True, BLACK)
- window.blit(expr_surf, (100, 450))
- # 显示多行结果
- pygame.draw.rect(window, CDE, (100, 520, 600, 160)) # 调整结果区域位置和高度
- lines = result_text.split('\n')
- y_offset = 520
- for line in lines:
- line_surf = font.render(line, True, result_color)
- window.blit(line_surf, (100, y_offset))
- y_offset += 40 # 每行间隔40像素
- pygame.display.flip()
- pygame.quit()
- sys.exit()
- if __name__ == "__main__":
- main()
复制代码 |
评分
-
查看全部评分
|