我的Othello游戏的Python 3.3代码遇到了大麻烦。我有一个很大的麻烦,因为我有很多问题。我会列出它们然后在这里附上我的代码。希望你们能帮助我。现在已经到了,如果你能为我纠正代码那就太棒了,但是如果你只是告诉我如何以及在哪里解决这些问题就没关系了。
如何在电路板中央打印原来的四块瓷砖?由于我的行和列是用户输入,因此我的程序不接受硬编码。
每次搬家后,如何在棋盘上印上我的动作?
我如何制作一个功能以及在何处将其置于循环中,如果游戏尚未结束,我可以继续进行移动?
首先我会发布我的函数和我的类,然后是我的用户界面。非常感谢你!
class Reversi:
### THE BOARD
def __init__(self,column,row):
self._column = column
self._row = row
self._board = self.getnewboard()
def getnewboard(self)->list:
'''Returns a new board with empty spaces'''
board = []
for i in range(self._column):
board.append([' '] * self._row)
board[int(self._column - 1)][int(self._row-1)] = 'B'
board[int(self._column/2)-1][int(self._row/2)] = 'B'
board[int(self._column/2)][int(self._row/2)-1] = 'W'
board[int(self._column/2)][int(self._row/2)] = 'W'
return board
def board_copy(self,board)->'a board copy':
'''duplicates a board'''
dupe = self.getnewboard()
for x in range(self._row):
for y in range(self._column):
dupe[x][y] = self.getnewboard()[x][y]
return dupe
def copyboard(self,board)->'a new board':
'''copy the current game board for further use'''
copy = self.board_copy(board)
for x in range(self._row):
for y in range(self._column):
copy[x][y] = board[x][y]
return copy
### PLAYERS
def change_turn(self,turn:str)->str:
'''Gives the player whose turn it is now'''
if turn == 'B':
return 'W'
else:
return 'B'
def who_first(self)->str:
'''Return a string,the function determines who is gonna play first'''
while True:
choice = input('1 for Black and 2 for White -- play first: ')
if choice == '1':
return 'player 1'
elif choice == '2':
return 'player 2'
while choice != '1' or chioce != '2':
please_choose = input('please choose between 1 and 2')
if please_choose == '1':
return 'player 1'
elif please_choose == '2':
return 'player 2'
else:
print('No good')
def second(self)->str:
'''The the second player'''
first = self.who_first()
second = ' '
if first == 'player 1':
second = 'player 2'
else:
second = 'player 1'
return second
def tile_option(self)->list:
'''Returns a list with two players represented as B for black and W
for white.The first element in the list is player1's tile.Player1
chooses first, according to who_first function
'''
print('Now player please chooses your tile')
choose = ''
while not (choose == 'B' or choose == 'W'):
print('Choose one from B and W')
choose = input('Enter B or W here: ').upper()
if choose == 'B':
return ['B','W'] # B stands for player1
else:
return ['W','B'] # W stands for player1
### Moves
def isonboard(self,x,y)->bool:
'''To check if the moves made by the players are on the board
and returns true or false
'''
return x >= 0 and x <= self._row and y >= 0 and y <= self._column
def oncorner(self,x,y):
'''Return true if the position is in a corner'''
return (x==0 and y ==0) or (x == self._row-1 and y == 0) or (x == 0 and y == self._column-1) or (x == self._row-1 and y == self._column-1)
def isvalidmove(self,board, tile, xstart, ystart):
# Returns False if the player's move on space xstart, ystart is invalid.
# If it is a valid move, returns a list of spaces that would become the player's if they made a move here.
if board[xstart][ystart] != ' ' or not self.isonboard(xstart, ystart):
return False
board[xstart][ystart] = tile # temporarily set the tile on the board.
if tile == 'B':
othertile = 'W'
else:
othertile = 'W'
tilesToFlip = []
for xdirection, ydirection in [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]]:
x, y = xstart, ystart
x += xdirection # first step in the direction
y += ydirection # first step in the direction
if self.isonboard(x,y) and board[x-1][y-1] == othertile:
# There is a piece belonging to the other player next to our piece.
x += xdirection
y += ydirection
if not self.isonboard(x, y):
continue
while board[x-1][y-1] == othertile:
x += xdirection
y += ydirection
if not self.isonboard(x, y): # break out of while loop, then continue in for loop
break
if not self.isonboard(x, y):
continue
if board[x-1][y-1] == tile:
# There are pieces to flip over. Go in the reverse direction until we reach the original space, noting all the tiles along the way.
while True:
x -= xdirection
y -= ydirection
if x == xstart and y == ystart:
break
tilesToFlip.append([x, y])
board[xstart][ystart] = ' ' # restore the empty space
if len(tilesToFlip) == 0: # If no tiles were flipped, this is not a valid move.
return False
return tilesToFlip
def validmoves(self,board,tile)->list:
'''Return a list of valid moves'''
l = []
for x in range(self._row):
for y in range(self._column):
if self.isvalidmove(board,tile,x,y) != False:
l.append([x,y])
return l
def moves_on_board(self,board,tile)->'a new board':
'''Return a new board with valid moves marked on it'''
copy = self.copyboard(board)
for x,y in self.validmoves(board,tile):
copy[x][y] = '!'
return copy
def make_valid_move(self,board,tile,xstart,ystart)->bool:
'''put the tiles on the board at xstart and ystart.Flip opponent's pieces
Returns False if the move is invalid, True if is valid
'''
flip_ya = self.isvalidmove(board,tile,xstart,ystart)
if flip_ya == False:
return False
tile = board[xstart][ystart]
for x,y in flip_ya:
tile = board[x][y]
return True
def player_move(self,board,tile)->'list of coordinates':
'''After a player, the second player is gonna
play the move.Given the board and player2's tile
Returns the move as [x,y], a list. Cannot put the tile on
where there's already a tile
'''
possible_moves = self.validmoves(board,tile)
# possible_moves is a list of valid moves
L1 = [] # L! and L2 are the lists of numbers fit in the range
L2 = [] # to make sure that the indices are valid
L_move = []
for x in range(self._row):
L1.append(x)
for y in range(self._column):
L2.append(y)
print('THIS IS L1 L2', L1, L2)
while True:
try:
x_co = int(input('Enter the x-coordinate you want to put the tile on: '))
y_co = int(input('Enter the y-coordinate you want to put the tile on: '))
if x_co in L1 and y_co in L2 and board[x_co][y_co] == ' ':
print('Essage')
x = x_co
y = y_co
break
else:
print('Invalid move, coordinates should be in ranges')
except:
print('Oh Jesus What\'s wrong here? I think you\'d better not enter spaces or strings,but coordinates')
return [x,y]
###SCORE
def record_score(self,board,player_turn)->dict:
'''Record the scores on the board and see scores
Returns a dictionary, whose key --> 'one' represents player1's score.
'''
score_1 = 0
score_2 = 0
b = player_turn[0]
a = player_turn[-1]
if a == 'B' or a == 'b':
print(a)
print('player1\'s tile is B,player2\'s tile is W')
for x in range(self._row):
for y in range(self._column):
if board[x][y] == 'B':
score_1 += 1
if board[x][y] == 'W':
score_2 += 1
if a == 'W' or a == 'w':
print(a)
print('player1\'s tile is W,player2\'s tile is B')
for x in range(self._row):
for y in range(self._column):
print(board[x][y])
if board[x][y] == 'W':
score_1 += 1
if board[x][y] == 'B':
score_2 += 1
return {'B':score_1,'W':score_2}
def show_points(self,board,player_turn):
'''This function prints out the current score of two players'''
scores = self.record_score(board,player_turn)
print('you have () points. your opponent has () points'.format(scores[player_turn[0]],scores[player_turn[0]]))
### WINNING STRATEGY
def terminal_test(self,board):
"""Is the game over?"""
# first find an empty square
for row in range(self._row):
for column in range(self._column):
if board[row][column] != 0:
continue
return True
import console_game
import sys
### USER INTERFACE
def print_board(board):
'''Prints out a new game board'''
HLINE = ' ----' * (board._row+1)
VLINE = ' | ' * (board._column+1)
print(HLINE)
for y in range(board._column):
print(VLINE)
print(y+1, end='')
for x in range(board._row):
print(board._board[x-2][y-2],end = '')
print('')
print(VLINE)
print(HLINE)
return board
def game_start(mainBoard,player_turn):
'''After the user enters valid column and row numbers, the game starts
'''
turn = c.who_first()
player1_tile,player2_tile = player_turn
print(turn + ' will go first.')
if turn == "player 1":
player_turn = (turn, player1_tile)
else:
player_turn = (turn, player2_tile)
print(player_turn[0])
print(player_turn[-1])
while True:
if turn == 'B':
# Player1's turn.
if False:
valid_moves_board = c.moves_on_board(mainBoard._board, player_turn[1])
print_board(mainBoard)
else:
print_board(mainBoard)
c.show_points(mainBoard,player1_tile,player2_tile)
move = c.player_move(mainBoard, player_turn[-1])
if move == 'noplay':
print('Thanks for playing!')
sys.exit() # terminate the program
## elif c.validmoves(mainBoard, player_turn[-1]) == []:
## break
else:
c.make_valid_move(mainBoard, player_turn[-1], move[0], move[-1])
turn = 'player 2'
else:
# player2's turn.
print_board(mainBoard)
c.show_points(mainBoard._board,player_turn[-1])
print('Now player 2 please make a move,remember coordinates should be valid')
x, y = c.player_move(mainBoard._board, player_turn[-1])
c.make_valid_move(mainBoard._board, player_turn[-1], x, y)
if c.validmoves(mainBoard._board, player_turn[-1]) == []:
break
else:
turn = 'player 1'
# Display the final score.
scores = c.record_score(mainBoard._board,player_turn)
print('player 1 scored {} points. player 2 scored {} points'.format(scores[player1_tile], scores[player1_tile]))
if scores['B'] > scores['W']:
print('player 1 wins. Congratulations!,won by {} points'.format(scores[player1_tile] - scores[player1_tile]))
elif scores['W'] < scores["B"]:
print('player 2 wins. Congratulations!, won by {} points'.format(scores[player1_tile] - scores[player1_tile]))
else:
print('The game was a tie! Uh huh!')
game_start(mainBoard._board,('player 2','W'))
if not play_again():
sys.exit()
elif play_again():
print('Huh')
def play_again():
'''This function asks if users want to play again or not'''
print('Do you want to play again?(y -> yes or n -> no)')
return input().lower().startswith('y')
if __name__ == '__main__':
print('Welcome to Othello!')
print()
print('Ready to play huh?')
print()
print('Let\'s begin!')
print()
### the row and column must be integers
while True:
try:
column = int(input('Enter an even number between 4 and 16: '))
row = int(input('Enter an even number between 4 and 16: '))
except:
print('No good')
else:
c = console_game.Reversi(column,row)
game_start(c,c.tile_option())