A 级计算机/AQA/试卷 1/程序框架/AS2019
这是针对 AQA AS 级计算机科学规范。
在这里,您可以提出一些关于部分问题的内容以及如何解决它们的想法。
请尊重他人,不要破坏或篡改页面,因为这会影响学生备考!
请勿在此页面讨论问题。 请使用讨论页面:讨论:A 级计算机/AQA/试卷 1/程序框架/AS2019
允许玩家“a”和“b”跳过回合
C#
意外创建,就像 Louis 一样
// SelectMove: line 382 (change)
// prompts skip action
Console.Write("select a piece to move, or say 'skip' to skip your turn: ")
// SelectMove: line 388 (addition)
// allows checking for skip request
else if (piece == "skip") {
return -1; // makemove skips over if pieceindex<0, so this will avoid making a move
}
Delphi/Pascal
Java
Console.write("Which piece do you want to move? Type 'skip' if you would like to skip the turn");
piece = Console.readLine();
if (piece.equals("")) {
endOfList = true;
}
if (piece.equalsIgnoreCase("Skip")) {
System.out.println("Skipped turn!");
return -1; //the value returned is lesser than 0 - makeMove will not be completed. (As it requires an index > 0)
}
Python
#B:
ListOfMoves = ListPossibleMoves(Board, B, NextPlayer, ListOfMoves)
if not ListEmpty(ListOfMoves):
skipMove = 'X'
while skipMove != 'N' and skipMove != 'Y':
skipMove = input("Do you wish to skip your move? (Y/N) ").upper()
if skipMove != 'N' and skipMove != 'Y':
print("Sorry, please input 'Y' or 'N'.")
if skipMove == 'N':
PieceIndex = SelectMove(ListOfMoves)
Board, B, A = MakeMove(Board, B, A, ListOfMoves, PieceIndex)
else: #Remove if not counting moves made
totalMovesMade -= 1 #Remove if not counting moves made
bMovesMade -= 1 #Remove if not counting moves made
NextPlayer = SwapPlayer(NextPlayer)
else:
GameEnd = True
#A:
ListOfMoves = ListPossibleMoves(Board, A, NextPlayer, ListOfMoves)
if not ListEmpty(ListOfMoves):
skipMove = 'X'
while skipMove != 'N' and skipMove != 'Y':
skipMove = input("Do you wish to skip your move? (Y/N) ").upper()
if skipMove != 'N' and skipMove != 'Y':
print("Sorry, please input 'Y' or 'N'.")
if skipMove == 'N':
PieceIndex = SelectMove(ListOfMoves)
Board, A, B = MakeMove(Board, A, B, ListOfMoves, PieceIndex)
else: #Remove if not counting moves made
totalMovesMade -= 1 #Remove if not counting moves made
aMovesMade -= 1 #Remove if not counting moves made
NextPlayer = SwapPlayer(NextPlayer)
else:
GameEnd = True
VB.NET
用户必须输入一个以“.txt”结尾的文件,否则程序会自动添加“.txt”。
C#
由 Brockenhurst College 的 Sol 编写。
private static void SetUpBoard(string[,] board, int[,] a, int[,] b, ref bool fileFound)
{
string fileName = "game1.txt";
Console.Write("Do you want to load a saved game? (Y/N): ");
string answer = Console.ReadLine();
if (answer == "Y" || answer == "y")
{
Console.Write("Enter the filename: ");
fileName = Console.ReadLine();
if (!(fileName[fileName.Length - 4] == '.'
&& fileName[fileName.Length - 3] == 't'
&& fileName[fileName.Length - 2] == 'x'
&& fileName[fileName.Length - 1] == 't'))
{
fileName += ".txt";
}
}
意外编写
// line 121 (addition)
// uses endswith for a more compact form of what Sol has done above
if !fileName.EndsWith(".txt") fileName += ".txt";
Delphi/Pascal
Java
由 Kennet 学校博学的 Nevans 编写
boolean setUpBoard(String[][] board, int[][] a, int[][] b, boolean fileFound) { String fileName = "game1.txt"; Console.write("Do you want to load a saved game? (Y/N): "); String answer = Console.readLine(); if (answer.equals("Y") || answer.equals("y")) { Console.write("Enter the filename: "); fileName = Console.readLine(); // oh look at me my name is nathen and i think im soooo smart compared to others! Well guess what see why fact checkers say this is false. fileName = fileName.endsWith(".txt") ? fileName : (fileName += ".txt"); } try { BufferedReader fileHandle = new BufferedReader(new FileReader(fileName)); fileFound = true; a = loadPieces(fileHandle, a); b = loadPieces(fileHandle, b); fileHandle.close(); createNewBoard(board); addPlayerA(board, a); addPlayerB(board, b); } catch (IOException e) { displayErrorCode(4); } return fileFound; }
Python
def SetUpBoard(Board, A, B, FileFound):
FileName = 'game1.txt'
Answer = input('Do you want to load a saved game? (Y/N): ')
if Answer == 'Y' or Answer == 'y':
FileName = input('Enter the filename: ')
if ".txt" not in FileName: ## This line and the following are what have been modified
FileName += ".txt" ##
try:
FileHandle = open(FileName, 'r')
FileFound = True
A = LoadPieces(FileHandle, A)
B = LoadPieces(FileHandle, B)
FileHandle.close()
Board = CreateNewBoard(Board)
Board = AddPlayerA(Board, A)
Board = AddPlayerB(Board, B)
except:
DisplayErrorCode(4)
return Board, A, B, FileFound
#I would use a slice to detect .txt on the end of the string rather than in the string. S Baker
#check for txt file name
if FileName[-4:] != ".txt":
FileName = FileName + ".txt"
VB.NET
Sub SetUpBoard(ByRef Board(,) As String, ByRef A(,) As Integer, ByRef B(,) As Integer, ByRef FileFound As Boolean)
Dim FileName, Answer As String
FileName = "game1.txt"
Console.Write("Do you want to load a saved game? (Y/N): ")
Answer = Console.ReadLine()
If Answer = "Y" Or Answer = "y" Then
Console.Write("Enter the filename: ")
FileName = Console.ReadLine()
End If
Try
Dim FileHandle As New StreamReader(FileName)
FileFound = True
LoadPieces(FileHandle, A)
LoadPieces(FileHandle, B)
FileHandle.Close()
CreateNewBoard(Board)
AddPlayerA(Board, A)
AddPlayerB(Board, B)
Catch
End Try
Try
Dim FileHandle As New StreamReader(FileName & ".txt")
FileFound = True
LoadPieces(FileHandle, A)
LoadPieces(FileHandle, B)
FileHandle.Close()
CreateNewBoard(Board)
AddPlayerA(Board, A)
AddPlayerB(Board, B)
Catch
DisplayErrorCode(4)
End Try
End Sub
在每个回合之后显示所用移动次数。
C#
private static void Game()
{
int[,] A = new int[NumberOfPieces + 1, 3];
int[,] B = new int[NumberOfPieces + 1, 3];
string[,] board = new string[BoardSize, BoardSize];
MoveRecord[] listOfMoves = new MoveRecord[MaxMoves];
for (int i = 0; i < MaxMoves; i++)
{
MoveRecord tempRec = new MoveRecord();
listOfMoves[i] = tempRec;
}
bool fileFound = false, gameEnd = false;
string nextPlayer = "a";
int pieceIndex = 0;
SetUpBoard(board, A, B, ref fileFound);
if (!fileFound)
{
gameEnd = true;
}
while (!gameEnd)
{
PrintPlayerPieces(A, B);
DisplayBoard(board);
Console.WriteLine("Next Player: " + nextPlayer);
ClearList(listOfMoves);
if (nextPlayer == "a")
{
Console.WriteLine("A has made " + B[0, 0] + " moves");
ListPossibleMoves(board, A, nextPlayer, listOfMoves);
if (!ListEmpty(listOfMoves))
{
pieceIndex = SelectMove(listOfMoves);
MakeMove(board, A, B, listOfMoves, pieceIndex);
nextPlayer = SwapPlayer(nextPlayer);
}
else
{
gameEnd = true;
}
}
else
{
Console.WriteLine("B has made " + B[0, 0] + " moves");
ListPossibleMoves(board, B, nextPlayer, listOfMoves);
if (!ListEmpty(listOfMoves))
{
pieceIndex = SelectMove(listOfMoves);
MakeMove(board, B, A, listOfMoves, pieceIndex);
nextPlayer = SwapPlayer(nextPlayer);
}
else
{
gameEnd = true;
}
}
}
if (fileFound)
{
PrintResult(A, B, nextPlayer);
}
Console.ReadLine();
}
Delphi/Pascal
Java
void game () {
int[][] a = new int[NUMBER_OF_PIECES + 1][3]; int[][] b = new int[NUMBER_OF_PIECES + 1][3]; String[][] board = new String[BOARD_SIZE][BOARD_SIZE]; MoveRecord[] listOfMoves = new MoveRecord[MAX_MOVES]; boolean gameEnd = false; boolean fileFound = false; String nextPlayer = "a"; int pieceIndex; fileFound = setUpBoard(board, a, b, fileFound); if (!fileFound) { gameEnd = true; } while (!gameEnd) { printPlayerPieces(a, b); displayBoard(board); Console.writeLine("Next player: " + nextPlayer);
//Outputs a line which indexes parts of array a and b which are incremented every turn System.out.println("PLAYER A HAS TAKEN " + a[0][0] + " MOVES"); System.out.println("PLAYER B HAS TAKEN " + b[0][0] + " MOVES");
listOfMoves = clearList(listOfMoves); if (nextPlayer.equals("a")) { listOfMoves = listPossibleMoves(board, a, nextPlayer, listOfMoves); if (!listEmpty(listOfMoves)) { pieceIndex = selectMove(listOfMoves); makeMove(board, a, b, listOfMoves, pieceIndex); nextPlayer = swapPlayer(nextPlayer); } else { gameEnd = true; } } else { listOfMoves = listPossibleMoves(board, b, nextPlayer, listOfMoves); if (!listEmpty(listOfMoves)) { pieceIndex = selectMove(listOfMoves); makeMove(board, b, a, listOfMoves, pieceIndex); nextPlayer = swapPlayer(nextPlayer); } else { gameEnd = true; } } } if (fileFound) { printResult(a, b, nextPlayer); } }由 Kennet 学校的 James Trenaman 编写
Python
def Game():
MovesTaken = 0 ##Code modification
A = [[0, 0, 0] for Piece in range(NUMBER_OF_PIECES + 1)]
B = [[0, 0, 0] for Piece in range(NUMBER_OF_PIECES + 1)]
Board = [['' for Column in range(BOARD_SIZE)] for Row in range(BOARD_SIZE)]
ListOfMoves = [MoveRecord() for Move in range(MAX_MOVES)]
GameEnd = False
FileFound = False
NextPlayer = 'a'
Board, A, B, FileFound = SetUpBoard(Board, A, B, FileFound)
if not FileFound:
GameEnd = True
while not GameEnd:
print ("Current moves made: " + str(MovesTaken)) ##Code modification
MovesTaken += 1 ## Code modification
PrintPlayerPieces(A, B)
DisplayBoard(Board)
print('Next Player: ', NextPlayer)
ListOfMoves = ClearList(ListOfMoves)
if NextPlayer == 'a':
ListOfMoves = ListPossibleMoves(Board, A, NextPlayer, ListOfMoves)
if not ListEmpty(ListOfMoves):
PieceIndex = SelectMove(ListOfMoves)
Board, A, B = MakeMove(Board, A, B, ListOfMoves, PieceIndex)
NextPlayer = SwapPlayer(NextPlayer)
else:
GameEnd = True
else:
ListOfMoves = ListPossibleMoves(Board, B, NextPlayer, ListOfMoves)
if not ListEmpty(ListOfMoves):
PieceIndex = SelectMove(ListOfMoves)
Board, B, A = MakeMove(Board, B, A, ListOfMoves, PieceIndex)
NextPlayer = SwapPlayer(NextPlayer)
else:
GameEnd = True
if FileFound:
PrintResult(A, B , NextPlayer)
Python 替代方案
def Game():
A = [[0, 0, 0] for Piece in range(NUMBER_OF_PIECES + 1)]
B = [[0, 0, 0] for Piece in range(NUMBER_OF_PIECES + 1)]
Board = [['' for Column in range(BOARD_SIZE)] for Row in range(BOARD_SIZE)]
ListOfMoves = [MoveRecord() for Move in range(MAX_MOVES)]
GameEnd = False
FileFound = False
NextPlayer = 'a'
Board, A, B, FileFound = SetUpBoard(Board, A, B, FileFound)
if not FileFound:
GameEnd = True
while not GameEnd:
PrintPlayerPieces(A, B)
DisplayBoard(Board)
print('Next Player: ', NextPlayer)
ListOfMoves = ClearList(ListOfMoves)
if NextPlayer == 'a':
print("A has made {} moves".format(A[0][0])) ##Code modification
ListOfMoves = ListPossibleMoves(Board, A, NextPlayer, ListOfMoves)
if not ListEmpty(ListOfMoves):
PieceIndex = SelectMove(ListOfMoves)
Board, A, B = MakeMove(Board, A, B, ListOfMoves, PieceIndex)
NextPlayer = SwapPlayer(NextPlayer)
else:
GameEnd = True
else:
print("B has made {} moves".format(B[0][0])) ##Code modification
ListOfMoves = ListPossibleMoves(Board, B, NextPlayer, ListOfMoves)
if not ListEmpty(ListOfMoves):
PieceIndex = SelectMove(ListOfMoves)
Board, B, A = MakeMove(Board, B, A, ListOfMoves, PieceIndex)
NextPlayer = SwapPlayer(NextPlayer)
else:
GameEnd = False
if FileFound:
PrintResult(A, B , NextPlayer)
VB.NET
Sub Game()
Dim A(NumberOfPieces, 2) As Integer
Dim B(NumberOfPieces, 2) As Integer
Dim Board(BoardSize - 1, BoardSize - 1) As String
Dim ListOfMoves(MaxMoves - 1) As MoveRecord
Dim NextPlayer As String
Dim FileFound, GameEnd As Boolean
Dim PieceIndex As Integer
Dim MovesA As Integer = 0
Dim MovesB As Integer = 0
GameEnd = False
FileFound = False
Dim RepeatRandomNumber As Boolean = True
While RepeatRandomNumber
Dim RN As Integer = Rnd(Int(1))
If RN = 0 Then
NextPlayer = "a"
RepeatRandomNumber = False
End If
If RN = 1 Then
NextPlayer = "b"
RepeatRandomNumber = False
End If
End While
NextPlayer = "a"
SetUpBoard(Board, A, B, FileFound)
If Not FileFound Then
GameEnd = True
End If
While Not GameEnd
PrintPlayerPieces(A, B)
DisplayBoard(Board)
Console.WriteLine("Next Player: " & NextPlayer)
ClearList(ListOfMoves)
If NextPlayer = "a" Then
ListPossibleMoves(Board, A, NextPlayer, ListOfMoves)
If Not ListEmpty(ListOfMoves) Then
PieceIndex = SelectMove(ListOfMoves)
MakeMove(Board, A, B, ListOfMoves, PieceIndex)
NextPlayer = SwapPlayer(NextPlayer)
MovesA += 1
Else
GameEnd = True
End If
Else
ListPossibleMoves(Board, B, NextPlayer, ListOfMoves)
If Not ListEmpty(ListOfMoves) Then
PieceIndex = SelectMove(ListOfMoves)
MakeMove(Board, B, A, ListOfMoves, PieceIndex)
NextPlayer = SwapPlayer(NextPlayer)
MovesB += 1
Else
GameEnd = True
End If
End If
End While
If FileFound Then
Console.WriteLine("Player A used " & MovesA & " moves")
Console.WriteLine("Player B used " & MovesB & " moves")
PrintResult(A, B, NextPlayer)
End If
Console.ReadLine()
End Sub
错误值 1-4 没有说明每个错误的含义。 在显示时添加每个错误的描述。
C#
由 Brockenhurst College 的 Sol 编写。
private static void DisplayErrorCode(int errorNumber)
{
Console.WriteLine("Error " + errorNumber);
if (errorNumber == 1)
{
Console.WriteLine("Error: Selected piece is unable to move.");
}
else if (errorNumber == 2)
{
Console.WriteLine("Error: Selected piece is unable to move to selected placement.");
}
else if (errorNumber == 3)
{
Console.WriteLine("Error: Exception error.");
}
else if (errorNumber == 4)
{
Console.WriteLine("Error: Invalid game file selected.");
}
else
{
Console.WriteLine("Error: Invalid error.");
}
}
Delphi/Pascal
Java
private String returnErrorCode (int errorNum) {
String[] errors = new String[] {
"Invalid piece selected" , "Piece can't move to location!", "Exception error: NumberFormat" "IOException (File can't be found/ loaded)"
};
return errors[errorNum];
}
Python
def DisplayErrorCode(value):
errors = {1:'Invalid Piece Chosen',2:'Invalid Piece Entered', 3:'Invalid X/Y coordinate',4:'Invalid File Chosen'}
print(errors[value])
print("Play now -.^")
VB.NET
Sub DisplayErrorCode(ByVal ErrorNumber As Integer)
Dim ErrorMessage As String = "Error: Undefined error."
Select Case ErrorNumber
Case "1"
ErrorMessage = "Error: Selected piece is unable to move."
Case "2"
ErrorMessage = "Error: Selected piece is unable to move to selected placement."
Case "3"
ErrorMessage = "Error: Exception error."
Case "4"
ErrorMessage = "Error: Invalid game file selected."
End Select
Console.WriteLine(ErrorMessage)
End Sub
最初的跳棋(或跳棋,我更喜欢这样称呼它)是一种游戏,你可以“跳过”对手的棋子将它们从棋盘上移除。 在框架中,你不能这样做。 为了添加这种游戏机制,你需要编辑 ValidJump 和 MakeMove 方法,但这可能很困难,因为它需要理解所使用的数据结构。
C#
Delphi/Pascal
Java
/**
* Checks for each piece if it can jump (left or right)
* Does this by checking for two conditions - the first one would be if the area the piece wants to jump to is empty (SPACE), the second one would be if the middlePiecePlayer is of the same team
*
* @param playersPieces all of the pieces the current player has
* @param piece current piece (eg a2)
* @param newRow jumps by 2
* @param newColumn jumps by 2
* @return valid if a piece can jump - if true, player jumps to set coordinates
*/
private boolean validJump(String[][] board, int[][] playersPieces, String piece, int newRow, int newColumn) {
boolean valid = false;
String oppositePiecePlayer, middlePiecePlayer, player, middlePiece;
int index, currentRow, currentColumn, middlePieceRow, middlePieceColumn;
player = piece.substring(0, 1).toLowerCase();
index = Integer.parseInt(piece.substring(1));
//used to set opposite player
if (player.equals("a")) {
oppositePiecePlayer = "b";
} else {
oppositePiecePlayer = "a";
}
if (newRow >= 0 && newRow < BOARD_SIZE && newColumn >= 0 && newColumn < BOARD_SIZE) {
if (board[newRow][newColumn].equals(SPACE)) {
currentRow = playersPieces[index][ROW];
currentColumn = playersPieces[index][COLUMN];
middlePieceRow = (currentRow + newRow) / 2; //the piece between the jump
middlePieceColumn = (currentColumn + newColumn) / 2;
middlePiece = board[middlePieceRow][middlePieceColumn];
middlePiecePlayer = middlePiece.substring(0, 1).toLowerCase();
if (middlePiecePlayer.equals(oppositePiecePlayer) //checks if player between jump is from own or not - if not, allow jump
&& !middlePiecePlayer.equals(" ")) {
//get piece in board coordinates and set into blank
//add eaten player to list of eaten players
valid = true;
}
}
}
return valid;
}
/**
* After validating each piece, the console would print the possible moves all current players make. (checks if move is available for each piece - left and right)
*
* @return listOfMoves only available moves a player can take
*/
private MoveRecord[] listPossibleMoves(String[][] board, int[][] playersPieces,
String nextPlayer, MoveRecord[] listOfMoves) {
int direction, numberOfMoves, currentColumn, leftColumn, rightColumn,
jumpLeftColumn, jumpRightColumn, i, currentRow, newRow, jumpRow;
String piece;
if (nextPlayer.equals("a")) {
direction = 1;
} else {
direction = -1;
}
boolean isJumping = false;
numberOfMoves = 0;
Console.println("EATEN PIECES: " + eatenPieces.toString());
for (i = 1; i < NUMBER_OF_PIECES; i++) {
piece = nextPlayer + i;
currentRow = playersPieces[i][ROW];
currentColumn = playersPieces[i][COLUMN];
if (playersPieces[i][DAME] == 1) {
piece = piece.toUpperCase();
}
jumpRow = currentRow + direction + direction;
jumpLeftColumn = currentColumn - 2;
jumpRightColumn = currentColumn + 2;
if (validJump(board, playersPieces, piece, jumpRow, jumpLeftColumn)) {
Console.writeLine(piece + " can jump to " + jumpRow + " , " + jumpLeftColumn);
numberOfMoves += 1;
listOfMoves[numberOfMoves].piece = piece;
listOfMoves[numberOfMoves].newRow = jumpRow;
listOfMoves[numberOfMoves].newColumn = jumpLeftColumn;
listOfMoves[numberOfMoves].canJump = true;
isJumping = true;
}
if (validJump(board, playersPieces, piece, jumpRow, jumpRightColumn)) {
Console.writeLine(piece + " can jump to " + jumpRow + " , " + jumpRightColumn);
numberOfMoves += 1;
listOfMoves[numberOfMoves].piece = piece;
listOfMoves[numberOfMoves].newRow = jumpRow;
listOfMoves[numberOfMoves].newColumn = jumpRightColumn;
listOfMoves[numberOfMoves].canJump = true;
isJumping = true;
}
}
if (!isJumping) {
for (i = 1; i < NUMBER_OF_PIECES + 1; i++) {
piece = nextPlayer + i;
currentRow = playersPieces[i][ROW];
currentColumn = playersPieces[i][COLUMN];
if (playersPieces[i][DAME] == 1) {
piece = piece.toUpperCase();
}
newRow = currentRow + direction;
leftColumn = currentColumn - 1;
rightColumn = currentColumn + 1;
if (validMove(board, newRow, leftColumn)) {
Console.writeLine(piece + " can move to " + newRow + " , " + leftColumn);
numberOfMoves += 1;
listOfMoves[numberOfMoves].piece = piece;
listOfMoves[numberOfMoves].newRow = newRow;
listOfMoves[numberOfMoves].newColumn = leftColumn;
listOfMoves[numberOfMoves].canJump = false;
}
if (validMove(board, newRow, rightColumn)) {
Console.writeLine(piece + " can move to " + newRow + " , " + rightColumn);
numberOfMoves += 1;
listOfMoves[numberOfMoves].piece = piece;
listOfMoves[numberOfMoves].newRow = newRow;
listOfMoves[numberOfMoves].newColumn = rightColumn;
listOfMoves[numberOfMoves].canJump = false;
}
}
}
Console.writeLine("There are " + numberOfMoves + " possible moves");
return listOfMoves;
}
private void makeMove(String[][] board, int[][] playersPieces,
int[][] opponentsPieces, MoveRecord[] listOfMoves, int pieceIndex) {
playersPieces[0][0] += 1;
if (pieceIndex > 0) {
String piece = listOfMoves[pieceIndex].piece;
int newRow = listOfMoves[pieceIndex].newRow;
int newColumn = listOfMoves[pieceIndex].newColumn;
int playersPieceIndex = Integer.parseInt(piece.substring(1));
int currentRow = playersPieces[playersPieceIndex][ROW];
int currentColumn = playersPieces[playersPieceIndex][COLUMN];
boolean jumping = listOfMoves[pieceIndex].canJump;
movePiece(board, playersPieces, piece, newRow, newColumn);
if (jumping) {
int middlePieceRow = (currentRow + newRow) / 2;
int middlePieceColumn = (currentColumn + newColumn) / 2;
String middlePiece = board[middlePieceRow][middlePieceColumn];
Console.writeLine("jumped over " + middlePiece);
eatenPieces.add(middlePiece);
for (int[] i : opponentsPieces) {
if (i[0] == middlePieceRow && i[1] == middlePieceColumn) {
i[0] = -1;
i[1] = -1;
i[2] = 0;
}
}
}
}
}
Python
def ValidJump(Board, PlayersPieces, Piece, NewRow, NewColumn):
Valid = False
MiddlePiece = ''
Player = Piece[0].lower()
Index = int(Piece[1:])
if Player == 'a':
OppositePiecePlayer = 'b'
else:
OppositePiecePlayer = 'a'
if NewRow in range(BOARD_SIZE) and NewColumn in range(BOARD_SIZE):
if Board[NewRow][NewColumn] == SPACE:
CurrentRow = PlayersPieces[Index][ROW]
CurrentColumn = PlayersPieces[Index][COLUMN]
MiddlePieceRow = (CurrentRow + NewRow) // 2
MiddlePieceColumn = (CurrentColumn + NewColumn) // 2
MiddlePiece = Board[MiddlePieceRow][MiddlePieceColumn]
MiddlePiecePlayer = MiddlePiece[0].lower()
if MiddlePiecePlayer == OppositePiecePlayer or MiddlePiecePlayer != ' ':
Valid = True
return Valid
def MakeMove(Board, PlayersPieces, OpponentsPieces, ListOfMoves, PieceIndex):
PlayersPieces[0][0] += 1
if PieceIndex > 0:
Piece = ListOfMoves[PieceIndex].Piece
NewRow = ListOfMoves[PieceIndex].NewRow
NewColumn = ListOfMoves[PieceIndex].NewColumn
PlayersPieceIndex = int(Piece[1:])
CurrentRow = PlayersPieces[PlayersPieceIndex][ROW]
CurrentColumn = PlayersPieces[PlayersPieceIndex][COLUMN]
Jumping = ListOfMoves[PieceIndex].CanJump
Board, PlayersPieces = MovePiece(Board, PlayersPieces, Piece, NewRow, NewColumn)
if Jumping:
MiddlePieceRow = (CurrentRow + NewRow) // 2
MiddlePieceColumn = (CurrentColumn + NewColumn) // 2
MiddlePiece = Board[MiddlePieceRow][MiddlePieceColumn]
Player = Piece[0].lower()
if Player == 'a':
OppositePiecePlayer = 'b'
else:
OppositePiecePlayer = 'a'
if MiddlePiece[:1] == OppositePiecePlayer:
Board[MiddlePieceRow][MiddlePieceColumn] = SPACE
StolenPieceNumber = int(MiddlePiece[1:])
OpponentsPieces[StolenPieceNumber][0]=-1
OpponentsPieces[StolenPieceNumber][1]=-1
print('jumped over ', MiddlePiece)
return Board, PlayersPieces, OpponentsPieces
VB.NET
Function ValidJump(ByVal Board(,) As String, ByVal PlayersPieces(,) As Integer, ByVal Piece As String, ByVal NewRow As Integer, ByVal NewColumn As Integer) As Boolean
Dim Valid As Boolean
Dim MiddlePiece, Player, OppositePiecePlayer, MiddlePiecePlayer As String
Dim Index, CurrentRow, CurrentColumn, MiddlePieceRow, MiddlePieceColumn As Integer
Valid = False
MiddlePiece = ""
Player = Left(Piece, 1).ToLower()
Index = CInt(Piece.Substring(1))
If Player = "a" Then
OppositePiecePlayer = "b"
Else
OppositePiecePlayer = "a"
End If
If NewRow >= 0 And NewRow < BoardSize And NewColumn >= 0 And NewColumn < BoardSize Then
If Board(NewRow, NewColumn) = Space Then
CurrentRow = PlayersPieces(Index, Row)
CurrentColumn = PlayersPieces(Index, Column)
MiddlePieceRow = (CurrentRow + NewRow) \ 2
MiddlePieceColumn = (CurrentColumn + NewColumn) \ 2
MiddlePiece = Board(MiddlePieceRow, MiddlePieceColumn)
MiddlePiecePlayer = Left(MiddlePiece, 1).ToLower()
If MiddlePiecePlayer = OppositePiecePlayer Or MiddlePiecePlayer <> " " Then
Valid = True
End If
End If
End If
Return Valid
End Function
Sub MakeMove(ByRef Board(,) As String, ByRef PlayersPieces(,) As Integer, ByRef OpponentsPieces(,) As Integer, ByVal ListOfMoves() As MoveRecord, ByVal PieceIndex As Integer)
Dim Piece, MiddlePiece As String
Dim NewRow, NewColumn, PlayersPieceIndex, CurrentRow, CurrentColumn, MiddlePieceRow, MiddlePieceColumn As Integer
Dim Jumping As Boolean
PlayersPieces(0, 0) = PlayersPieces(0, 0) + 1
If PieceIndex > 0 Then
Piece = ListOfMoves(PieceIndex).Piece
NewRow = ListOfMoves(PieceIndex).NewRow
NewColumn = ListOfMoves(PieceIndex).NewColumn
If Len(Piece) = 2 Then
PlayersPieceIndex = CInt(Right(Piece, 1))
Else
PlayersPieceIndex = CInt(Right(Piece, 2))
End If
CurrentRow = PlayersPieces(PlayersPieceIndex, Row)
CurrentColumn = PlayersPieces(PlayersPieceIndex, Column)
Jumping = ListOfMoves(PieceIndex).CanJump
MovePiece(Board, PlayersPieces, Piece, NewRow, NewColumn, OpponentsPieces)
If Jumping Then
MiddlePieceRow = (CurrentRow + NewRow) \ 2
MiddlePieceColumn = (CurrentColumn + NewColumn) \ 2
MiddlePiece = Board(MiddlePieceRow, MiddlePieceColumn)
Dim Player As String = CStr(Piece(0)).ToLower
Dim OppositePiecePlayer As String = ""
Select Case Player
Case "a"
OppositePiecePlayer = "b"
Case "b"
OppositePiecePlayer = "a"
End Select
If Left(MiddlePiece, 1) = OppositePiecePlayer Then
Board(MiddlePieceRow, MiddlePieceColumn) = Space
End If
Dim StolenPieceNumber As Integer = Right(MiddlePiece, 1)
OpponentsPieces(StolenPieceNumber, 0) = -1
OpponentsPieces(StolenPieceNumber, 1) = -1
Console.WriteLine("jumped over " & MiddlePiece)
End If
End If
End Sub
在 Game() 中添加一个新的函数/方法。 数组中的所有元素都可以保存,没有要求错过每个数组的第一个元素。 查看 SetupBoard() 和 LoadPieces() 以更好地理解。
C#
意外创建
// Game: line 573 (addition)
// calls save function every turn, could be changed to explicit request for save but have not implemented that here
saveGame(A, B);
// New function - saves game
private static void saveGame(int[,] a, int[,] b)
{
StreamWriter writer = new StreamWriter("curGame.txt"); // name could be changed if required using strings passed in from main, but not used here
foreach (int num in a) { writer.WriteLine(num); } // iterate through A and B and write each to a line
foreach (int num in b) { writer.WriteLine(num); }
writer.Close();
Console.WriteLine("autosaved to curGame.txt");
}
Delphi/Pascal
Java
private void saveToFile(String fileName, int[][] a, int[][] b) {
try {
File file = new File("{ENTER DIRECTORY HERE WITH DOUBLE SLASHES}" + fileName + ".txt");
PrintWriter writer = new PrintWriter(file);
for (int[] i : a) {
for (int j : i) {
writer.println(j);
}
}
for (int[] i : b) {
for (int j : i) {
writer.println(j);
}
}
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//in game(), String fileSavedName declared at top.
Console.writeLine("Would you like to save the game at this point (Type S) Press enter if no");
if (sc.next().equalsIgnoreCase("S")) {
if (fileSavedName.equalsIgnoreCase("")) {
Console.writeLine("No existing file found, create a new one - type a file name.txt");
fileSavedName = sc.next();
saveToFile(fileSavedName, a, b, nextPlayer);
}
else {
saveToFile(fileSavedName, a, b, nextPlayer);
}
}
Python
#3.6 or later:
def SaveGame(A,B):
Filename = input("Enter File Name: ")
File= open(Filename,"w")
for x in A:
File.write(f"{x[0]}\n{x[1]}\n{x[2]}\n")
for x in B:
File.write(f"{x[0]}\n{x[1]}\n{x[2]}\n")
#Before 3.6:
def SaveGame(A,B):
saved = False
while saved == False:
saveName = input("Please input the file name you wish to use: ")
if saveName[(len(saveName)-4):] != '.txt':
saveName += '.txt'
try:
fileTest = open(saveName,'r')
overwrite = 'X'
while overwrite != 'Y' and overwrite != 'N':
overwrite = input("That file name has already been used. Do you want to overwrite it?")
if overwrite == 'Y':
print("Saving...")
continueSaving = True
elif overwrite == 'N':
continueSaving = False
else:
print("Sorry, that's not a valid option.")
except:
print("That file name has not yet been used. Saving...")
continueSaving = True
if continueSaving == True:
fileSave = open(saveName,'w')
for i in A:
fileSave.write(str(i[0]))
fileSave.write('\n')
fileSave.write(str(i[1]))
fileSave.write('\n')
fileSave.write(str(i[2]))
fileSave.write('\n')
for i in range(0,len(B)):
fileSave.write(str(B[i][0]))
fileSave.write('\n')
fileSave.write(str(B[i][1]))
fileSave.write('\n')
fileSave.write(str(B[i][2]))
if i != len(B)-1:
fileSave.write('\n')
saved = True
#All versions:
def PrintResult(A, B, NextPlayer, EndFromSave):
if EndFromSave == True:
print("Game saved. You can access this game at any time from the filename you specified.")
else:
print('Game ended')
print(NextPlayer,'lost this game as they cannot make a move')
PrintPlayerPieces(A, B)
def Game():
A = [[0, 0, 0] for Piece in range(NUMBER_OF_PIECES + 1)]
B = [[0, 0, 0] for Piece in range(NUMBER_OF_PIECES + 1)]
Board = [['' for Column in range(BOARD_SIZE)] for Row in range(BOARD_SIZE)]
ListOfMoves = [MoveRecord() for Move in range(MAX_MOVES)]
GameEnd = False
FileFound = False
NextPlayer = 'a'
Board, A, B, FileFound = SetUpBoard(Board, A, B, FileFound)
while FileFound == 'Error':
print("Sorry, an error occured. Please try again.")
Board, A, B, FileFound = SetUpBoard(Board, A, B, FileFound)
if not FileFound:
GameEnd = True
while not GameEnd:
PrintPlayerPieces(A, B)
DisplayBoard(Board)
print('Next Player: ', NextPlayer)
ListOfMoves = ClearList(ListOfMoves)
if NextPlayer == 'a':
ListOfMoves = ListPossibleMoves(Board, A, NextPlayer, ListOfMoves)
if not ListEmpty(ListOfMoves):
PieceIndex = SelectMove(ListOfMoves)
Board, A, B = MakeMove(Board, A, B, ListOfMoves, PieceIndex)
NextPlayer = SwapPlayer(NextPlayer)
else:
GameEnd = True
else:
ListOfMoves = ListPossibleMoves(Board, B, NextPlayer, ListOfMoves)
if not ListEmpty(ListOfMoves):
PieceIndex = SelectMove(ListOfMoves)
Board, B, A = MakeMove(Board, B, A, ListOfMoves, PieceIndex)
NextPlayer = SwapPlayer(NextPlayer)
else:
GameEnd = True
saveCheck = 'X'
while saveCheck != 'Y' and saveCheck != 'N' and not ListEmpty(ListOfMoves):
saveCheck = input("Do you want to save? (Y/N) ").upper()
if saveCheck == 'Y':
SaveGame(A,B)
GameEnd = True
EndFromSave = True
elif saveCheck != 'N':
print("Sorry, that's not a valid option.")
if FileFound:
try:
if EndFromSave == False:
print("")
except:
EndFromSave = False
print("")
PrintResult(A, B , NextPlayer, EndFromSave)
VB.NET
Sub Game()
Dim A(NumberOfPieces, 2) As Integer
Dim B(NumberOfPieces, 2) As Integer
Dim Board(BoardSize - 1, BoardSize - 1) As String
Dim ListOfMoves(MaxMoves - 1) As MoveRecord
Dim NextPlayer As String
Dim FileFound, GameEnd As Boolean
Dim PieceIndex As Integer
Dim MovesA As Integer = 0
Dim MovesB As Integer = 0
GameEnd = False
FileFound = False
Dim RepeatRandomNumber As Boolean = True
While RepeatRandomNumber
Dim RN As Integer = Rnd(Int(1))
If RN = 0 Then
NextPlayer = "a"
RepeatRandomNumber = False
End If
If RN = 1 Then
NextPlayer = "b"
RepeatRandomNumber = False
End If
End While
NextPlayer = "a"
SetUpBoard(Board, A, B, FileFound)
If Not FileFound Then
GameEnd = True
End If
While Not GameEnd
PrintPlayerPieces(A, B)
DisplayBoard(Board)
Console.WriteLine("Next Player: " & NextPlayer)
ClearList(ListOfMoves)
If NextPlayer = "a" Then
ListPossibleMoves(Board, A, NextPlayer, ListOfMoves)
If Not ListEmpty(ListOfMoves) Then
PieceIndex = SelectMove(ListOfMoves)
MakeMove(Board, A, B, ListOfMoves, PieceIndex)
NextPlayer = SwapPlayer(NextPlayer)
MovesA += 1
Else
GameEnd = True
End If
Else
ListPossibleMoves(Board, B, NextPlayer, ListOfMoves)
If Not ListEmpty(ListOfMoves) Then
PieceIndex = SelectMove(ListOfMoves)
MakeMove(Board, B, A, ListOfMoves, PieceIndex)
NextPlayer = SwapPlayer(NextPlayer)
MovesB += 1
Else
GameEnd = True
End If
Dim SaveGame As String = "N"
Console.WriteLine("Do you want to save the board? (Y/N)")
SaveGame = Console.ReadLine()
If SaveGame = "Y" Or SaveGame = "y" Then
Dim FileName As String
Console.WriteLine("Enter a name for the file")
FileName = Console.ReadLine()
If Right(FileName, 4) <> ".txt" Then
FileName = FileName & ".txt"
End If
SaveGameSubA(FileName, A)
SaveGameSubB(FileName, B)
End If
End If
End While
If FileFound Then
Console.WriteLine("Player A used " & MovesA & " moves")
Console.WriteLine("Player B used " & MovesB & " moves")
PrintResult(A, B, NextPlayer)
End If
Console.ReadLine()
End Sub
Sub SaveGameSubA(ByVal FileName As String, ByRef PlayersPieces(,) As Integer)
Dim FileHandle As New System.IO.StreamWriter(FileName, True)
Dim Index As Integer
For Index = 0 To 12
FileHandle.WriteLine(PlayersPieces(Index, Row))
FileHandle.WriteLine(PlayersPieces(Index, Column))
FileHandle.WriteLine(PlayersPieces(Index, Dame))
Next
FileHandle.Close()
End Sub
Sub SaveGameSubB(ByVal FileName As String, ByRef PlayersPieces(,) As Integer)
Dim FileHandle As New System.IO.StreamWriter(FileName, True)
Dim Index As Integer
For Index = 0 To 12
FileHandle.WriteLine(PlayersPieces(Index, Row))
FileHandle.WriteLine(PlayersPieces(Index, Column))
FileHandle.WriteLine(PlayersPieces(Index, Dame))
Next
FileHandle.Close()
End Sub
当前,所有保存的游戏都会让 A 下一回合,即使 A 是最后一次轮到的人。 这对于扮演 B 的人来说是不公平的。 您需要修改您对保存游戏的实现以及游戏自己的加载游戏和主子程序才能实现这一点。
C#
Delphi/Pascal
Java
Python
VB.NET
如果没有空间创建“王”,则不允许进行此移动。 您可能需要编辑 ListPossibleMoves() 来实现这一点。
C#
由 Brockenhurst College 的 Sol 编写。
private static void ListPossibleMoves(string[,] board, int[,] playersPieces, string nextPlayer, MoveRecord[] listOfMoves)
{
int direction, numberOfMoves = 0; ;
int currentColumn, leftColumn, rightColumn;
int jumpLeftColumn, jumpRightColumn;
int currentRow, newRow, jumpRow;
string piece;
if (nextPlayer == "a")
{
direction = 1;
}
else
{
direction = -1;
}
for (int i = 1; i < NumberOfPieces + 1; i++)
{
piece = nextPlayer + i;
currentRow = playersPieces[i, Row];
currentColumn = playersPieces[i, Column];
if (playersPieces[i, Dame] == 1)
{
piece = piece.ToUpper();
}
newRow = currentRow + direction;
leftColumn = currentColumn - 1;
rightColumn = currentColumn + 1;
if (ValidMove(board, newRow, leftColumn) && (newRow != BoardSize - 1 && newRow != 0))
{//same selection as before + checking whether the next row is top or bottom row
Console.WriteLine(piece + " can move to " + newRow + " , " + leftColumn);
numberOfMoves++;
listOfMoves[numberOfMoves].Piece = piece;
listOfMoves[numberOfMoves].NewRow = newRow;
listOfMoves[numberOfMoves].NewColumn = leftColumn;
listOfMoves[numberOfMoves].CanJump = false;
}
else if (ValidMove(board, newRow, leftColumn) && CheckDameRow(board))
{//copied original selection as above + checking for top and bottom row availibility
Console.WriteLine(piece + " can move to " + newRow + " , " + leftColumn);
numberOfMoves++;
listOfMoves[numberOfMoves].Piece = piece;
listOfMoves[numberOfMoves].NewRow = newRow;
listOfMoves[numberOfMoves].NewColumn = leftColumn;
listOfMoves[numberOfMoves].CanJump = false;
}
if (ValidMove(board, newRow, rightColumn) && (newRow != BoardSize - 1 && newRow != 0))
{//same selection as before + you know the drill
Console.WriteLine(piece + " can move to " + newRow + " , " + rightColumn);
numberOfMoves++;
listOfMoves[numberOfMoves].Piece = piece;
listOfMoves[numberOfMoves].NewRow = newRow;
listOfMoves[numberOfMoves].NewColumn = rightColumn;
listOfMoves[numberOfMoves].CanJump = false;
}
else if (ValidMove(board, newRow, rightColumn) && CheckDameRow(board))
{//copied selection as before + you know the drill
Console.WriteLine(piece + " can move to " + newRow + " , " + rightColumn);
numberOfMoves++;
listOfMoves[numberOfMoves].Piece = piece;
listOfMoves[numberOfMoves].NewRow = newRow;
listOfMoves[numberOfMoves].NewColumn = rightColumn;
listOfMoves[numberOfMoves].CanJump = false;
}
jumpRow = currentRow + direction + direction;
jumpLeftColumn = currentColumn - 2;
jumpRightColumn = currentColumn + 2;
if (ValidJump(board, playersPieces, piece, jumpRow, jumpLeftColumn) && (jumpRow != BoardSize - 1 && jumpRow != 0))
{//done same as above
Console.WriteLine(piece + " can jump to " + jumpRow + " , " + jumpLeftColumn);
numberOfMoves++;
listOfMoves[numberOfMoves].Piece = piece;
listOfMoves[numberOfMoves].NewRow = jumpRow;
listOfMoves[numberOfMoves].NewColumn = jumpLeftColumn;
listOfMoves[numberOfMoves].CanJump = true;
}
else if (ValidJump(board, playersPieces, piece, jumpRow, jumpLeftColumn) && CheckDameRow(board))
{//same as above
Console.WriteLine(piece + " can jump to " + jumpRow + " , " + jumpLeftColumn);
numberOfMoves++;
listOfMoves[numberOfMoves].Piece = piece;
listOfMoves[numberOfMoves].NewRow = jumpRow;
listOfMoves[numberOfMoves].NewColumn = jumpLeftColumn;
listOfMoves[numberOfMoves].CanJump = true;
}
if (ValidJump(board, playersPieces, piece, jumpRow, jumpRightColumn) && (jumpRow != BoardSize - 1 && jumpRow != 0))
{//same as above
Console.WriteLine(piece + " can jump to " + jumpRow + " , " + jumpRightColumn);
numberOfMoves++;
listOfMoves[numberOfMoves].Piece = piece;
listOfMoves[numberOfMoves].NewRow = jumpRow;
listOfMoves[numberOfMoves].NewColumn = jumpRightColumn;
listOfMoves[numberOfMoves].CanJump = true;
}
else if (ValidJump(board, playersPieces, piece, jumpRow, jumpRightColumn) && CheckDameRow(board))
{//same as above
Console.WriteLine(piece + " can jump to " + jumpRow + " , " + jumpRightColumn);
numberOfMoves++;
listOfMoves[numberOfMoves].Piece = piece;
listOfMoves[numberOfMoves].NewRow = jumpRow;
listOfMoves[numberOfMoves].NewColumn = jumpRightColumn;
listOfMoves[numberOfMoves].CanJump = true;
}
}
Console.WriteLine("There are " + numberOfMoves + " possible moves");
}
private static bool CheckDameRow(string[,] board)
{//added new method to check for availability on the top and bottom row
bool validA = false, validB = false;
for (int i = 0; i < 4; i++)
{
if (board[0, 2 * i + 1] == Space)
validA = true;
if (board[BoardSize - 1, 2 * i] == Space)
validB = true;
}
if (validA && validB)
return true;
else
return false;
}
Delphi/Pascal
Java
Python
VB.NET
“王”似乎有点平淡无奇。 为什么不让“王”也能够垂直移动 2 格? 或者斜着移动 2 格? 我建议在 ListPossibleMoves() 中全部完成,通过设置一个布尔值来设置为 True,如果当前棋子是“王”,并且在现有的移动检查之后添加一个新的选择语句,将新的移动添加到列表中。 使用 game3.txt 测试起来非常容易。 也许让它像国际象棋中的皇后一样移动? 或者至少能够向后移动。
C#
Delphi/Pascal
Java
Python
#Note that this code only allows the dame to move backwards - not any of the other mentioned potential functionality.
def TestMove(Piece,Board,NewRow,LeftColumn,RightColumn,JumpRow,JumpLeftColumn,JumpRightColumn,ListOfMoves,NumberOfMoves,PlayersPieces):
if ValidMove(Board, NewRow, LeftColumn):
print(Piece, ' can move to ', NewRow, ' , ', LeftColumn)
NumberOfMoves += 1
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = NewRow
ListOfMoves[NumberOfMoves].NewColumn = LeftColumn
ListOfMoves[NumberOfMoves].CanJump = False
if ValidMove(Board, NewRow, RightColumn):
print(Piece, ' can move to ', NewRow, ' , ', RightColumn)
NumberOfMoves += 1
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = NewRow
ListOfMoves[NumberOfMoves].NewColumn = RightColumn
ListOfMoves[NumberOfMoves].CanJump = False
if ValidJump(Board, PlayersPieces, Piece, JumpRow, JumpLeftColumn):
print(Piece, ' can jump to ', JumpRow, ' , ', JumpLeftColumn)
NumberOfMoves += 1
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = JumpRow
ListOfMoves[NumberOfMoves].NewColumn = JumpLeftColumn
ListOfMoves[NumberOfMoves].CanJump = True
if ValidJump(Board, PlayersPieces, Piece, JumpRow, JumpRightColumn):
print(Piece, ' can jump to ', JumpRow, ' , ', JumpRightColumn)
NumberOfMoves += 1
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = JumpRow
ListOfMoves[NumberOfMoves].NewColumn = JumpRightColumn
ListOfMoves[NumberOfMoves].CanJump = True
return ListOfMoves,NumberOfMoves
def ListPossibleMoves(Board, PlayersPieces, NextPlayer, ListOfMoves):
if NextPlayer == 'a':
Direction = 1
else:
Direction = -1
NumberOfMoves = 0
for i in range(1, NUMBER_OF_PIECES + 1):
Piece = NextPlayer + str(i)
CurrentRow = PlayersPieces[i][ROW]
CurrentColumn = PlayersPieces[i][COLUMN]
if PlayersPieces[i][DAME] == 1:
Piece = Piece.upper()
NewRow = CurrentRow + Direction
LeftColumn = CurrentColumn - 1
RightColumn = CurrentColumn + 1
JumpRow = CurrentRow + Direction + Direction
JumpLeftColumn = CurrentColumn - 2
JumpRightColumn = CurrentColumn + 2
ListOfMoves,NumberOfMoves = TestMove(Piece,Board,NewRow,LeftColumn,RightColumn,JumpRow,JumpLeftColumn,JumpRightColumn,ListOfMoves,NumberOfMoves,PlayersPieces)
if PlayersPieces[i][DAME] == 1:
NewRow = CurrentRow - Direction
JumpRow = CurrentRow - Direction - Direction
ListOfMoves,NumberOfMoves = TestMove(Piece,Board,NewRow,LeftColumn,RightColumn,JumpRow,JumpLeftColumn,JumpRightColumn,ListOfMoves,NumberOfMoves,PlayersPieces)
print('There are ', NumberOfMoves, ' possible moves')
return ListOfMoves
VB.NET
让 AI 控制 B,而不是让另一个玩家控制它。 设置起来并不难。 我建议用一个新的函数来替换 Game() 中对 SelectMove() 的函数调用,以生成一个有效的 pieceIndex。 AI 的工作方式可以由你决定,无论是随机的还是有策略的。
C#
Delphi/Pascal
Java
Python
#If Player B can make a move that will cause a piece to become a dame, it will do so. If not, it picks a random move.
def ComputerMove(ListOfMoves):
FoundPiece = False
for i in range(0,len(ListOfMoves)-1):
if ListOfMoves[i].NewRow == 0:
Index = i
Piece = ListOfMoves[i].Piece
NewRow = ListOfMoves[i].NewRow
NewColumn = ListOfMoves[i].NewColumn
FoundPiece = True
while FoundPiece == False:
i = random.randint(0,len(ListOfMoves)-1)
if ListOfMoves[i].NewRow != -1:
Index = i
Piece = ListOfMoves[i].Piece
NewRow = ListOfMoves[i].NewRow
NewColumn = ListOfMoves[i].NewColumn
FoundPiece = True
print("""Piece Moved: {0}
Row moved to: {1}
Column moved to: {2}""".format(Piece,NewRow,NewColumn))
return Index
def Game():
A = [[0, 0, 0] for Piece in range(NUMBER_OF_PIECES + 1)]
B = [[0, 0, 0] for Piece in range(NUMBER_OF_PIECES + 1)]
Board = [['' for Column in range(BOARD_SIZE)] for Row in range(BOARD_SIZE)]
ListOfMoves = [MoveRecord() for Move in range(MAX_MOVES)]
GameEnd = False
FileFound = False
NextPlayer = 'a'
Board, A, B, FileFound = SetUpBoard(Board, A, B, FileFound)
if not FileFound:
GameEnd = True
while not GameEnd:
PrintPlayerPieces(A, B)
DisplayBoard(Board)
print('Next Player: ', NextPlayer)
ListOfMoves = ClearList(ListOfMoves)
if NextPlayer == 'a':
ListOfMoves = ListPossibleMoves(Board, A, NextPlayer, ListOfMoves)
if not ListEmpty(ListOfMoves):
PieceIndex = SelectMove(ListOfMoves)
Board, A, B = MakeMove(Board, A, B, ListOfMoves, PieceIndex)
NextPlayer = SwapPlayer(NextPlayer)
else:
GameEnd = True
else:
ListOfMoves = ListPossibleMoves(Board, B, NextPlayer, ListOfMoves)
if not ListEmpty(ListOfMoves):
PieceIndex = ComputerMove(ListOfMoves)
Board, B, A = MakeMove(Board, B, A, ListOfMoves, PieceIndex)
NextPlayer = SwapPlayer(NextPlayer)
else:
GameEnd = True
if FileFound:
PrintResult(A, B , NextPlayer)
VB.NET
'Option for player B to be controlled by computer, in which case player B makes a random move
Function SelectMove(ByVal ListOfMoves() As MoveRecord, ByVal Computer As Boolean, NextPlayer As String) As Integer
Dim ValidPiece, ValidMove, Found, EndOfList As Boolean
Dim RowString, ColumnString As String
Dim Piece As String = ""
Dim Index, ChosenPieceIndex, NewRow, NewColumn As Integer
ValidPiece = False
Dim ComputerPieceNum As Integer
Dim ComputerRow As Integer
Dim ComputerColumn As Integer
Dim Repeat As Boolean = True
If Computer And NextPlayer = "b" Then
While Not ValidPiece
While Repeat
ComputerPieceNum = Int((12 * Rnd()) + 1)
Piece = "b" & ComputerPieceNum
If Piece = "" Then
EndOfList = True
End If
While Not Found And Not EndOfList
Index = Index + 1
If ListOfMoves(Index).Piece = Piece Then
Found = True
ElseIf ListOfMoves(Index).Piece = "" Then
EndOfList = True
'DisplayErrorCode(1)
End If
End While
If Found Then
ValidPiece = True
Repeat = False
End If
End While
ChosenPieceIndex = Index
ValidMove = False
While Not ValidMove
ComputerRow = Int((9 * Rnd()))
RowString = ComputerRow
ComputerColumn = Int((9 * Rnd()))
ColumnString = ComputerColumn
Try
NewRow = CInt(RowString)
NewColumn = CInt(ColumnString)
Found = False
EndOfList = False
Index = ChosenPieceIndex - 1
While Not Found And Not EndOfList
Index = Index + 1
If ListOfMoves(Index).Piece <> Piece Then
EndOfList = True
'DisplayErrorCode(2)
ElseIf (ListOfMoves(Index).NewRow = NewRow) And (ListOfMoves(Index).NewColumn = NewColumn) Then
Found = True
End If
End While
ValidMove = Found
Catch
'DisplayErrorCode(3)
End Try
End While
End While
Else
Found = False
EndOfList = False
Console.Write("Which piece do you want to move? ")
Piece = Console.ReadLine()
Index = 0
If Piece = "" Then
EndOfList = True
End If
While Not Found And Not EndOfList
Index = Index + 1
If ListOfMoves(Index).Piece = Piece Then
Found = True
ElseIf ListOfMoves(Index).Piece = "" Then
EndOfList = True
DisplayErrorCode(1)
End If
End While
If Found Then
ValidPiece = True
End If
ChosenPieceIndex = Index
ValidMove = False
While Not ValidMove
Console.Write("Which row do you want to move to? ")
RowString = Console.ReadLine
Console.Write("Which column do you want to move to? ")
ColumnString = Console.ReadLine
Try
NewRow = CInt(RowString)
NewColumn = CInt(ColumnString)
Found = False
EndOfList = False
Index = ChosenPieceIndex - 1
While Not Found And Not EndOfList
Index = Index + 1
If ListOfMoves(Index).Piece <> Piece Then
EndOfList = True
DisplayErrorCode(2)
ElseIf (ListOfMoves(Index).NewRow = NewRow) And (ListOfMoves(Index).NewColumn = NewColumn) Then
Found = True
End If
End While
ValidMove = Found
Catch
DisplayErrorCode(3)
End Try
End While
End If
Return Index
End Function
Sub Game()
Dim A(NumberOfPieces, 2) As Integer
Dim B(NumberOfPieces, 2) As Integer
Dim Board(BoardSize - 1, BoardSize - 1) As String
Dim ListOfMoves(MaxMoves - 1) As MoveRecord
Dim NextPlayer As String
Dim FileFound, GameEnd As Boolean
Dim PieceIndex As Integer
Dim Computer As Boolean = False
Dim ComputerYN
GameEnd = False
FileFound = False
NextPlayer = "a"
SetUpBoard(Board, A, B, FileFound)
Console.WriteLine("Would you like player B to be controlled by the computer? (Y/N)")
ComputerYN = Console.ReadLine()
If ComputerYN = "Y" Or ComputerYN = "y" Then
Computer = True
End If
If Not FileFound Then
GameEnd = True
End If
While Not GameEnd
PrintPlayerPieces(A, B)
DisplayBoard(Board)
Console.WriteLine("Next Player: " & NextPlayer)
ClearList(ListOfMoves)
If NextPlayer = "a" Then
ListPossibleMoves(Board, A, NextPlayer, ListOfMoves)
If Not ListEmpty(ListOfMoves) Then
PieceIndex = SelectMove(ListOfMoves, Computer, NextPlayer)
MakeMove(Board, A, B, ListOfMoves, PieceIndex)
NextPlayer = SwapPlayer(NextPlayer)
Else
GameEnd = True
End If
Else
ListPossibleMoves(Board, B, NextPlayer, ListOfMoves)
If Not ListEmpty(ListOfMoves) Then
PieceIndex = SelectMove(ListOfMoves, Computer, NextPlayer)
MakeMove(Board, B, A, ListOfMoves, PieceIndex)
NextPlayer = SwapPlayer(NextPlayer)
Else
GameEnd = True
End If
End If
End While
If FileFound Then
PrintResult(A, B, NextPlayer)
End If
Console.ReadLine()
End Sub
给用户一个选项,让他们添加一个自定义游戏文件(例如,创建另一个默认文件供选择(例如 game5.txt)),并允许用户决定棋子的起始位置,以及棋子的数量和类型。
C#
Delphi/Pascal
Java
Python
def SetPieceLocation(PieceCreated,PieceDame,PieceRow,PieceColumn,Board,PiecesSoFar):
if 0 <= PieceRow < BOARD_SIZE and 0 <= PieceColumn < BOARD_SIZE:
if PieceDame == 'Y':
PieceDame = 1
else:
PieceDame = 0
if [PieceRow,PieceColumn,0] not in PiecesSoFar and [PieceRow,PieceColumn,1] not in PiecesSoFar:
if Board[PieceRow][PieceColumn] == SPACE:
PieceCreated = True
else:
print("Invalid Location - Location is not a space.")
else:
print("Invalid Location - Location has already been used.")
else:
print("Invalid Location - Row and Column must be a natural number lower than the board size of {0}.".format(BOARD_SIZE))
return PieceCreated,PieceDame
def GetPieceInfo(PiecesPerPlayer,Board,PlayerPieces):
for i in range(1,PiecesPerPlayer+1):
PieceCreated = False
while PieceCreated != True:
try:
print("Piece {0} of {1}:".format(i,PiecesPerPlayer))
PieceRow = int(input("What row will this piece be on? "))
PieceColumn = int(input("What column will this piece be on? "))
PieceDame = input("Is this piece a dame? (Y/N) ").upper()
if PieceDame == 'Y' or PieceDame == 'N':
PieceCreated,PieceDame = SetPieceLocation(PieceCreated,PieceDame,PieceRow,PieceColumn,Board,PlayerPieces)
else:
print("Invalid Dame Response - Must be Y or N.")
except ValueError:
print("Invalid Location - Row and Column must be a natural number lower than the board size of {0}.".format(BOARD_SIZE))
PlayerPieces.append([PieceRow,PieceColumn,PieceDame])
return PlayerPieces
def CreateAllPieces(Board,PiecesPerPlayer):
print("Player A:")
A = [[0,0,0]]
A = GetPieceInfo(PiecesPerPlayer,Board,A)
for i in range(0,NUMBER_OF_PIECES-PiecesPerPlayer):
A.append([-1,-1,0])
print("Player B:")
B = [[0,0,0]]
B = GetPieceInfo(PiecesPerPlayer,Board,B)
for i in range(0,NUMBER_OF_PIECES-PiecesPerPlayer):
B.append([-1,-1,0])
return Board,A,B
def CreateCustomBoard(Board):
Board = CreateNewBoard(Board)
PiecesPerPlayer = NUMBER_OF_PIECES + 1
while PiecesPerPlayer <= 0 or PiecesPerPlayer > NUMBER_OF_PIECES:
try:
PiecesPerPlayer = int(input("How many pieces do you want each player to have? "))
if PiecesPerPlayer <= 0:
print("Sorry, your value must be at least 1.")
elif PiecesPerPlayer > NUMBER_OF_PIECES:
print("Sorry, your value is too high to load all the pieces.")
except ValueError:
print("Sorry, but your value needs to be an integer.")
Board, A, B = CreateAllPieces(Board,PiecesPerPlayer)
Board = AddPlayerA(Board, A)
Board = AddPlayerB(Board, B)
SaveGame(A,B)
return A, B, Board
def SetUpBoard(Board, A, B, FileFound):
while True:
Answer = input('Do you want to load a saved game or board template? (Y/N): ').upper()
if Answer == 'Y':
FileName = input('Enter the filename: ')
if FileName[(len(FileName)-4):] != '.txt':
FileName += '.txt'
try:
FileHandle = open(FileName, 'r')
FileFound = True
A = LoadPieces(FileHandle, A)
B = LoadPieces(FileHandle, B)
FileHandle.close()
Board = CreateNewBoard(Board)
Board = AddPlayerA(Board, A)
Board = AddPlayerB(Board, B)
break
except:
DisplayErrorCode(4)
FileFound == 'Error'
elif Answer == 'N':
SecondAnswer = input('Do you want to create a custom board? (Y/N): ').upper()
if SecondAnswer == 'Y':
A, B, Board = CreateCustomBoard(Board)
FileFound = True
break
elif SecondAnswer == 'N':
A, B, Board = '', '', []
break
else:
print("Sorry, that's not a valid answer.")
else:
print("Sorry, that's not a valid answer.")
return Board, A, B, FileFound
VB.NET
像跳棋一样双跳
[edit | edit source]传统的跳棋游戏允许“双跳”,如果你进行了一次跳跃并且可以在上述跳跃之后进行第二次跳跃,那么你可以选择是否进行。你可以使用 game3.txt 来帮助使用 a6 棋子。
C#
Delphi/Pascal
Java
//class change - added doubleJump boolean to be used to check if piece can double jump.
class MoveRecord {
String piece = "";
int newRow = -1;
int newColumn = -1;
boolean canJump = false;
boolean canDoubleJump = false;
}
//from function [ListPossibleMoves] in one jump section
if (validJump(board, playersPieces, piece, jumpRow, jumpLeftColumn)) {
//all the other stuff was deleted
//here youre "predicting" where the piece will jump to next and you want to check if the area is SPACE.
currentRow += direction > 0 ? -2 : 2; //if direction is -1, currentRow after jump is incremented by -2, else, 2
currentColumn -= 2; //current column is 2 after left jump (jumpLeftColumn above)
jumpRow = currentRow + direction * 2; //calculating which row youll jump to next
jumpLeftColumn = currentColumn - 2; //if jumped left
jumpRightColumn = currentColumn + 2; // if jumped right
//you now have these variables that will be used in the if statement below:
try {
if (board[jumpRow][jumpLeftColumn].equals(SPACE) || board[jumpRow][jumpRightColumn].equals(SPACE)) {
//if space at jump location
listOfMoves[numberOfMoves].canDoubleJump = true; //update class object
}
} catch (Exception ignored) { //in case its out of bounds, continue flow (ignore error)
}
//were at game() now, main game loop
while(!gameEnd) {
//all the other code
if (!listOfMoves[pieceIndex].canDoubleJump) { //if selected piece doesnt have doubleJump = true, player swapped.
nextPlayer = swapPlayer(nextPlayer);
}
//if player wishes to skip their double jump, the 'skip' command can be used (implemented already)
Python
#Note that double jumps are not compulsory if they are possible.
def TestMove(Piece,Board,NewRow,LeftColumn,RightColumn,JumpRow,JumpLeftColumn,JumpRightColumn,ListOfMoves,NumberOfMoves,PlayersPieces,jumpsOnly,PieceMoved):
if jumpsOnly == False:
if ValidMove(Board, NewRow, LeftColumn):
print(Piece, ' can move to ', NewRow, ' , ', LeftColumn)
NumberOfMoves += 1
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = NewRow
ListOfMoves[NumberOfMoves].NewColumn = LeftColumn
ListOfMoves[NumberOfMoves].CanJump = False
if ValidMove(Board, NewRow, RightColumn):
print(Piece, ' can move to ', NewRow, ' , ', RightColumn)
NumberOfMoves += 1
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = NewRow
ListOfMoves[NumberOfMoves].NewColumn = RightColumn
ListOfMoves[NumberOfMoves].CanJump = False
if ValidJump(Board, PlayersPieces, Piece, JumpRow, JumpLeftColumn):
print(Piece, ' can jump to ', JumpRow, ' , ', JumpLeftColumn)
NumberOfMoves += 1
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = JumpRow
ListOfMoves[NumberOfMoves].NewColumn = JumpLeftColumn
ListOfMoves[NumberOfMoves].CanJump = True
if ValidJump(Board, PlayersPieces, Piece, JumpRow, JumpRightColumn):
print(Piece, ' can jump to ', JumpRow, ' , ', JumpRightColumn)
NumberOfMoves += 1
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = JumpRow
ListOfMoves[NumberOfMoves].NewColumn = JumpRightColumn
ListOfMoves[NumberOfMoves].CanJump = True
else:
if ValidJump(Board, PlayersPieces, Piece, JumpRow, JumpLeftColumn) and Piece == PieceMoved:
print(Piece, ' can jump to ', JumpRow, ' , ', JumpLeftColumn)
NumberOfMoves += 1
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = JumpRow
ListOfMoves[NumberOfMoves].NewColumn = JumpLeftColumn
ListOfMoves[NumberOfMoves].CanJump = True
if ValidJump(Board, PlayersPieces, Piece, JumpRow, JumpRightColumn) and Piece == PieceMoved:
print(Piece, ' can jump to ', JumpRow, ' , ', JumpRightColumn)
NumberOfMoves += 1
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = JumpRow
ListOfMoves[NumberOfMoves].NewColumn = JumpRightColumn
ListOfMoves[NumberOfMoves].CanJump = True
return ListOfMoves,NumberOfMoves
def ListPossibleMoves(Board, PlayersPieces, NextPlayer, ListOfMoves, jumpsOnly, PieceMoved):
if NextPlayer == 'a':
Direction = 1
else:
Direction = -1
NumberOfMoves = 0
for i in range(1, NUMBER_OF_PIECES + 1):
Piece = NextPlayer + str(i)
CurrentRow = PlayersPieces[i][ROW]
CurrentColumn = PlayersPieces[i][COLUMN]
if PlayersPieces[i][DAME] == 1:
Piece = Piece.upper()
NewRow = CurrentRow + Direction
LeftColumn = CurrentColumn - 1
RightColumn = CurrentColumn + 1
JumpRow = CurrentRow + Direction + Direction
JumpLeftColumn = CurrentColumn - 2
JumpRightColumn = CurrentColumn + 2
ListOfMoves,NumberOfMoves = TestMove(Piece,Board,NewRow,LeftColumn,RightColumn,JumpRow,JumpLeftColumn,JumpRightColumn,ListOfMoves,NumberOfMoves,PlayersPieces,jumpsOnly,PieceMoved)
print('There are ', NumberOfMoves, ' possible moves')
return ListOfMoves
def MakeMove(Board, PlayersPieces, OpponentsPieces, ListOfMoves, PieceIndex, canDoubleJump):
PlayersPieces[0][0] += 1
if PieceIndex > 0:
Piece = ListOfMoves[PieceIndex].Piece
NewRow = ListOfMoves[PieceIndex].NewRow
NewColumn = ListOfMoves[PieceIndex].NewColumn
PlayersPieceIndex = int(Piece[1:])
CurrentRow = PlayersPieces[PlayersPieceIndex][ROW]
CurrentColumn = PlayersPieces[PlayersPieceIndex][COLUMN]
Jumping = ListOfMoves[PieceIndex].CanJump
Board, PlayersPieces = MovePiece(Board, PlayersPieces, Piece, NewRow, NewColumn)
if Jumping:
MiddlePieceRow = (CurrentRow + NewRow) // 2
MiddlePieceColumn = (CurrentColumn + NewColumn) // 2
MiddlePiece = Board[MiddlePieceRow][MiddlePieceColumn]
Player = Piece[0].lower()
print('jumped over ', MiddlePiece)
if canDoubleJump == False:
canDoubleJump = True
else:
canDoubleJump = False
else:
canDoubleJump = False
return Board, PlayersPieces, OpponentsPieces, canDoubleJump
def Game():
A = [[0, 0, 0] for Piece in range(NUMBER_OF_PIECES + 1)]
B = [[0, 0, 0] for Piece in range(NUMBER_OF_PIECES + 1)]
Board = [['' for Column in range(BOARD_SIZE)] for Row in range(BOARD_SIZE)]
ListOfMoves = [MoveRecord() for Move in range(MAX_MOVES)]
GameEnd = False
FileFound = False
NextPlayer = 'a'
Board, A, B, FileFound = SetUpBoard(Board, A, B, FileFound)
while FileFound == 'Error':
print("Sorry, an error occured. Please try again.")
Board, A, B, FileFound = SetUpBoard(Board, A, B, FileFound)
if not FileFound:
GameEnd = True
while not GameEnd:
canDoubleJump = False
PrintPlayerPieces(A, B)
DisplayBoard(Board)
print('Next Player: ', NextPlayer)
ListOfMoves = ClearList(ListOfMoves)
if NextPlayer == 'a':
ListOfMoves = ListPossibleMoves(Board, A, NextPlayer, ListOfMoves, False, 'x0')
if not ListEmpty(ListOfMoves):
PieceIndex,PieceMoved = SelectMove(ListOfMoves)
Board, A, B, canDoubleJump = MakeMove(Board, A, B, ListOfMoves, PieceIndex, canDoubleJump)
if canDoubleJump == True:
ListOfMoves = ClearList(ListOfMoves)
ListOfMoves = ListPossibleMoves(Board, A, NextPlayer, ListOfMoves, True, PieceMoved)
if not ListEmpty(ListOfMoves):
skipJump = 'X'
while skipJump != 'N' and skipJump != 'Y':
skipJump = input("Do you wish to skip your double jump? (Y/N) ").upper()
if skipJump != 'N' and skipJump != 'Y':
print("Sorry, please input 'Y' or 'N'.")
if skipJump == 'N':
PieceIndex,PieceMoved = SelectMove(ListOfMoves)
Board, A, B, canDoubleJump = MakeMove(Board, A, B, ListOfMoves, PieceIndex, canDoubleJump)
NextPlayer = SwapPlayer(NextPlayer)
else:
GameEnd = True
else:
ListOfMoves = ListPossibleMoves(Board, B, NextPlayer, ListOfMoves, False, 'x0')
if not ListEmpty(ListOfMoves):
PieceIndex,PieceMoved = SelectMove(ListOfMoves)
Board, B, A, canDoubleJump = MakeMove(Board, B, A, ListOfMoves, PieceIndex, canDoubleJump)
if canDoubleJump == True:
ListOfMoves = ClearList(ListOfMoves)
ListOfMoves = ListPossibleMoves(Board, B, NextPlayer, ListOfMoves, True, PieceMoved)
if not ListEmpty(ListOfMoves):
skipJump = 'X'
while skipJump != 'N' and skipJump != 'Y':
skipJump = input("Do you wish to skip your double jump? (Y/N) ").upper()
if skipJump != 'N' and skipJump != 'Y':
print("Sorry, please input 'Y' or 'N'.")
if skipJump == 'N':
PieceIndex,PieceMoved = SelectMove(ListOfMoves)
Board, B, A, canDoubleJump = MakeMove(Board, B, A, ListOfMoves, PieceIndex, canDoubleJump)
NextPlayer = SwapPlayer(NextPlayer)
else:
GameEnd = True
if FileFound:
PrintResult(A, B , NextPlayer)
VB.NET
尝试下一行以添加“dame”
[edit | edit source]与之前的问题类似:如果没有空间在主行上创建“dame”,尝试下一行,并继续这样做直到它可以放置“dame”。
C#
Delphi/Pascal
Java
Python
def MoveDame(Board, Player, NewRow, NewColumn):
spaceFound = False #Allows the program to stop looking for an empty space when one is found
if Player == 'a':
lookupRow = 0 #Starts from the top
rowInc = 1 #Goes downwards
else:
lookupRow = BOARD_SIZE - 1 #Starts from the bottom
rowInc = -1 #Goes upwards
while spaceFound == False:
for i in range (0, BOARD_SIZE - 1):
if Board[lookupRow][i] == SPACE: #Checks if the space is empty
NewColumn = i #Sets new co-ordinates
NewRow = lookupRow
spaceFound == True #Used to break out of the while loop
break #Breaks out of the for loop
lookupRow += rowInc #Goes to the next row, as no empty spaces found
return NewRow, NewColumn
VB.NET
随机玩家开始
[edit | edit source]随机玩家开始
C#
意外创建
// Game: line 563 (change)
// this kind of breaks save games as it will still choose a random player in that situation, but IIRC this would occur anyway if a save was made on B's turn
string nextPlayer = new Random().Next(2) == 0 ? "a" : "b";
Delphi/Pascal
Java
private void game() {
//rest of the code here, we're only editing the String nextPlayer by creating a new Random object
Random random = new Random();
String nextPlayer = random.nextInt(10) < 5 ? "b" : "a";
Python
import random
def Game():
A = [[0, 0, 0] for Piece in range(NUMBER_OF_PIECES + 1)]
B = [[0, 0, 0] for Piece in range(NUMBER_OF_PIECES + 1)]
Board = [['' for Column in range(BOARD_SIZE)] for Row in range(BOARD_SIZE)]
ListOfMoves = [MoveRecord() for Move in range(MAX_MOVES)]
GameEnd = False
FileFound = False
Players = [‘a’,’b’]
NextPlayer = random.choice(Players)
Board, A, B, FileFound = SetUpBoard(Board, A, B, FileFound)
if not FileFound:
GameEnd = True
while not GameEnd:
PrintPlayerPieces(A, B)
DisplayBoard(Board)
print('Next Player: ', NextPlayer)
ListOfMoves = ClearList(ListOfMoves)
if NextPlayer == 'a':
ListOfMoves = ListPossibleMoves(Board, A, NextPlayer, ListOfMoves)
if not ListEmpty(ListOfMoves):
PieceIndex = SelectMove(ListOfMoves)
Board, A, B = MakeMove(Board, A, B, ListOfMoves, PieceIndex)
NextPlayer = SwapPlayer(NextPlayer)
else:
GameEnd = True
else:
ListOfMoves = ListPossibleMoves(Board, B, NextPlayer, ListOfMoves)
if not ListEmpty(ListOfMoves):
PieceIndex = SelectMove(ListOfMoves)
Board, B, A = MakeMove(Board, B, A, ListOfMoves, PieceIndex)
NextPlayer = SwapPlayer(NextPlayer)
else:
GameEnd = True
if FileFound:
PrintResult(A, B , NextPlayer)
VB.NET
//Edited By Jay PGS
Sub Game()
Dim A(NumberOfPieces, 2) As Integer
Dim B(NumberOfPieces, 2) As Integer
Dim Board(BoardSize - 1, BoardSize - 1) As String
Dim ListOfMoves(MaxMoves - 1) As MoveRecord
Dim NextPlayer As String
Dim FileFound, GameEnd As Boolean
Dim PieceIndex As Integer
GameEnd = False
FileFound = False
Dim rng As New Random
Dim N As Integer
N = rng.Next(0, 2)
If N = 0 Then
NextPlayer = "a"
Else
NextPlayer = "b"
End If
SetUpBoard(Board, A, B, FileFound)
If Not FileFound Then
GameEnd = True
End If
While Not GameEnd
PrintPlayerPieces(A, B)
DisplayBoard(Board)
Console.WriteLine("Next Player: " & NextPlayer)
ClearList(ListOfMoves)
If NextPlayer = "a" Then
ListPossibleMoves(Board, A, NextPlayer, ListOfMoves)
If Not ListEmpty(ListOfMoves) Then
PieceIndex = SelectMove(ListOfMoves)
MakeMove(Board, A, B, ListOfMoves, PieceIndex)
NextPlayer = SwapPlayer(NextPlayer)
Else
GameEnd = True
End If
Else
ListPossibleMoves(Board, B, NextPlayer, ListOfMoves)
If Not ListEmpty(ListOfMoves) Then
PieceIndex = SelectMove(ListOfMoves)
MakeMove(Board, B, A, ListOfMoves, PieceIndex)
NextPlayer = SwapPlayer(NextPlayer)
Else
GameEnd = True
End If
End If
End While
If FileFound Then
PrintResult(A, B, NextPlayer)
End If
Console.ReadLine()
End Sub
用于“game4.txt”
[edit | edit source]当一个玩家在其回合时没有可用的移动时,游戏结束,该玩家输掉了游戏。建议,在这种情况下,如果玩家在棋盘上有“Dame”棋子,则可以将“Dame”棋子移动到与其主端相反的任何空方格。(对于玩家 A 来说是第 7 行,对于玩家 B 来说是第 0 行)
C#
Delphi/Pascal
Java
Python
def TestMove(Piece,Board,NewRow,LeftColumn,RightColumn,JumpRow,JumpLeftColumn,JumpRightColumn,ListOfMoves,NumberOfMoves,PlayersPieces):
if ValidMove(Board, NewRow, LeftColumn):
print(Piece, ' can move to ', NewRow, ' , ', LeftColumn)
NumberOfMoves += 1
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = NewRow
ListOfMoves[NumberOfMoves].NewColumn = LeftColumn
ListOfMoves[NumberOfMoves].CanJump = False
if ValidMove(Board, NewRow, RightColumn):
print(Piece, ' can move to ', NewRow, ' , ', RightColumn)
NumberOfMoves += 1
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = NewRow
ListOfMoves[NumberOfMoves].NewColumn = RightColumn
ListOfMoves[NumberOfMoves].CanJump = False
if ValidJump(Board, PlayersPieces, Piece, JumpRow, JumpLeftColumn):
print(Piece, ' can jump to ', JumpRow, ' , ', JumpLeftColumn)
NumberOfMoves += 1
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = JumpRow
ListOfMoves[NumberOfMoves].NewColumn = JumpLeftColumn
ListOfMoves[NumberOfMoves].CanJump = True
if ValidJump(Board, PlayersPieces, Piece, JumpRow, JumpRightColumn):
print(Piece, ' can jump to ', JumpRow, ' , ', JumpRightColumn)
NumberOfMoves += 1
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = JumpRow
ListOfMoves[NumberOfMoves].NewColumn = JumpRightColumn
ListOfMoves[NumberOfMoves].CanJump = True
return ListOfMoves,NumberOfMoves
def ValidTeleport(PlayersPieces,NextPlayer,ListOfMoves,NumberOfMoves,Board):
if NextPlayer == 'a':
EndRow = 7
else:
EndRow = 0
for i in range(1, NUMBER_OF_PIECES + 1):
if PlayersPieces[i][DAME] == 1:
for j in range(0,8):
if Board[EndRow][j] == SPACE:
NumberOfMoves += 1
Piece = NextPlayer.upper() + str(i)
print(Piece, 'can teleport to ', EndRow, ' , ', j)
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = EndRow
ListOfMoves[NumberOfMoves].NewColumn = j
ListOfMoves[NumberOfMoves].CanJump = False
return ListOfMoves,NumberOfMoves
def ListPossibleMoves(Board, PlayersPieces, NextPlayer, ListOfMoves):
if NextPlayer == 'a':
Direction = 1
else:
Direction = -1
NumberOfMoves = 0
for i in range(1, NUMBER_OF_PIECES + 1):
Piece = NextPlayer + str(i)
CurrentRow = PlayersPieces[i][ROW]
CurrentColumn = PlayersPieces[i][COLUMN]
if PlayersPieces[i][DAME] == 1:
Piece = Piece.upper()
NewRow = CurrentRow + Direction
LeftColumn = CurrentColumn - 1
RightColumn = CurrentColumn + 1
JumpRow = CurrentRow + Direction + Direction
JumpLeftColumn = CurrentColumn - 2
JumpRightColumn = CurrentColumn + 2
ListOfMoves,NumberOfMoves = TestMove(Piece,Board,NewRow,LeftColumn,RightColumn,JumpRow,JumpLeftColumn,JumpRightColumn,ListOfMoves,NumberOfMoves,PlayersPieces)
if ListEmpty(ListOfMoves):
ListOfMoves,NumberOfMoves = ValidTeleport(PlayersPieces,NextPlayer,ListOfMoves,NumberOfMoves,Board)
print('There are ', NumberOfMoves, ' possible moves')
return ListOfMoves
Python 替代方案
def ValidTeleport(Board, PlayersPieces, NextPlayer, ListOfMoves, NumberOfMoves):
if NextPlayer == 'a':
EndRow = 7
else:
EndRow = 0
if ListEmpty(ListOfMoves):
for i in range(1, NUMBER_OF_PIECES + 1):
if PlayersPieces[i][DAME] == 1:
if NextPlayer == 'a':
for j in range(0, 8):
if Board[7][j] == SPACE:
Piece = NextPlayer.upper() + str(i)
NumberOfMoves += 1
print(Piece, 'can teleport to ', EndRow, ' , ', j)
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = EndRow
ListOfMoves[NumberOfMoves].NewColumn = j
ListOfMoves[NumberOfMoves].CanJump = False
else:
for j in range(0, 8):
if Board[0][j] == SPACE:
Piece = NextPlayer.upper() + str(i)
NumberOfMoves += 1
print(Piece, 'can teleport to ', EndRow, ' , ', j)
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = EndRow
ListOfMoves[NumberOfMoves].NewColumn = j
ListOfMoves[NumberOfMoves].CanJump = False
return ListOfMoves, NumberOfMoves
def ListPossibleMoves(Board, PlayersPieces, NextPlayer, ListOfMoves):
if NextPlayer == 'a':
Direction = 1
else:
Direction = -1
global NumberOfMoves
NumberOfMoves = 0
for i in range(1, NUMBER_OF_PIECES + 1):
Piece = NextPlayer + str(i)
CurrentRow = PlayersPieces[i][ROW]
CurrentColumn = PlayersPieces[i][COLUMN]
if PlayersPieces[i][DAME] == 1:
Piece = Piece.upper()
NewRow = CurrentRow + Direction
LeftColumn = CurrentColumn - 1
RightColumn = CurrentColumn + 1
if ValidMove(Board, NewRow, LeftColumn):
print(Piece, ' can move to ', NewRow, ' , ', LeftColumn)
NumberOfMoves += 1
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = NewRow
ListOfMoves[NumberOfMoves].NewColumn = LeftColumn
ListOfMoves[NumberOfMoves].CanJump = False
if ValidMove(Board, NewRow, RightColumn):
print(Piece, ' can move to ', NewRow, ' , ', RightColumn)
NumberOfMoves += 1
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = NewRow
ListOfMoves[NumberOfMoves].NewColumn = RightColumn
ListOfMoves[NumberOfMoves].CanJump = False
JumpRow = CurrentRow + Direction + Direction
JumpLeftColumn = CurrentColumn - 2
JumpRightColumn = CurrentColumn + 2
if ValidJump(Board, PlayersPieces, Piece, JumpRow, JumpLeftColumn):
print(Piece, ' can jump to ', JumpRow, ' , ', JumpLeftColumn)
NumberOfMoves += 1
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = JumpRow
ListOfMoves[NumberOfMoves].NewColumn = JumpLeftColumn
ListOfMoves[NumberOfMoves].CanJump = True
if ValidJump(Board, PlayersPieces, Piece, JumpRow, JumpRightColumn):
print(Piece, ' can jump to ', JumpRow, ' , ', JumpRightColumn)
NumberOfMoves += 1
ListOfMoves[NumberOfMoves].Piece = Piece
ListOfMoves[NumberOfMoves].NewRow = JumpRow
ListOfMoves[NumberOfMoves].NewColumn = JumpRightColumn
ListOfMoves[NumberOfMoves].CanJump = True
## The line below is the only modification that needs to be added for this question.
ListOfMoves, NumberOfMoves = ValidTeleport(Board, PlayersPieces, NextPlayer, ListOfMoves, NumberOfMoves)
print('There are ', NumberOfMoves, ' possible moves')
return ListOfMoves
VB.NET