Experimental Python-based AI bot framework
[tennix.git] / defaultbot.py
blob720dbcd73e7148511d25a01aafe0bcdd3fe90fe3
2 # Experimental implementation of a Python-based Tennix AI Bot
4 import random
5 import time
6 import threading
7 import math
9 (INPUT_AXIS_X, INPUT_AXIS_Y) = range(2)
10 (INPUT_KEY_HIT, INPUT_KEY_TOPSPIN, INPUT_KEY_SMASH) = range(3)
12 __name__ = 'John Python'
14 class DumbPythonBot(object):
15 SCREEN_MID_Y = 480./2.
16 DESIRED_POWER = { INPUT_KEY_HIT: 90, INPUT_KEY_TOPSPIN: 70, INPUT_KEY_SMASH: 70 }
18 def __init__(self):
19 self.t = None
20 self.cancelled = False
21 self.ball_x = 0.0
22 self.ball_y = 0.0
23 self.player_x = 0.0
24 self.player_y = 0.0
25 self.power = 0.0
26 self.power_locked = False
27 self.current_tactic = INPUT_KEY_HIT
28 self.desired_power = self.DESIRED_POWER[self.current_tactic]
30 def blubb(self):
31 i = 0
32 while not self.cancelled:
33 time.sleep(2)
34 self.current_tactic = random.randint(INPUT_KEY_HIT, INPUT_KEY_SMASH)
35 self.desired_power = self.DESIRED_POWER[self.current_tactic]*(1.2-0.4*random.random())
36 print 'determined new tactic:', self.current_tactic
37 i += 1
38 print 'thread cancelled'
40 def loaded(self):
41 print __name__, 'has been loaded'
42 self.t = threading.Thread(target=self.blubb)
43 self.t.start()
45 def unloaded(self):
46 print __name__, 'has been unloaded'
47 self.cancelled = True
48 if self.t is not None:
49 self.t.join()
51 def get_key(self, key_id):
52 if math.sqrt((self.player_x - self.ball_x)**2 + (self.player_y - self.ball_y)**2) > 150:
53 return False
55 if self.power > self.desired_power and random.randint(0, 3)==0:
56 self.power_locked = True
57 return False
58 if key_id == self.current_tactic and not self.power_locked:
59 #if abs(self.player_x - self.ball_x) < 10 and self.power > self.desired_power:
60 return abs(self.player_x - self.ball_x) > 5 and self.power < self.desired_power + 0.3*random.random()
61 else:
62 return False
64 def get_axis(self, axis_id):
65 desired_position = self.ball_y - 20. * (self.ball_y - self.SCREEN_MID_Y) / self.SCREEN_MID_Y
66 if axis_id == INPUT_AXIS_Y and abs(desired_position - self.player_y) > 5:
67 return max(-1.0, min(1.0, desired_position - self.player_y))
69 return 0.0
71 def ball_moved(self, x, y):
72 self.ball_x = x
73 self.ball_y = y
75 def player_moved(self, x, y):
76 self.player_x = x
77 self.player_y = y
79 def power_changed(self, power):
80 if power < max(0.05, self.desired_power - 0.8):
81 self.power_locked = False
82 self.power = power
85 bot = DumbPythonBot()
87 loaded = bot.loaded
88 unloaded = bot.unloaded
89 get_key = bot.get_key
90 get_axis = bot.get_axis
91 set_ball_coords = bot.ball_moved
92 set_player_coords = bot.player_moved
93 set_player_power = bot.power_changed