Last active
September 20, 2019 10:06
-
-
Save onjin/17a9f2b9468eeeb93ffb to your computer and use it in GitHub Desktop.
pysnake dojo pyconpl 2014
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# to run snake you need an engine: https://bitbucket.org/Gandi24/pysnake/src/master/ | |
# to watch this snake in action check youtube https://www.youtube.com/watch?v=gc2wpQp95TA (red one) | |
def move(snake1=None, snake2=None, food=None, data=None, board_width=None, board_height=None): # NOQA | |
from math import sqrt | |
from collections import namedtuple | |
Point = namedtuple('Point', 'x y') | |
def d(point): | |
return Point(point.x, point.y + 1) | |
def u(point): | |
return Point(point.x, point.y - 1) | |
def l(point): | |
return Point(point.x - 1, point.y) | |
def r(point): | |
return Point(point.x + 1, point.y) | |
waysf = { | |
'd': d, | |
'u': u, | |
'l': l, | |
'r': r, | |
} | |
ways = waysf.keys() | |
# avoid walls | |
if d(snake1.head).y == board_height: | |
ways.remove('d') | |
if u(snake1.head).y == -1: | |
ways.remove('u') | |
if l(snake1.head).x == -1: | |
ways.remove('l') | |
if r(snake1.head).x == board_width: | |
ways.remove('r') | |
# avoid self | |
ways = filter(lambda way: waysf[way](snake1.head) not in snake1.body, ways) | |
# avoid other | |
ways = filter(lambda way: waysf[way](snake1.head) not in snake2.body, ways) | |
def distance(head, other): | |
return abs(head.x - other.x) + abs(head.y - other.y) | |
mine_distance = distance(snake1.head, food) | |
other_distance = distance(snake2.head, food) | |
middle = Point(board_width / 2, board_height / 2) | |
if mine_distance > other_distance: | |
target = middle | |
else: | |
target = food | |
mine_distance = distance(snake1.head, target) | |
tail_distance = distance(snake1.body[-1], target) | |
if mine_distance > tail_distance: | |
target = snake1.body[-1] | |
# ways to target | |
ways = sorted( | |
ways, key=lambda way: distance(waysf[way](snake1.head), target) | |
) | |
if not len(ways): | |
return 'u' # never give up, fixme: lost less | |
return ways[0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment