我是蟒蛇的初学者。我有两个文件。
test.py
class UrPiece:
def __init__(self, color, symbol):
self.color = color
self.position = None
self.complete = False
self.symbol = symbol
def can_move(self, num_moves):
pass
class BoardSquare:
def __init__(self, x, y, entrance=False, _exit=False, rosette=False, forbidden=False):
self.piece = None
self.position = (x, y)
self.next_white = None
self.next_black = None
self.exit = _exit
self.entrance = entrance
self.rosette = rosette
self.forbidden = forbidden
def load_from_json(self, json_string):
import json
loaded_position = json.loads(json_string)
self.piece = None
self.position = loaded_position['position']
self.next_white = loaded_position['next_white']
self.next_black = loaded_position['next_black']
self.exit = loaded_position['exit']
self.entrance = loaded_position['entrance']
self.rosette = loaded_position['rosette']
self.forbidden = loaded_position['forbidden']
def jsonify(self):
next_white = self.next_white.position if self.next_white else None
next_black = self.next_black.position if self.next_black else None
return {'position': self.position, 'next_white': next_white, 'next_black': next_black, 'exit': self.exit, 'entrance': self.entrance, 'rosette': self.rosette, 'forbidden': self.forbidden}test2.py
from test import UrPiece, BoardSquare
from sys import argv
from random import choice
WHITE = 'White'
BLACK = 'Black'
class RoyalGameOfUr:
STARTING_PIECES = 7
def __init__(self, board_file_name):
self.board = None
self.load_board(board_file_name)
def load_board(self, board_file_name):
import json
try:
with open(board_file_name) as board_file:
board_json = json.loads(board_file.read())
self.num_pieces = self.STARTING_PIECES
self.board = []
for x, row in enumerate(board_json):
self.board.append([])
for y, square in enumerate(row):
self.board[x].append(BoardSquare(x, y, entrance=square['entrance'], _exit=square['exit'], rosette=square['rosette'], forbidden=square['forbidden']))
for i in range(len(self.board)):
for j in range(len(self.board[i])):
if board_json[i][j]['next_white']:
x, y = board_json[i][j]['next_white']
self.board[i][j].next_white = self.board[x][y]
if board_json[i][j]['next_black']:
x, y = board_json[i][j]['next_black']
self.board[i][j].next_black = self.board[x][y]
except OSError:
print('The file was unable to be opened. ')
def draw_block(self, output, i, j, square):
MAX_X = 8
MAX_Y = 5
for y in range(MAX_Y):
for x in range(MAX_X):
if x == 0 or y == 0 or x == MAX_X - 1 or y == MAX_Y - 1:
output[MAX_Y * i + y][MAX_X * j + x] = '+'
if square.rosette and (y, x) in [(1, 1), (1, MAX_X - 2), (MAX_Y - 2, 1), (MAX_Y - 2, MAX_X - 2)]:
output[MAX_Y * i + y][MAX_X * j + x] = '*'
if square.piece:
# print(square.piece.symbol)
output[MAX_Y * i + 2][MAX_X * j + 3: MAX_X * j + 5] = square.piece.symbol
def display_board(self):
"""
Draws the board contained in the self.board object
"""
if self.board:
#print(self.board[1][0].piece)
output = [[' ' for _ in range(8 * len(self.board[i//5]))] for i in range(5 * len(self.board))]
for i in range(len(self.board)):
for j in range(len(self.board[i])):
if not self.board[i][j].forbidden:
self.draw_block(output, i, j, self.board[i][j])
print('\n'.join(''.join(output[i]) for i in range(5 * len(self.board))))
def roll_d4_dice(self, n=4):
dots = 0
for _ in range(n):
dots += choice([0, 1])
return dots
def play_game(self):
self.display_board()
if __name__ == '__main__':
# file_name = input('What is the file name of the board json? ') if len(argv) < 2 else argv[1]
file_name = 'two_lines.ur'
rgu = RoyalGameOfUr(file_name)
rgu.play_game()在这里,self.display_board()打印板。不需要任何辩论。我需要在黑板上显示一个UrPiece对象。
我尝试在“玩游戏”功能上创建一个BoardSqure类的实例,但是它不起作用。我完全是蟒蛇的初学者。如果有人能解释该做什么或指出我能读到的任何资源,我将非常感激。谢谢。
输出:
++++++++ ++++++++
+ + + +
+ + + +
+ + + +
++++++++ ++++++++
++++++++ ++++++++
+ + + +
+ + + +
+ + + +
++++++++ ++++++++
++++++++ ++++++++
+ + + +
+ + + +
+ + + +
++++++++ ++++++++
++++++++ ++++++++
+ + + +
+ + + +
+ + + +
++++++++ ++++++++
++++++++ ++++++++
+ + + +
+ + + +
+ + + +
++++++++ ++++++++
++++++++ ++++++++
+ + + +
+ + + +
+ + + +
++++++++ ++++++++
++++++++ ++++++++
+ + + +
+ + + +
+ + + +
++++++++ ++++++++
++++++++ ++++++++
+ + + +
+ + + +
+ + + +
++++++++ ++++++++预期输出:
++++++++ ++++++++
+ + + +
+ + + +
+ + + +
++++++++ ++++++++
++++++++ ++++++++
+ + + +
+ + + +
+ + + +
++++++++ ++++++++
++++++++ ++++++++
+ + + +
+ + + +
+ + + +
++++++++ ++++++++
++++++++ ++++++++
+ + + +
+ + + +
+ + + +
++++++++ ++++++++
++++++++ ++++++++
+ + + +
+ + + +
+ + + +
++++++++ ++++++++
++++++++ ++++++++
+ + + +
+ + + +
+ + + +
++++++++ ++++++++
++++++++ ++++++++
+ + + +
+ W + + +
+ + + +
++++++++ ++++++++
++++++++ ++++++++
+ + + +
+ + + +
+ + + +
++++++++ ++++++++two_lines.ur
[[{"position": [0, 0], "next_white": [1, 0], "next_black": null, "exit": "", "entrance": "White", "rosette": false, "forbidden": false}, {"position": [0, 1], "next_white": null, "next_black": null, "exit": "", "entrance": "", "rosette": false, "forbidden": true}, {"position": [0, 2], "next_white": null, "next_black": [1, 2], "exit": "", "entrance": "Black", "rosette": false, "forbidden": false}], [{"position": [1, 0], "next_white": [2, 0], "next_black": null, "exit": "", "entrance": "", "rosette": false, "forbidden": false}, {"position": [1, 1], "next_white": null, "next_black": null, "exit": "", "entrance": "", "rosette": false, "forbidden": true}, {"position": [1, 2], "next_white": null, "next_black": [2, 2], "exit": "", "entrance": "", "rosette": false, "forbidden": false}], [{"position": [2, 0], "next_white": [3, 0], "next_black": null, "exit": "", "entrance": "", "rosette": false, "forbidden": false}, {"position": [2, 1], "next_white": null, "next_black": null, "exit": "", "entrance": "", "rosette": false, "forbidden": true}, {"position": [2, 2], "next_white": null, "next_black": [3, 2], "exit": "", "entrance": "", "rosette": false, "forbidden": false}], [{"position": [3, 0], "next_white": [4, 0], "next_black": null, "exit": "", "entrance": "", "rosette": false, "forbidden": false}, {"position": [3, 1], "next_white": null, "next_black": null, "exit": "", "entrance": "", "rosette": false, "forbidden": true}, {"position": [3, 2], "next_white": null, "next_black": [4, 2], "exit": "", "entrance": "", "rosette": false, "forbidden": false}], [{"position": [4, 0], "next_white": [5, 0], "next_black": null, "exit": "", "entrance": "", "rosette": false, "forbidden": false}, {"position": [4, 1], "next_white": null, "next_black": null, "exit": "", "entrance": "", "rosette": false, "forbidden": true}, {"position": [4, 2], "next_white": null, "next_black": [5, 2], "exit": "", "entrance": "", "rosette": false, "forbidden": false}], [{"position": [5, 0], "next_white": [6, 0], "next_black": null, "exit": "", "entrance": "", "rosette": false, "forbidden": false}, {"position": [5, 1], "next_white": null, "next_black": null, "exit": "", "entrance": "", "rosette": false, "forbidden": true}, {"position": [5, 2], "next_white": null, "next_black": [6, 2], "exit": "", "entrance": "", "rosette": false, "forbidden": false}], [{"position": [6, 0], "next_white": [7, 0], "next_black": null, "exit": "", "entrance": "", "rosette": false, "forbidden": false}, {"position": [6, 1], "next_white": null, "next_black": null, "exit": "", "entrance": "", "rosette": false, "forbidden": true}, {"position": [6, 2], "next_white": null, "next_black": [7, 2], "exit": "", "entrance": "", "rosette": false, "forbidden": false}], [{"position": [7, 0], "next_white": null, "next_black": null, "exit": "", "entrance": "", "rosette": false, "forbidden": false}, {"position": [7, 1], "next_white": null, "next_black": null, "exit": "", "entrance": "", "rosette": false, "forbidden": true}, {"position": [7, 2], "next_white": null, "next_black": null, "exit": "", "entrance": "", "rosette": false, "forbidden": false}]]我尝试了什么:
def play_game(self):
piece = UrPiece(WHITE, 'W')
bs_1 = BoardSquare(1, 1)
bs_1.piece = piece
piece.position = bs_1
if bs_1.piece:
self.display_board()给出相同的输出。
def play_game(self):
"""
Your job is to recode this function to play the game.
"""
piece = UrPiece(WHITE, 'W')
bs_1 = BoardSquare(1, 0)
# bs_1.piece = piece
self.board[1][0] = bs_1
self.display_board()给出相同的输出。但
def play_game(self):
piece = UrPiece(WHITE, 'W')
bs_1 = BoardSquare(1, 0)
bs_1.piece = piece
self.board[1][0] = bs_1
self.display_board() 给出错误:
output[MAX_Y * i + y][MAX_X * j + x] = '+'
IndexError: list assignment index out of range如何更新主板对象,使BoardSquare中的部分分布为UrPiece。
发布于 2020-11-13 11:58:07
我已经完成了密码。
test.py
class UrPiece:
WhiteStarts = []
BlackStarts = []
WhiteEnds = []
BlackEnds = []
def __init__(self, color, symbol):
self.color = color
self.position = None
self.complete = False
self.symbol = symbol
def can_move(self, num_moves):
if (self.complete == True and self.position and num_moves > 1):
return False
elif (self.complete == True and self.position == None):
return False
else:
return True
class BoardSquare:
def __init__(self, x, y, entrance=False, _exit=False, rosette=False, forbidden=False):
self.piece = None
self.position = (x, y)
self.next_white = None
self.next_black = None
self.exit = _exit
self.entrance = entrance
self.rosette = rosette
self.forbidden = forbidden
def load_from_json(self, json_string):
import json
loaded_position = json.loads(json_string)
self.piece = None
self.position = loaded_position['position']
self.next_white = loaded_position['next_white']
self.next_black = loaded_position['next_black']
self.exit = loaded_position['exit']
self.entrance = loaded_position['entrance']
self.rosette = loaded_position['rosette']
self.forbidden = loaded_position['forbidden']
def jsonify(self):
next_white = self.next_white.position if self.next_white else None
next_black = self.next_black.position if self.next_black else None
return {'position': self.position, 'next_white': next_white, 'next_black': next_black, 'exit': self.exit, 'entrance': self.entrance, 'rosette': self.rosette, 'forbidden': self.forbidden}test2.py
from sys import argv
from random import choice, randint
from test import BoardSquare, UrPiece
WHITE = 'White'
BLACK = 'Black'
# players = dict()
class RoyalGameOfUr:
STARTING_PIECES = 7
def __init__(self, board_file_name):
self.players = {}
self.board = None
self.load_board(board_file_name)
self.num_pieces = 0
def load_board(self, board_file_name):
"""
This function takes a file name and loads the map, creating BoardSquare objects in a grid.
:param board_file_name: the board file name
:return: sets the self.board object within the class
"""
import json
try:
with open(board_file_name) as board_file:
board_json = json.loads(board_file.read())
self.num_pieces = self.STARTING_PIECES
self.board = []
for x, row in enumerate(board_json):
self.board.append([])
for y, square in enumerate(row):
self.board[x].append(BoardSquare(x, y, entrance=square['entrance'], _exit=square['exit'],
rosette=square['rosette'], forbidden=square['forbidden']))
for i in range(len(self.board)):
for j in range(len(self.board[i])):
if board_json[i][j]['next_white']:
x, y = board_json[i][j]['next_white']
self.board[i][j].next_white = self.board[x][y]
if board_json[i][j]['next_black']:
x, y = board_json[i][j]['next_black']
self.board[i][j].next_black = self.board[x][y]
except OSError:
print('The file was unable to be opened. ')
def draw_block(self, output, i, j, square):
"""
Helper function for the display_board method
:param output: the 2d output list of strings
:param i: grid position row = i
:param j: grid position col = j
:param square: square information, should be a BoardSquare object
"""
MAX_X = 8
MAX_Y = 5
for y in range(MAX_Y):
for x in range(MAX_X):
if x == 0 or y == 0 or x == MAX_X - 1 or y == MAX_Y - 1:
output[MAX_Y * i + y][MAX_X * j + x] = '+'
if square.rosette and (y, x) in [(1, 1), (1, MAX_X - 2), (MAX_Y - 2, 1), (MAX_Y - 2, MAX_X - 2)]:
output[MAX_Y * i + y][MAX_X * j + x] = '*'
if square.piece:
# print(square.piece.symbol)
output[MAX_Y * i + 2][MAX_X * j + 3: MAX_X * j + 5] = square.piece.symbol
def display_board(self):
"""
Draws the board contained in the self.board object
"""
if self.board:
output = [[' ' for _ in range(8 * len(self.board[i // 5]))] for i in range(5 * len(self.board))]
for i in range(len(self.board)):
for j in range(len(self.board[i])):
if not self.board[i][j].forbidden:
self.draw_block(output, i, j, self.board[i][j])
print('\n'.join(''.join(output[i]) for i in range(5 * len(self.board))))
def moves_get(self, player, num_moves):
moves_allowed = []
for piece in player:
if piece.can_move(num_moves):
moves_allowed.append(piece)
return moves_allowed
def cont_play(self, players):
for player in players:
if all((piece.complete for piece in players[player])):
return False
return True
def start_moovement(self, the_piece, dice_results):
if the_piece.position:
x, y = the_piece.position.position
self.board[x][y].piece.position = None
self.board[x][y].piece = None
position = self.board[x][y]
else:
dice_results -= 1
if the_piece.color == 'White':
position = UrPiece.WhiteStarts[0]
else:
position = UrPiece.BlackStarts[0]
for i in range(dice_results):
if the_piece.color == 'White':
position = position.next_white
if position:
x, y = position.position
the_piece.position = self.board[x][y]
if self.board[x][y].piece:
print(self.board[x][y].piece.symbol, 'has been knocked off')
self.board[x][y].piece.position = None
self.board[x][y].piece = None
self.board[x][y].piece = the_piece
else:
the_piece.position = None
the_piece.complete = True
print(the_piece.symbol, 'has completed its path.')
return position
def player_init(self):
player_name = input('What is your name? ')
self.players[player_name] = [UrPiece('White', 'W{}'.format(i + 1)) for i in range(self.STARTING_PIECES)]
print('{} you will play as white.'.format(player_name))
player_name = input('What is your name? ')
self.players[player_name] = [UrPiece('Black', 'B{}'.format(i + 1)) for i in range(self.STARTING_PIECES)]
print('{} you will play as black.'.format(player_name))
def play_game(self):
if not self.board:
print('Unable to start the game until the board is loaded')
return
turn = 0
self.player_init()
player_names = list(self.players.keys())
player = self.players[player_names[turn]]
for i in range(len(self.board)):
for j in range(len(self.board[i])):
if self.board[i][j].entrance == 'White':
UrPiece.WhiteStarts.append(self.board[i][j])
else:
if self.board[i][j].entrance == 'Black':
UrPiece.BlackStarts.append(self.board[i][j])
while self.cont_play(self.players):
self.display_board()
player = self.players[player_names[turn]]
dice_results = self.roll_d4_dice()
print('You rolled', dice_results)
while self.take_turn(player, dice_results):
self.display_board()
print('You have landed on a rosette, go again. ')
dice_results = self.roll_d4_dice()
turn = (turn + 1) % 2
print(player_names[((turn + 1) % 2)], 'has won the game.')
def take_turn(self, player, dice_results):
moves_allowed = self.moves_get(player, dice_results)
for i, move in enumerate(moves_allowed):
if not move.position:
print(i + 1, move.symbol, 'currently off the board')
else:
print(i + 1, move.symbol, move.position.position)
for piece in player:
if piece.complete:
print(piece.symbol, 'has completed the race.')
if moves_allowed and dice_results:
move = int(input('Which move do you wish to make? '))
while move not in range(1, len(moves_allowed) + 1):
move = int(input("Sorry, that wasn't a valid selection, which move do you wish to make? "))
final_position = self.start_moovement(moves_allowed[(move - 1)], dice_results)
if final_position and final_position.rosette:
return True
else:
print('No moves are possible with the current dice roll. ')
return False
def roll_d4_dice(self, n=4):
"""
:param n: the number of tetrahedral d4 to roll, each with one dot on
:return: the result of the four rolls.
"""
dots = 0
for _ in range(n):
dots += choice([0, 1])
return dots
if __name__ == '__main__':
file_name = input('What is the file name of the board json? ') if len(argv) < 2 else argv[1]
#file_name = 'original_board.ur'
rgu = RoyalGameOfUr(file_name)
rgu.play_game()https://stackoverflow.com/questions/64814440
复制相似问题