1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| import requests from collections import deque
GRID_WIDTH = 20 GRID_HEIGHT = 20 DIRECTIONS = ['UP', 'DOWN', 'LEFT', 'RIGHT'] MOVES = { 'UP': (0, -1), 'DOWN': (0, 1), 'LEFT': (-1, 0), 'RIGHT': (1, 0) }
session = requests.Session()
base_url = 'http://eci-2zeg4gjm1ccotm7csi62.cloudeci1.ichunqiu.com:5000/'
headers = { 'Accept-Language': 'zh-CN,zh;q=0.9', 'User-Agent': 'Mozilla/5.0', 'Content-Type': 'application/json', 'Accept': '*/*', 'Origin': base_url, 'Referer': base_url + '/', 'Accept-Encoding': 'gzip, deflate, br', 'Connection': 'keep-alive', }
cookies = { 'session': 'eyJ1c2VybmFtZSI6Int7MSAxfX0ifQ.ZyZPqA.r1I5UHgWZtPRZBpdaxzAJE9-Vg4' }
def send_move(direction): data = {"direction": direction} response = session.post(base_url + '/move', headers=headers, cookies=cookies, json=data) if response.status_code == 200: print("服务器返回的JSON:", response.text) return response.json() else: print("Error:", response.status_code) return None
def bfs(snake, food, grid_width, grid_height): head = tuple(snake[0]) snake_body = set(tuple(pos) for pos in snake) queue = deque() queue.append((head, [])) visited = set() visited.add(head) while queue: current_pos, path = queue.popleft() if current_pos == tuple(food): return path for direction, (dx, dy) in MOVES.items(): new_x = current_pos[0] + dx new_y = current_pos[1] + dy new_pos = (new_x, new_y) if 0 <= new_x < grid_width and 0 <= new_y < grid_height: if new_pos not in snake_body and new_pos not in visited: visited.add(new_pos) queue.append((new_pos, path + [direction])) return None
def get_next_positions(snake, grid_width, grid_height): head_x, head_y = snake[0] possible_moves = {} for direction, (dx, dy) in MOVES.items(): new_x = head_x + dx new_y = head_y + dy if 0 <= new_x < grid_width and 0 <= new_y < grid_height: if [new_x, new_y] not in snake: possible_moves[direction] = [new_x, new_y] return possible_moves
state = send_move('RIGHT') if not state: print("无法开始游戏。") exit()
food = state['food'] snake = state['snake']
print("开始游戏。")
while True: path = bfs(snake, food, GRID_WIDTH, GRID_HEIGHT) if path: next_move = path[0] else: possible_moves = get_next_positions(snake, GRID_WIDTH, GRID_HEIGHT) if possible_moves: next_move = list(possible_moves.keys())[0] else: print("没有可移动的位置,游戏结束。") break state = send_move(next_move) if not state: print("无法从服务器获取游戏状态。") break if state.get('status') != 'ok': print("游戏结束:", state) break food = state['food'] snake = state['snake'] print("移动方向:", next_move, "当前得分:", state['score'])
|