Jump to content

A-level Computing/AQA/Paper 1/Skeleton program/AS2019

From Wikibooks, open books for an open world

This is for the AQA AS Level Computer Science Specification.

This is where suggestions can be made about what some of the questions might be and how we can solve them.

Please be respectful and do not vandalise or tamper with the page, as this would affect students' preparation for exams!
Please do not discuss questions on this page. Instead use the discussion page:Talk:A-level Computing/AQA/Paper 1/Skeleton program/AS2019

Make Player skip turn

[edit | edit source]

Allow player 'a' and 'b' to be able to skip their turn

C#:

created by accident, like 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:


Input file ends with ".txt"

[edit | edit source]

The user has to enter a file which ends with ".txt", else it will add it for them.

C#:

Coded by Sol, of Brockenhurst College.

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";
                }
            }

Coded by accident

// 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:

Coded by Nevans the knowledgeable of Kennet School

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


Display number of moves taken.

[edit | edit source]

Displays the number of moves taken after each turn.

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);
       }
   }
Coded by James Trenaman of Kennet School


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 Alternative Solution:

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


Displays error value meanings

[edit | edit source]

Error values 1-4 don't have any notation as to what each error means. Add a description for each one when displayed.

C#:

Coded by Sol, of Brockenhurst College.

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


Allow taking of other players pieces as in draughts

[edit | edit source]

The original game of Checkers (or Draughts, as I'd prefer to call it) is a game where you are able to 'jump over' your opponent's pieces to take them off the board. In the skeleton, you aren't able to do as such. To add this gameplay mechanic, you'd want to edit the ValidJump and MakeMove methods, but it may be difficult as it requires understanding of the data structures used.

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


Save the game

[edit | edit source]

Add a new function/method called from Game(). All elements in the arrays can be saved, there is no requirement to miss the first element off of each array. Look at SetupBoard() and LoadPieces() for better understanding.

C#:

Created by accident

// 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


Allow saves to specify the next player

[edit | edit source]

Currently, all saved games will give the next turn to A, even if A was the last player to have a turn. This is unfair to the person playing as B. You will need to modify both your implementation of savegames and the game's own load game and main subroutines to achieve this.

C#:


Delphi/Pascal:


Java:


Python:


VB.NET:


Don't allow move to create dame under certain conditions

[edit | edit source]

If there is no room for the dame to be created, don't allow the move to be made. You may want to edit ListPossibleMoves() to do this.

C#:

Coded by Sol, of Brockenhurst College.

		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:


Allow the dame to have better movement

[edit | edit source]

The dame seems a bit bland. Why not allow the dame to move 2 spaces vertically as well? Or 2 spaces diagonally? I would recommend doing it all in ListPossibleMoves(), by setting up a bool to be set to True if the current piece is a dame, and add a new selection statement after the existing move checks that adds to the list the new movement. It is quite easy to test using game3.txt. Perhaps allow it to move like a Queen from chess? Or at least be able to move backwards.

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:


Player B is controlled by the computer

[edit | edit source]

Have an AI control B instead of having another player do it. It isn't too difficult to set up. I would recommend replacing the function call to SelectMove() in Game() with a new function to generate a valid number for pieceIndex. The way the AI works can be up to you, whether it is just random or actually has a strategy to it.

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


Allow the user to create a custom game file

[edit | edit source]

Give the user the option to add a custom game file (as in, create another default file to pick from (e.g game5.txt)), and allow the user to dictate the starting positions of the pieces, as well as the number of pieces and the type of pieces.

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:


Double jump as in Draughts

[edit | edit source]

The original game of Draughts allows 'double jumps', where if you make a jump and are able to make a second after aforementioned jump, you are able to if you so choose. You can use game3.txt to help using the a6 piece.

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:


Try next row to add dame

[edit | edit source]

Similar to a previous question: if there is no space to create a dame on the home row, try the next row on, and continue to do so until it can place a 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:


Random player starts

[edit | edit source]

Random player starts

C#:

created by accident

// 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


Use for 'game4.txt'

[edit | edit source]

When a player has no possible moves available when it is their turn, the game ends and that player has lost the game. Rather than losing the game under these circumstances, it has been suggested that if the player has a Dame piece on the board, the Dame can be moved to any empty square at the opposite end to their home end. (Row 7 for Player A, Row 0 for Player B)

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 Alternative solution:

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: