Để tóm gọn và đỡ tốn thời gian, giải thưởng thuộc về Nhâm Xuân Nam (cũng là người thắng giải http://www.vithon.org/2010/06/03/kết-quả-cuộc-thi-giải-toan-bằng-python).
Sau đây là bài fire_in_the_hole.py của Nhâm Xuân Nam:
'''
Created on Dec 15, 2010
@author: namnx
'''
import entity
import random
import inspect
class HolePlayer(entity.Player):
def name_ship(self, ship):
n = repr(ship.__class__)
return n[n.index('.') + 1 : -2]
def on_hit(self, x, y):
# dont care
pass
def orient_ship(self, ship):
return entity.HORIZONTAL
def place_ship(self, ship):
while True:
x = random.randint(0, self.ocean.width - 1)
y = random.randint(0, self.ocean.height - 1)
if not self.t_ocean:
self.t_ocean = entity.Ocean(self.ocean.width, self.ocean.height)
try:
ship.place(self.t_ocean, x, y)
return (x, y)
except ValueError:
pass
def lock_missile(self, ship):
opponent_ships = self.get_opponent_ships()
if self.step < 4:
if ship.__class__ == entity.Destroyer:
for s in opponent_ships:
if (s.__class__ == ship.__class__) and (s.orientation == ship.orientation):
break
self.step += 1
return (s.x, s.y)
for s in opponent_ships:
if s.__class__ == ship.__class__:
break;
self.step += 1
return (s.x, s.y)
else:
for s in opponent_ships:
if s.__class__ == entity.MissileCruiser:
break
if ship.__class__ == entity.MissileCruiser:
if s.orientation == entity.HORIZONTAL:
return (s.x-2, s.y)
else:
return (s.x, s.y-2)
else:
if s.orientation == entity.HORIZONTAL:
return (s.x+2, s.y)
else:
return (s.x, s.y+2)
def get_opponent_ships(self):
frames = inspect.stack()
for frame in frames:
if frame[3] == '__turn':
break;
gameObj = frame[0].f_locals['self']
for i in range(len(gameObj.players)):
if gameObj.players[i].__class__ != self.__class__:
break
return gameObj.ships[i]
def entry(name):
p = HolePlayer(name)
p.t_ocean = None
p.step = 0
return p
Xin chúc mừng bạn Xuân Nam.