机器人
积分排行榜
Scratch
积分排行榜
Python
在线答题
积分排行榜
活跃排行榜
打字练习
Microbit
C++
在线答题
积分排行榜
活跃排行榜
网盘
积分
未登录
未登录
登录学习
作者:
张一朔
更新时间:
2025-05-17 13:16
浏览:
31次
点赞:
0次
热度:
20
import random import numpy as np from typing import List, Tuple, Dict, Set, Optional class QuantumState: def __init__(self, positions: List[Tuple[int, int]], probabilities: List[float]): self.positions = positions # 可能的位置列表 self.probabilities = probabilities # 对应位置的概率振幅 self.normalize() def normalize(self): """归一化概率振幅""" magnitude_squared = sum(p**2 for p in self.probabilities) if magnitude_squared > 0: self.probabilities = [p / np.sqrt(magnitude_squared) for p in self.probabilities] def collapse(self) -> Tuple[int, int]: """波函数坍缩,根据概率选择一个确定的位置""" position_indices = list(range(len(self.positions))) weights = [p**2 for p in self.probabilities] index = random.choices(position_indices, weights=weights)[0] return self.positions[index] def entangle(self, other_state: 'QuantumState') -> None: """与另一个量子态纠缠""" # 简化的纠缠模型:两个态的位置完全相关 self.positions = other_state.positions.copy() self.probabilities = other_state.probabilities.copy() self.normalize() def split(self, directions: List[Tuple[int, int]], maze: 'QuantumMaze') -> 'QuantumState': """分裂量子态,创建叠加态""" new_positions = [] new_probabilities = [] for dx, dy in directions: for i, (x, y) in enumerate(self.positions): new_x, new_y = x + dx, y + dy if maze.is_valid_position(new_x, new_y): new_positions.append((new_x, new_y)) new_probabilities.append(self.probabilities[i] / np.sqrt(len(directions))) return QuantumState(new_positions, new_probabilities) class QuantumMaze: def __init__(self, width: int, height: int, difficulty: int = 3): self.width = width self.height = height self.difficulty = difficulty self.maze = self._generate_maze() self.start = (1, 1) self.goal = (width - 2, height - 2) self.entangled_pairs = self._create_entangled_pairs() self.wall_pairs = self._create_uncertain_walls() def _generate_maze(self) -> List[List[int]]: """使用深度优先搜索生成随机迷宫""" maze = [[1 for _ in range(self.width)] for _ in range(self.height)] stack = [] visited = set() # 从起点开始 x, y = self.start maze[y][x] = 0 # 0表示通路,1表示墙 visited.add((x, y)) stack.append((x, y)) directions = [(0, 2), (2, 0), (0, -2), (-2, 0)] while stack: x, y = stack[-1] unvisited_neighbors = [] for dx, dy in directions: nx, ny = x + dx, y + dy if 0 < nx < self.width - 1 and 0 < ny < self.height - 1 and (nx, ny) not in visited: unvisited_neighbors.append((nx, ny, dx//2, dy//2)) if unvisited_neighbors: nx, ny, wx, wy = random.choice(unvisited_neighbors) maze[y + wy][x + wx] = 0 # 打通墙壁 maze[ny][nx] = 0 # 设置为通路 visited.add((nx, ny)) stack.append((nx, ny)) else: stack.pop() # 添加一些随机墙壁增加难度 for _ in range(self.difficulty * 5): x = random.randint(1, self.width - 2) y = random.randint(1, self.height - 2) if (x, y) != self.start and (x, y) != self.goal: maze[y][x] = 1 return maze def _create_entangled_pairs(self) -> Dict[Tuple[int, int], Tuple[int, int]]: """创建量子纠缠位置对""" pairs = {} num_pairs = min(5, self.difficulty * 2) for _ in range(num_pairs): while True: x1 = random.randint(1, self.width - 2) y1 = random.randint(1, self.height - 2) x2 = random.randint(1, self.width - 2) y2 = random.randint(1, self.height - 2) if (x1, y1) != (x2, y2) and (x1, y1) not in pairs and (x2, y2) not in pairs: pairs[(x1, y1)] = (x2, y2) pairs[(x2, y2)] = (x1, y1) break return pairs def _create_uncertain_walls(self) -> List[Tuple[Tuple[int, int], Tuple[int, int]]]: """创建不确定的墙壁对(测不准原理)""" walls = [] num_pairs = min(3, self.difficulty) for _ in range(num_pairs): while True: x1 = random.randint(1, self.width - 2) y1 = random.randint(1, self.height - 2) x2 = random.randint(1, self.width - 2) y2 = random.randint(1, self.height - 2) if (x1, y1) != (x2, y2) and self.maze[y1][x1] == 1 and self.maze[y2][x2] == 1: walls.append(((x1, y1), (x2, y2))) break return walls def is_valid_position(self, x: int, y: int) -> bool: """检查位置是否有效(在迷宫范围内且不是墙)""" if 0 <= x < self.width and 0 <= y < self.height: return self.maze[y][x] == 0 return False def get_uncertain_wall_state(self, position: Tuple[int, int]) -> bool: """获取不确定墙壁的状态(根据测不准原理)""" for (pos1, pos2) in self.wall_pairs: if position == pos1: return self.maze[pos2[1]][pos2[0]] == 0 if position == pos2: return self.maze[pos1[1]][pos1[0]] == 0 return self.maze[position[1]][position[0]] == 0 def observe(self, state: QuantumState) -> Tuple[QuantumState, bool]: """观测量子态,导致波函数坍缩""" position = state.collapse() new_state = QuantumState([position], [1.0]) # 检查是否到达终点 if position == self.goal: return new_state, True # 检查纠缠对 if position in self.entangled_pairs: entangled_pos = self.entangled_pairs[position] new_state.positions.append(entangled_pos) new_state.probabilities = [1.0/np.sqrt(2), 1.0/np.sqrt(2)] new_state.normalize() return new_state, False def render(self, state: QuantumState) -> str: """渲染迷宫和玩家的量子态""" rendered = [] for y in range(self.height): row = [] for x in range(self.width): if (x, y) == self.start: row.append('S') elif (x, y) == self.goal: row.append('G') elif (x, y) in state.positions: idx = state.positions.index((x, y)) prob = state.probabilities[idx]**2 # 根据概率显示不同的符号 if prob > 0.7: row.append('@') elif prob > 0.3: row.append('o') else: row.append('.') elif self.get_uncertain_wall_state((x, y)): row.append('?') # 不确定的墙 elif self.maze[y][x] == 1: row.append('#') # 墙 else: row.append(' ') # 通路 rendered.append(''.join(row)) # 添加量子态信息 state_info = [f"Quantum State: {len(state.positions)} positions"] for i, (x, y) in enumerate(state.positions): prob = state.probabilities[i]**2 state_info.append(f" Position ({x}, {y}): Probability {prob:.2f}") return '\n'.join(rendered + state_info) class QuantumMazeGame: def __init__(self, width: int = 15, height: int = 15, difficulty: int = 3): self.maze = QuantumMaze(width, height, difficulty) self.player_state = QuantumState([self.maze.start], [1.0]) self.game_over = False self.victory = False self.observations_left = 5 + difficulty # 限制观测次数 def move(self, directions: List[Tuple[int, int]]) -> None: """移动玩家(分裂量子态)""" if self.game_over: return self.player_state = self.maze.split(directions, self.maze) # 检查是否到达终点(即使是叠加态) for pos in self.player_state.positions: if pos == self.maze.goal: self.victory = True self.game_over = True def observe(self) -> None: """观测玩家位置,导致波函数坍缩""" if self.game_over or self.observations_left <= 0: return self.observations_left -= 1 self.player_state, self.victory = self.maze.observe(self.player_state) self.game_over = self.victory or self.observations_left == 0 def get_status(self) -> str: """获取游戏状态信息""" status = [ f"Observations Left: {self.observations_left}", f"Goal: ({self.maze.goal[0]}, {self.maze.goal[1]})", ] if self.game_over: if self.victory: status.append("Congratulations! You solved the quantum maze!") else: status.append("Game Over! You ran out of observations.") return '\n'.join(status) def get_display(self) -> str: """获取游戏显示内容""" return self.maze.render(self.player_state) def main(): """主游戏循环""" print("Welcome to Quantum Maze!") print("Navigate the maze using quantum superposition to reach the goal (G).") print("You can move in multiple directions at once, but be careful with observations!") print("Each observation collapses your quantum state and reduces your observation count.") print("Type 'w', 'a', 's', 'd' to move (up, left, down, right).") print("Type 'observe' to collapse your quantum state and check your position.") print("Type 'q' to quit.") game = QuantumMazeGame() while not game.game_over: print("\n" + game.get_display()) print("\n" + game.get_status()) move_input = input("\nEnter move (e.g. 'w', 'wd', 'observe', 'q'): ").lower().strip() if move_input == 'q': print("Quitting game...") break if move_input == 'observe': game.observe() continue directions = [] for c in move_input: if c == 'w': directions.append((0, -1)) elif c == 'a': directions.append((-1, 0)) elif c == 's': directions.append((0, 1)) elif c == 'd': directions.append((1, 0)) if directions: game.move(directions) else: print("Invalid input. Please try again.") print("\n" + game.get_display()) print("\n" + game.get_status()) if __name__ == "__main__": main()
点赞成功
分享作品
×