本文整理汇总了Python中board.Board.display方法的典型用法代码示例。如果您正苦于以下问题:Python Board.display方法的具体用法?Python Board.display怎么用?Python Board.display使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类board.Board
的用法示例。
在下文中一共展示了Board.display方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import display [as 别名]
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) + " ]")
示例2: main
# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import display [as 别名]
def main():
board = Board()
board.lastmove = 'x'
turn = 'o'
while not board.check_win(board.lastmove):
board.display()
got_move = False
print("It's " + turn + "'s turn.")
while not got_move:
movex = raw_input(" Enter row number (0-2): ")
movey = raw_input(" Enter column number (0-2): ")
try:
movex = int(movex)
movey = int(movey)
got_move = True
except ValueError:
got_move = False
board.move(movex, movey, turn)
if board.lastmove == 'o':
turn = 'x'
elif board.lastmove == 'x':
turn = 'o'
print('')
# For posterity.
board.display()
示例3: start
# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import display [as 别名]
def start(self):
print "Welcome to Tic Tac Toe\n"
board = Board()
turn = 0
while not board.is_end_game(self.players):
board.display()
print "_________________\n"
active = self.players[turn % len(self.players)]
board.claim(active, active.get_valid_move(board))
turn += 1
示例4: game
# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import display [as 别名]
def game(white_engine, black_engine, game_time=300.0, verbose=False):
""" Run a single game. Raises RuntimeError in the event of time expiration.
Raises LookupError in the case of a bad move. The tournament engine must
handle these exceptions. """
# TODO: Figure out a method of introspection to figure out which player
# raised an exception
# TODO: Make this a generator or coroutine to support multithreading.
# Iteration stops at final board, makes for simple GUI on top of this.
#initialize variables
board = Board()
time = { -1 : game_time, 1 : game_time }
engine = { -1 : black_engine, 1 : white_engine }
# do rounds
for move_num in range(60):
moves = []
for color in [-1, 1]:
start_time = times()[0] #user time elapsed
move = get_move(board, engine[color], color, move_num)
end_time = times()[0]
time[color] -= (end_time - start_time)
logging.debug("Player %(color)d has %(time)f seconds remaining" %\
{'color' : color, 'time' : time[color]})
if time[color] < 0:
raise RuntimeError(
"Player %(color)d literally has a RuntimeError"
% {'color' : color })
# make a move, otherwise pass
if move is not None:
board.execute_move(move, color)
moves.append(move)
logging.info(
"Round %(move_num)2d: Player %(color)d flipped %(move)s"
% { 'color' : color,
'move' : move_string(move),
'move_num' : move_num })
if verbose:
board.display()
#test for game over
if not moves:
logging.info("No legal moves remaining. The game is over.")
break
return board
示例5: __init__
# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import display [as 别名]
class Interaction:
def __init__(self, width, height):
self.width = width
self.height = height
# Used to map numbers to locations for the user
self.number_board = Board(width, height)
for x in range(0, width):
for y in range(0, height):
self.number_board.place_tile(self.x_y_to_number(x, y), x, y)
def get_move(self, turn, board):
print("Current board:")
board.display()
print("Board locations:")
self.number_board.display()
while True:
move = input("Where would " + str(turn) + " like to move? ")
move_num = -1
try:
move_num = int(move)
x, y = self.number_to_x_y(move_num)
if move_num < 0 or move_num > self.width * self.height - 1:
print("Must be a proper location number.")
elif board.is_occupied(x, y):
print("That location is already occupied.")
else:
return (x, y)
except:
print("Must be a proper location number.")
def display_winner(self, board, player_won):
print("Final board:")
board.display()
if player_won:
print("Congratuations! You are the winner! :)")
else:
print("Sorry, the computer has bested you. :(")
def display_cat_game(self, board):
print("Final board:")
board.display()
print("It was a tie (CAT game)! :|")
def number_to_x_y(self, num):
return (num % self.width, num // self.width)
def x_y_to_number(self, x, y):
return y * self.width + x
示例6: run_game
# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import display [as 别名]
def run_game(model, record_file=None):
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()
board = Board(model,300)
if record_file != None:
record = True
else:
record = False
if record:
record_file.write("state,action,reward,total\n")
total = 0
while True:
time_passed = clock.tick(50)
state = board.model.current_state
action = None
reward = None
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
action = 0
reward = board.actionA()
elif event.key == pygame.K_LEFT:
action = 1
reward = board.actionB()
elif event.key == pygame.K_UP:
action = 2
reward = board.actionC()
elif event.key == pygame.K_DOWN:
action = 3
reward = board.actionD()
if record and reward != None:
total += reward
record_file.write(str(state.get_id())+","+str(action)+","+str(reward)+","+str(total)+"\n")
screen.fill(BG_COLOR)
board.display(screen)
pygame.display.flip()
示例7: play
# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import display [as 别名]
def play(self, verbose=True):
# BEGIN
pickers_word = self.picker.pick_word()
secret = SecretWord(pickers_word)
board = Board(secret)
while board.done() == False:
for guesser in self.guessers:
if verbose:
board.display()
self.winner = guesser
attempt = guesser.guess(board)
board.guess(attempt)
while len(secret.match(attempt)) > 0 and board.done() == False:
attempt = guesser.guess(board)
board.guess(attempt)
return board
示例8: game
# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import display [as 别名]
def game(white_engine, black_engine, game_time=300.0, verbose=False):
""" Run a single game. Raise RuntimeError in the event of time expiration.
Raise LookupError in the case of a bad move. The tournament engine must
handle these exceptions. """
# Initialize variables
board = Board()
time = { -1 : game_time, 1 : game_time }
engine = { -1 : black_engine, 1 : white_engine }
if verbose:
print "INITIAL BOARD\n--\n"
board.display(time)
# Do rounds
for move_num in range(60):
moves = []
for color in [-1, 1]:
start_time = timeit.default_timer()
move = get_move(board, engine[color], color, move_num, time)
end_time = timeit.default_timer()
# Update user time
time[color] -= round(end_time - start_time, 1)
if time[color] < 0:
raise RuntimeError(color)
# Make a move, otherwise pass
if move is not None:
board.execute_move(move, color)
moves.append(move)
if verbose:
print "--\n"
print "Round " + str(move_num + 1) + ": " + player[color] + " plays in " + move_string(move) + '\n'
board.display(time)
if not moves:
# No more legal moves. Game is over.
break
示例9: run_game
# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import display [as 别名]
def run_game():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()
board = Board(BOARD_WIDTH, BOARD_HEIGHT, CELL_SIZE)
for j in range(BOARD_HEIGHT):
for i in range(BOARD_WIDTH):
if START[j][i] == 'S':
board.addStart(i,j)
board.addPlayer(i,j)
elif START[j][i] == 'O':
board.addObstacle(i,j)
elif START[j][i] == 'F':
board.addFlag(i,j)
elif START[j][i] == 'G':
board.addGoal(i,j)
while True:
time_passed = clock.tick(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
board.moveUp()
elif event.key == pygame.K_DOWN:
board.moveDown()
elif event.key == pygame.K_RIGHT:
board.moveRight()
elif event.key == pygame.K_LEFT:
board.moveLeft()
screen.fill(BG_COLOR)
board.display(screen)
pygame.display.flip()
示例10: play
# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import display [as 别名]
def play(self, verbose=True):
# BEGIN
board = Board(SecretWord(self.picker.pick_word()))
while not board.done():
if len(self.guessers)>1:
flag = True
else:
flag = False
for guesser in range(len(self.guessers)):
self.winner = guesser
guess_word = self.guessers[guesser].guess(board)
if guess_word:
board.guess(guess_word)
else:
return board
if verbose:
if flag:
print(self.guessers[guesser].name,'guesses', guess_word)
board.display()
if board.done() and flag:
print('winner is', self.guessers[guesser].name)
break
while guess_word in board.hits() and not board.done():
guess_word = self.guessers[guesser].guess(board)
if guess_word:
board.guess(guess_word)
else:
return board
if verbose:
if flag:
print(self.guessers[guesser].name,'guesses', guess_word)
board.display()
if board.done() and flag:
print('winner is', self.guessers[guesser].name)
return board
"*** REPLACE THIS LINE ***"
示例11: __init__
# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import display [as 别名]
class Game:
def __init__(self, turnAI=False, depth=10):
self.board = Board()
self.larvaTurn = True
self.currentAgent = self.board.getLarva()
self.turnAI = turnAI
self.depth = depth
self.round = 0
self.timing = []
def start(self):
while True:
self.board.display()
self.playRound()
self.larvaTurn = not self.larvaTurn
if self.isOver():
break
self.end()
def playRound(self):
self.round += 1
print "Round:", self.round
if self.larvaTurn:
print "Larva turn"
else:
print "Bird Turn"
if self.turnAI:
"""
AI makes a move
"""
"""
import cProfile, pstats, StringIO
pr = cProfile.Profile()
pr.enable()
"""
t1 = time.time()
agents = []
for agent in self.board.agents:
agents.append([agent.coordinates.x, agent.coordinates.y])
root = Node(agents, None, self.larvaTurn, 0, self.larvaTurn)
AlphaBetaPruning(root, 0, 999999, -999999, self.depth)
src_coordinates, dst_coordinates = root.getBestMove()
t2 = time.time()
"""
pr.disable()
s = StringIO.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print s.getvalue()
"""
print "AI made a move in", t2 - t1, "seconds"
self.timing.append(t2 - t1)
printIndex(src_coordinates)
print "->",
printIndex(dst_coordinates)
print
print "Root node score:", root.score
self.currentAgent = self.board.findAgent(src_coordinates)
self.currentAgent.move(dst_coordinates)
self.turnAI = False
else:
while True: # Loop until valid move
try:
src_coordinates, dst_coordinates = self.readCommand()
except:
print "Invalid input\n", "Please try again"
continue
if self.validateMove(src_coordinates, dst_coordinates):
print "Valid move made"
self.turnAI = True
self.currentAgent.move(dst_coordinates)
break
else:
print "Please try again"
def readCommand(self):
"""
Processes the command used to run the game from command line
"""
cmd = raw_input("Enter move >> ")
if cmd is None or not " " in cmd:
raise Exception("Improper format")
command_string = cmd.split(" ")
src = command_string[0]
dst = command_string[1]
#.........这里部分代码省略.........
示例12: __init__
# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import display [as 别名]
class Game:
"""Game where everything comes together"""
def __init__(self, players, computers, dictionary='sowpods.txt'):
"""Sets up initial game state with player names given"""
self.bag = Bag()
self.board = Board()
self.player_order = players + sorted(computers.keys())
self.computers = computers
self.players = {}
for player in players:
self.players[player] = Player(player,self)
for computer in computers:
self.players[computer] = AI(computer, self, computers[computer])
self.turn = 0
self.played = False
self.dictionary = Dictionary(dictionary)
def display(self, compact=True):
"""displays home screen with board and player scores"""
if compact:
self.board.display_compact()
else:
self.board.display()
for player in self.players.values():
player.display()
print ''
print "Letters left: ", self.bag.num_letters_left()
print ''
sys.stdout.flush()
def display_rack(self, player):
"""displays the rack of player"""
self.players[player].display_rack()
def display_player_screen(self, compact=True):
"""Displays the screen each player will see when it is their turn"""
self.display(compact)
curr_player = self.player_order[self.turn % len(self.player_order)]
raw_input(curr_player + ": Press enter to see your letters")
print '\n' + curr_player + "'s letters:"
self.display_rack(curr_player)
def save_game(self):
'''Save the game in its current to a file'''
# save bag, board, and player_order
with open('bag.data', 'wb') as save_file:
pickle.dump(self.bag(), save_file)
with open('board.data', 'wb') as save_file:
pickle.dump(self.board(), save_file)
with open('player_order.data', 'wb') as save_file:
pickle.dump(self.player_order, save_file)
# save players
numAI = 1
for index, player in enumerate(self.players):
if self.players[player].isAI:
player_data = [player, \
self.players[player].rack(), \
self.players[player].score, \
self.computers[player]]
with open('AI_' + str(numAI) + '.data', 'wb') as save_file:
pickle.dump(player_data, save_file)
numAI += 1
else:
player_data = [player, \
self.players[player].rack(), \
self.players[player].score]
with open('player' + str(index + 1) + '.data', 'wb') as save_file:
pickle.dump(player_data, save_file)
# save turn, num_players, num_computers
with open('game_info.data', 'wb') as save_file:
num_real_players = len(self.players) - len(self.computers)
pickle.dump([self.turn, num_real_players, len(self.computers)], \
save_file)
示例13: str
# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import display [as 别名]
f.color = random.sample(colors,1)[0]
f.character = random.choice(junk)
g.color = random.sample(colors,1)[0]
g.character = random.choice(junk)
while count <= 1500:
a.move_random(color(a.character,a.color))
b.move_random(color(b.character,b.color))
c.move_random(color(c.character,c.color))
d.move_random(color(d.character,d.color))
e.move_random(color(e.character,e.color))
f.move_random(color(f.character,f.color))
g.move_random(color(g.character,g.color))
count_d = "Count: " + str(count)
vma = "Valid Moves A: " + str(a.get_valid_moves(a.x,a.y))
vmb = "Valid Moves B: " + str(b.get_valid_moves(b.x,b.y))
vmc = "Valid Moves C: " + str(c.get_valid_moves(c.x,c.y))
vmd = "Valid Moves D: " + str(d.get_valid_moves(d.x,d.y))
#os.system('clear')
#board.display()
#print(count_d + "\n" + vma + "\n" + vmb +"\n" + vmc + "\n" + vmd)
#print(junk)
count+=1
#time.sleep(.1)
count = 0
picture += 1
os.system('clear')
board.display()
time.sleep(1)
#print(count_d + "\n" + vma + "\n" + vmb +"\n" + vmc + "\n" + vmd)