-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbots.py
More file actions
68 lines (65 loc) · 2.6 KB
/
bots.py
File metadata and controls
68 lines (65 loc) · 2.6 KB
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
import random, math
#Player Classes
#Each has method for making move, these take care of updating the list describing the piles.
# As well as storing num of players and names
def get_nim_sum(l):
"Returns the nim-sum/bitwise xor result of an iterable object."
sum = 0
for x in l:
sum ^= x
return sum
def generate_board(max_length = 10, max_pile_height = 20):
"Generates a random starting board."
length = random.randint(2,max_length)
piles = [random.randint(1,max_pile_height) for i in range(length)]
return piles
class Player:
"Super class to the objects used in games. Counts wins and instances."
wins = 0
instances = 0
def __init__(self):
"Inits a player. Keeps of track of the number of active players."
type(self).instances += 1
def __del__(self):
"Reduces number of players when one is deleted."
type(self).instances -= 1
class RandomBot(Player):
"Computer Player making moves completely at random"
name = "Dum-Bot"
def make_move(self, piles, dis=None, board=None, board_buttons=None, board_header=None, logo=None):
"""Attempts to make a move chosen at random.
Returns True if there exists a valid move and False otherwise."""
l = [i for i in range(len(piles)) if piles[i]]
if not l:
return False
ind = random.choice(l)
piles[ind] = random.randint(0,piles[ind]-1)
if board:
board.piles[ind].number = piles[ind]
board.piles[ind].update_marker_list()
return True
class SmartBot(Player):
"Computer Player always making a winning move in case it's possible"
name = "Smart-Bot"
def make_move(self, piles, dis=None, board=None, board_buttons=None, board_header=None, logo=None):
"""Attempts to make a move. Optimal if there exists such a move.
Returns True if there exists a valid move and False otherwise."""
nim_sum = get_nim_sum(piles)
def done(ind, num):
piles[ind] = num
if board:
board.piles[ind].number = piles[ind]
board.piles[ind].update_marker_list()
#No winning move. Keep stalling.
if not nim_sum:
for i, height in enumerate(piles):
if height:
done(i, height-1)
return True
return False
#Find winning move
for i, height in enumerate(piles):
opt = height^nim_sum
if opt < height:
done(i, opt)
return True