本文整理汇总了Python中board.Board类的典型用法代码示例。如果您正苦于以下问题:Python Board类的具体用法?Python Board怎么用?Python Board使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Board类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
class Game:
moves = 0
board = None
def __init__(self, board_size):
"""
Let's create the game
"""
self.board = Board(board_size)
def is_ended(self):
"""
Check if the game is ended
"""
total = sum([x for row in self.board.grid for x in row])
return total == 0
def won(self):
"""
Check if the first player won
"""
return self.is_ended() and self.moves % 2 == 1
def possible_moves(self):
"""
Collect all possible moves on the corrent game board
"""
x = 0
y = 0
moves = []
while(x > self.board.size):
while(y > self.board.size):
if self.board[x][y] == 0:
continue
moves = moves + self.spot_possible_moves(x, y)
y = y + 1
x = x + 1
return moves
def spot_possible_moves(self, x, y):
width = 0
height = 0
x_increment = 1
moves = []
while(width < x):
y_increment = 1
while(height < self.board.size - y):
height = height + y_increment
y_increment = y_increment + 1
moves = moves + [(x, y), width, height]
width = math.pow(x_increment, 2)
x_increment = x_increment + 1
return moves
def valid_move(self, move):
pass
def move(self):
self.board.flip((4, 1), 4, 2)
self.move = self.move + 1
示例2: main
def main():
parser = argparse.ArgumentParser(description='Print Trello.com JSON file')
parser.add_argument('-f', '--format', choices=["text", "markdown", "html"],
default="markdown")
parser.add_argument('source', metavar="json_file")
parser.add_argument('-v', '--version', action='version',
version='TrelloPrint ' + RELEASE)
args = parser.parse_args()
filename = args.source
with open(filename, "r") as f:
data = json.load(f)
b = Board(data)
if (args.format == "text"):
print(b)
exit
md_string = b.get_md()
if (args.format == "markdown"):
print(md_string)
elif (args.format == "html"):
with open(TEMP_FILE_NAME, "w") as temp_fd:
temp_fd.write(md_string)
os.system("markdown " + TEMP_FILE_NAME)
os.remove(TEMP_FILE_NAME)
示例3: __init__
class FanoronaGame:
"""This class represents the game as is it."""
def __init__(self):
"""Ctor"""
self.board = Board()
def start(self):
"""Starts the game with GUI"""
gui = GUI(self.board)
gui.start_main_loop()
def start_text(self):
"""Starts the game in text mode"""
black = False # white begin the game
while not self.board.game_is_finished():
self.board.print_board()
if black:
prompt = "black> "
else:
prompt = "white> "
move = raw_input(prompt)
self.board.move_piece(move, black)
black = not black
示例4: testComputeBuildValue
def testComputeBuildValue(self):
b = Board()
gc = gamecontroller.GameController(b)
gc.turnIndex = 2
p0, p1, p2, p3 = gc.players
ai0, ai1, ai2, ai3 = [gc.ais[i] for i in range(4)]
column = BuildingColumn(Resources.Red, [
BuildingCard(5, Resources.Red, Resources.Glass),
BuildingCard(2, Resources.Red, Resources.Bank),
BuildingCard(3, Resources.Red, Resources.Red),
BuildingCard(3, Resources.Red, Resources.Red),
])
b.buildingColumn[Resources.Red] = column
column.setRoof(RoofCard(4, 4))
b.buildingColumn[Resources.Green].setRoof(FinalRoofCard(10))
p0.amount = 100
p0.addCard(ShareCard(Resources.Red, 2))
p0.addCard(WorkforceCard(0, 1))
b.advanceShareScore(Resources.Red, 17)
valueBefore = b.getShareValueForScore(maxShareScore[2][17])
valueAfter = b.getShareValueForScore(maxShareScore[2][21])
expected = 2 * (valueAfter - valueBefore) + 3 * valueAfter + 4 * 3 - 20
self.assertEqual(expected, ai0.computeBuildValue(gc, Resources.Red))
self.assertEqual(-1000, ai0.computeBuildValue(gc, Resources.Green))
p0.amount = 10
self.assertEqual(-1000, ai0.computeBuildValue(gc, Resources.Red))
示例5: test_king_is_checked
def test_king_is_checked(self):
board = Board()
board[0, 0].piece = King(board.black)
board[1, 1].piece = Queen(board.white)
board[7, 7].piece = King(board.white)
self.assertTrue(board.king_is_checked(board.black))
self.assertFalse(board.king_is_checked(board.white))
示例6: test_flagged_neighbours
def test_flagged_neighbours(self):
board = Board(3, 3)
board.flagged.add((0, 0))
board.flagged.add((1, 0))
self.assertEqual(board.flagged_neighbours((0, 1)), 2)
self.assertEqual(board.flagged_neighbours((1, 1)), 2)
self.assertEqual(board.flagged_neighbours((2, 0)), 1)
示例7: TestRandomPlacing
class TestRandomPlacing(unittest.TestCase):
"""Test behaviour of random function."""
def setUp(self):
"""Set up a board."""
self.board = Board(5, 5)
def tearDown(self):
"""Clean up."""
self.board = None
def testRandomPlacingPatrol(self):
"""Test the case when random placing patrol."""
result = self.board.random_placing('p0', 2, k=0)
self.assertEqual(result, "Done")
def testRandomDestroyer(self):
"""Test the case when random placing destroyer."""
result = self.board.random_placing('d0', 3, k=0)
self.assertEqual(result, "Done")
def testRandomPlacingSubmarine(self):
"""Test the case when random placing submarine."""
result = self.board.random_placing('s0', 4, k=0)
self.assertEqual(result, "Done")
def testRandomPlacingAircraft(self):
"""Test the case when random placing aircraft."""
result = self.board.random_placing('a0', 5, k=0)
self.assertEqual(result, "Done")
示例8: computeRect
def computeRect(self):
"""also adjust the scale for maximum usage of space"""
Board.computeRect(self)
sideRect = self.player.front.boundingRect()
boardRect = self.boundingRect()
scale = (sideRect.width() + sideRect.height()) / (boardRect.width() - boardRect.height())
self.setScale(scale)
示例9: init_pooo
def init_pooo(init_string):
"""Initialise le robot pour un match
:param init_string: instruction du protocole de communication de Pooo (voire ci-dessous)
:type init_string: chaîne de caractères (utf-8 string)
INIT<matchid>TO<#players>[<me>];<speed>;\
<#cells>CELLS:<cellid>(<x>,<y>)'<radius>'<offsize>'<defsize>'<prod>,...;\
<#lines>LINES:<cellid>@<dist>OF<cellid>,...
<me> et <owner> désignent des numéros de 'couleur' attribués aux joueurs. La couleur 0 est le neutre.
le neutre n'est pas compté dans l'effectif de joueurs (<#players>).
'...' signifie que l'on répète la séquence précédente autant de fois qu'il y a de cellules (ou d'arêtes).
0CELLS ou 0LINES sont des cas particuliers sans suffixe.
<dist> est la distance qui sépare 2 cellules, exprimée en... millisecondes !
/!\ attention: un match à vitesse x2 réduit de moitié le temps effectif de trajet d'une cellule à l'autre par rapport à l'indication <dist>.
De manière générale temps_de_trajet=<dist>/vitesse (division entière).
:Example:
"INIT20ac18ab-6d18-450e-94af-bee53fdc8fcaTO6[2];1;3CELLS:1(23,9)'2'30'8'I,2(41,55)'1'30'8'II,3(23,103)'1'20'5'I;2LINES:[email protected],[email protected]"
"""
print("INIT DU MATCH");
global MATCH_AI ;
(nbPlayers,playerId,l_n,l_e) = potocole.initStringToAI(init_string);
print("NUMERO DU JOUEUR :",playerId);
board = Board(nbPlayers,l_n);
print("EDGES :" ,l_e);
board.addEdges(l_e);
MATCH_AI = AI(board,playerId) ;
示例10: get_successor_states
def get_successor_states(self, state, mark):
successors = []
for move in state.get_valid_moves():
successor = Board(copy(state.board))
successor.move(mark, move)
successors.append((move, successor))
return successors
示例11: Ant
class Ant(object):
def __init__(self, n):
self.board = Board(n)
self.i = int(n) / 2
self.j = int(n) / 2
self.d = Direction()
def step(self):
if self.board[self.i, self.j]: # Square is black
self.d.turn_right()
else: # Square is white
self.d.turn_left()
self.board.flip(self.i, self.j)
self._move_forward()
def _move_forward(self):
i, j = self.i, self.j
board = self.board
if self.d == 'up':
self.i, self.j = board.move_up(i, j)
elif self.d == 'right':
self.i, self.j = board.move_right(i, j)
elif self.d == 'down':
self.i, self.j = board.move_down(i, j)
else:
self.i, self.j = board.move_left(i, j)
def __repr__(self):
s = 'Ant(i={}, j={})'.format(self.i, self.j)
return s + '\n' + str(self.board)
示例12: main
def main():
board = Board(30,30)
a = Entity( 20, 20, "A", board)
b = Entity( 15, 15, "B", board)
a()
b()
os.system('clear')
board.display()
print("[ w:up a:left s:down d:right q:quit ]")
print("[ A:you .:travelled _:untravelled x:" + str(a.x) + " y:" + str(a.y) + " ]")
while True:
key = getch()
if key == 'w':
a.move_direction('north')
if key == 'a':
a.move_direction('west')
if key == 's':
a.move_direction('south')
if key == 'd':
a.move_direction('east')
if key == 'q':
break
os.system('clear')
board.display()
print("[ w:up a:left s:down d:right q:quit ]")
print("[ A:you .:travelled _:untravelled x:" + str(a.x) + " y:" + str(a.y) + " ]")
示例13: testActionBuild
def testActionBuild(self):
b = Board()
gc = GameController(b)
p0, p1, p2, p3 = gc.players
# Doctor the board
for resource in FirmsOrGoods:
b.revenues[resource] = 0
column = BuildingColumn(Resources.Red, [
BuildingCard(5, Resources.Red, Resources.Glass),
BuildingCard(6, Resources.Red, Resources.Iron),
BuildingCard(5, Resources.Red, Resources.Glass),
BuildingCard(2, Resources.Red, Resources.Bank),
BuildingCard(3, Resources.Red, Resources.Red),
BuildingCard(3, Resources.Red, Resources.Red),
])
b.buildingColumn[Resources.Red] = column
b.roofStack = [RoofCard(5, 7, 4)]
column.setRoof(RoofCard(4, 4, 2))
p2.amount = 20
gc.actionBuild(p2, Resources.Red)
self.assertEqual(0, p2.amount)
self.assertEqual(4, p2.getLevel())
self.assertIn(ShareCard(Resources.Red, 3), p2.cards)
self.assertEqual(10, b.revenues[Resources.Red])
self.assertEqual(5, b.revenues[Resources.Glass])
self.assertEqual(7, b.shareScore[Resources.Red])
self.assertEqual(5, column.length())
self.assertEqual(6, column.getLevel())
示例14: test_gameplay_second_player
def test_gameplay_second_player(self):
"""
Test that the AI picks the middle square as quickly as possible when playing second
"""
board = Board()
board.add_mark(0, "O")
self.assertEquals(4, board.find_next_move("X"))
示例15: ConnectFour
class ConnectFour(object):
def __init__(self, cell_list=None, columns=7, column_size=6, human=False, level='easy'):
self.adversaries = [HumanPlayer(), HumanPlayer(False, 'O')]
if not human:
self.adversaries[1] = ComputerPlayer(level=level)
self.board = Board()
def read_player_move(self, ):
return self.current_player.move(self.board)
def play(self, ):
self.current_player = [player for player in self.adversaries
if player.turn is True][0]
while True:
print self.board
move = self.read_player_move()
if move in ('q', 'Q'):
sys.exit(0)
self.board.set_cell(move, self.current_player.name)
over = self.board.game_over()
if over:
break
self.current_player = self.get_next_player()[0]
print self.board
print "Cat's Game!" if over == 'tie' else \
self.current_player.name + " won the game!"
def get_next_player(self, ):
for player in self.adversaries:
player.turn = not player.turn
return [player for player in self.adversaries if player.turn is True]