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

From Wikibooks, open books for an open world
< A-level Computing‎ | AQA‎ | Paper 1‎ | Skeleton program
Jump to navigation Jump to search

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]

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]

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

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

Delphi/Pascal:

Java:

Python:

def SetUpBoard(Board, A, B, FileFound):
  FileFound = False
  FileName = 'game1.txt'
  Answer = input('Do you want to load a saved game? (Y/N): ')
  if Answer == 'Y' or Answer == 'y':
    while FileFound == False:
      FileName = input('Enter the filename: ')
      if '.txt' not in FileName:
        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)
  elif Answer == 'N' or Answer == 'n':
    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

VB.NET:

  FileName = "game1.txt"
  FileFound = False
  Console.WriteLine("Do you want to load a saved game? (Y/N): ")
  Answer = Console.ReadLine()
  If Answer = "Y" or Answer = "y" Then
    While FileFound = False
      Console.WriteLine("Enter the filename: ")
      FileName = Console.ReadLine()
      If Right(FileName, 4) <> ".txt" Then
        FileName = (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)
    End While
  End If

Display number of moves taken.[edit]

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:

Python:

def Game():
  MovesTaken = 0
  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))
    MovesTaken += 1
    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]))
      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]))
      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]

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
  If ErrorNumber = "1" Then ErrorMessage = "Error: Selected piece is unable to move."
  If ErrorNumber = "2" Then ErrorMessage = "Error: Selected piece is unable to move to selected placement."
  If ErrorNumber = "3" Then ErrorMessage = "Error: Exception error."
  If ErrorNumber = "4" Then ErrorMessage = "Error: Invalid game file selected."
  Console.WriteLine(ErrorMessage)
End Sub

Allow taking of other players pieces as in draughts[edit]

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:

Save the game[edit]

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 SLAHSES}" + 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();
        }
    }

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]

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]

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 availibility 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]

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:

VB.NET:

Player B is controlled by the computer[edit]

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:

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]

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 CreateAllPieces(Board,PiecesPerPlayer):
  print("Player A:")
  A = [[-1,-1,0]]
  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':
          if 0 <= PieceRow < BOARD_SIZE and 0 <= PieceColumn < BOARD_SIZE:
            if PieceDame == 'Y':
              PieceDame = 1
            else:
              PieceDame = 0
            if [PieceRow,PieceColumn,0] not in A and [PieceRow,PieceColumn,1] not in A:
              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))
        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))
    A.append([PieceRow,PieceColumn,PieceDame])
  for i in range(PiecesPerPlayer,NUMBER_OF_PIECES-PiecesPerPlayer+2):
    A.append([-1,-1,0])
  print("Player B:")
  B = [[-1,-1,0]]
  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':
          if 0 <= PieceRow < BOARD_SIZE and 0 <= PieceColumn < BOARD_SIZE:
            if PieceDame == 'Y':
              PieceDame = 1
            else:
              PieceDame = 0
            if [PieceRow,PieceColumn,0] not in A and [PieceRow,PieceColumn,1] not in A and [PieceRow,PieceColumn,0] not in B and [PieceRow,PieceColumn,1] not in B:
              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))
        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))
    B.append([PieceRow,PieceColumn,PieceDame])
  for i in range(PiecesPerPlayer,NUMBER_OF_PIECES+2-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]

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:

Python:

VB.NET:

Try next row to add dame[edit]

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]

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:

Stalemate Detection - Not possible?[edit]

There is currently a possibility for a stalemate (i.e. where neither player is able to win) to occur. One potential addition is to implement stalemate detection, so if neither player is able to win, the game ends. The outcome (both win, both lose or simply a tie) is up to the programmer.

Note from original submitter:

The original scenario imagined for a stalemate was the following:

0 1 2 3 4 5 6 7
0 X A X X X
1 X X X X
2 X a X a X a X a
3 a X a X a X a X
4 X b X b X b X b
5 b X b X b X b X
6 X X X X
7 X X X B X

Assuming dames can move forwards and backwards as per normal chequers (as would be implemented by edit 8 here: [8]), and as no piece can jump over another, neither player is able to lose. As a result, a stalemate has resulted.

However, I realise that this would be far too complicated, and unrealistic for an AS level solution.


C#:

Delphi/Pascal:

Java:

Python:

VB.NET: