Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # ==============================================================================
- # 恐龙模式 (贪吃蛇) 自动化脚本 (dinosaur_farmer_v4.py)
- #
- # 版本 4: 移除了所有 """...""" 形式的文档字符串。
- #
- # 策略:
- # 1. 保证在调用 measure() 时,无人机正位于一个苹果上。
- # 2. 采用动态寻路:每移动一步都重新计算到目标的最优路径,以应对
- # 自身尾巴(移动障碍物)的变化。
- # 3. 自动完成整个游戏、收获、重玩的循环。
- #
- # 严格遵守所有编程限制。
- # ==============================================================================
- from utils import *
- # ------------------------------------------------------------------------------
- # 配置与常量
- # ------------------------------------------------------------------------------
- START_X = 0
- START_Y = 0
- DIRECTION_VECTORS = {
- North: (0, 1),
- East: (1, 0),
- South: (0, -1),
- West: (-1, 0)
- }
- OPPOSITE_DIRECTIONS = {
- North: South,
- South: North,
- East: West,
- West: East
- }
- # ------------------------------------------------------------------------------
- # 辅助函数
- # ------------------------------------------------------------------------------
- def manhattan_distance(x1, y1, x2, y2):
- return abs(x1 - x2) + abs(y1 - y2)
- # 准备开始一轮恐龙游戏,结束时无人机应位于第一个苹果上。
- def setup_game():
- quick_print("正在准备新一轮的恐龙游戏...")
- clear()
- move_to(START_X, START_Y)
- # 假设每次生成苹果需要1个仙人掌
- if num_items(Items.Cactus) < get_world_size() * get_world_size():
- quick_print("警告: 仙人掌数量可能不足以填满整个地图。")
- # 装备帽子,这会在无人机下方生成第一个苹果
- quick_print("装备恐龙帽...")
- change_hat(Hats.Dinosaur_Hat)
- # 检查苹果是否成功生成
- if get_entity_type() != Entities.Apple:
- quick_print("错误:装备帽子后未生成苹果。")
- return False
- return True
- # ------------------------------------------------------------------------------
- # 核心寻路算法
- # ------------------------------------------------------------------------------
- # 全局变量,用于在递归调用中共享状态
- path_solution = []
- visited_grid = []
- apple_x = 0
- apple_y = 0
- def find_path_recursive(current_x, current_y):
- global path_solution
- global visited_grid
- global apple_x
- global apple_y
- if current_x == apple_x and current_y == apple_y:
- return True
- visited_grid[current_y][current_x] = True
- possible_moves = []
- directions_to_check = [North, East, South, West]
- for direction in directions_to_check:
- dx, dy = DIRECTION_VECTORS[direction]
- next_x, next_y = current_x + dx, current_y + dy
- world_size = get_world_size()
- if 0 <= next_x < world_size and 0 <= next_y < world_size:
- if not visited_grid[next_y][next_x]:
- dist = manhattan_distance(next_x, next_y, apple_x, apple_y)
- possible_moves.append([dist, direction])
- n = len(possible_moves)
- for i in range(n):
- for j in range(0, n - i - 1):
- if possible_moves[j][0] > possible_moves[j+1][0]:
- temp = possible_moves[j]
- possible_moves[j] = possible_moves[j+1]
- possible_moves[j+1] = temp
- for move_info in possible_moves:
- direction = move_info[1]
- path_solution.append(direction)
- dx, dy = DIRECTION_VECTORS[direction]
- if find_path_recursive(current_x + dx, current_y + dy):
- return True
- path_solution.pop()
- return False
- def find_path_to_apple(start_x, start_y, target_x, target_y, snake_body):
- global path_solution
- global visited_grid
- global apple_x
- global apple_y
- apple_x = target_x
- apple_y = target_y
- path_solution = []
- world_size = get_world_size()
- visited_grid = []
- for _ in range(world_size):
- row = []
- for _ in range(world_size):
- row.append(False)
- visited_grid.append(row)
- # 蛇的身体是障碍物
- for segment in snake_body:
- visited_grid[segment[1]][segment[0]] = True
- if find_path_recursive(start_x, start_y):
- return path_solution
- else:
- return None
- # ------------------------------------------------------------------------------
- # 主游戏逻辑
- # ------------------------------------------------------------------------------
- def play_dinosaur_game():
- if not setup_game():
- change_hat(Hats.Green_Hat) # 如果设置失败,换回绿帽以重置状态
- return
- snake_body = [[get_pos_x(), get_pos_y()]]
- game_over = False
- while not game_over:
- # 此时无人机正位于一个苹果上,安全调用 measure()
- measured_pos = measure()
- if not measured_pos:
- quick_print("错误: measure() 未返回位置。可能是游戏结束的信号。")
- break
- target_x, target_y = measured_pos
- quick_print("下一个苹果在: (" + str(target_x) + ", " + str(target_y) + ")")
- # 第一次寻路,规划从当前苹果到下一个苹果的完整路径
- head_x, head_y = snake_body[0]
- path = find_path_to_apple(head_x, head_y, target_x, target_y, snake_body)
- if not path:
- quick_print("被困住了!找不到初始路径。游戏结束。")
- break
- # 吃掉当前苹果并开始移动
- # 移动第一步,意味着“吃掉”了脚下的苹果,尾巴需要增长
- direction_to_move = path[0]
- if move(direction_to_move):
- new_head_x, new_head_y = get_pos_x(), get_pos_y()
- snake_body.insert(0, [new_head_x, new_head_y])
- # 尾巴增长:不执行 snake_body.pop()
- quick_print("吃到苹果!尾巴长度: " + str(len(snake_body)))
- else:
- quick_print("错误:初始移动失败。")
- break
- # 循环移动,直到到达目标苹果
- while get_pos_x() != target_x or get_pos_y() != target_y:
- # 动态寻路:每一步都重新计算路径,因为蛇身在移动
- head_x, head_y = snake_body[0]
- current_path = find_path_to_apple(head_x, head_y, target_x, target_y, snake_body)
- if not current_path:
- quick_print("移动途中被困住!找不到路径。游戏结束。")
- game_over = True
- break
- direction_to_move = current_path[0]
- if move(direction_to_move):
- new_head_x, new_head_y = get_pos_x(), get_pos_y()
- snake_body.insert(0, [new_head_x, new_head_y])
- snake_body.pop() # 正常移动,尾巴前进
- else:
- quick_print("错误:中途移动失败,路径规划可能出错。")
- game_over = True
- break
- if game_over:
- break
- # 检查是否已满
- if len(snake_body) >= get_world_size() * get_world_size():
- quick_print("恭喜!填满了整个地图!")
- break
- # 游戏结束,收获骨头
- tail_length = len(snake_body)
- bones_earned = tail_length * tail_length
- quick_print("最终尾巴长度: " + str(tail_length))
- quick_print("预计获得骨头: " + str(bones_earned))
- quick_print("正在更换帽子以收获骨头...")
- change_hat(Hats.Green_Hat) # 换掉帽子以收获
- quick_print("收获完成!")
- # ==============================================================================
- # 主函数
- # ==============================================================================
- def main():
- while True:
- play_dinosaur_game()
- quick_print("======== 完成一轮恐龙挑战,准备开始下一轮... ========")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment