-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogic.py
99 lines (85 loc) · 2.79 KB
/
logic.py
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
import random
def extract_snakes(data):
snakes = []
for snake in data["board"]["snakes"]:
for loc in snake["body"]:
snakes.append([loc["x"], loc["y"]])
return snakes
def extract_snakes_head(data):
snake_heads = []
for snake in data["board"]["snakes"]:
if snake["id"]!=data["you"]["id"]:
head = snake["head"]
snake_heads.append([head["x"], head["y"]])
return snake_heads
def distance(a,b):
return abs(a[0]-b[0]) + abs(a[1]-b[1])
def assign_move(move):
if move==[0,1]:
return "up"
elif move==[0,-1]:
return "down"
elif move==[1,0]:
return "right"
elif move==[-1,0]:
return "left"
def check_wall(board_dim, x,y):
# print("wall: ",board_dim,x,y)
X,Y = board_dim
if 0<=x<X and 0<=y<Y:
return True
return False
def check_other_snake(snakes,snake_heads,x, y):
# print("Snakes: ", snakes, x, y)
for snake in snakes:
if snake[0]==x and snake[1]==y:
return False
for head in snake_heads:
if distance(head,[x,y])<=1:
return False
return True
def return_value(move,shout):
return {
"move":assign_move(move),
"shout":shout
}
def move(data):
board_dim = [data['board']["height"],data['board']['width']]
snakes = extract_snakes(data)
snake_heads = extract_snakes_head(data)
food_temp = data["board"]["food"]
foods = []
for food in food_temp:
foods.append([food["x"],food["y"]])
you = data["you"]
you_head = [you["head"]["x"], you["head"]["y"]]
you_body = you["body"]
you_length = you["length"]
# Choose a random direction to move in
directions = [[0,1], [0,-1], [-1,0], [1,0]]
last_call = []
possible_moves = []
for move in directions:
x,y = you_head[0]+move[0], you_head[1]+move[1]
# print(f"MOVE: {move}")
wall_check = check_wall(board_dim,x,y)
snake_check = check_other_snake(snakes,snake_heads,x,y)
print(wall_check,snake_check)
if wall_check and snake_check:
possible_moves.append(move)
if wall_check:
last_call.append(move)
for move in possible_moves:
x,y = you_head[0]+move[0], you_head[1]+move[1]
for food in foods:
if distance([x,y],food)==0:
print(f"FINAL MOVE: {move}")
return return_value(move,"POSSBILE: " + " ".join(f"[{x[0]} {x[1]}]" for x in possible_moves))
if len(possible_moves)>0:
move = random.choice(possible_moves)
print(f"RANDOM POSSBILE MOVE: {move} out of {possible_moves}")
return {"move": assign_move(move)}
else:
move = random.choice(last_call)
print(f"RANDOM MOVE: {move}")
return {"move": assign_move(move)}