A-level Computing/AQA/Problem Solving, Programming, Data Representation and Practical Exercise/Skeleton code/2015 Exam/Section D
I just wanted to say good luck to all on results day after that nightmare of a paper! And good luck to any future years who attempt this in class, you'll need it!
It isn't an extremely bad paper, the FEN question (if someone wants to make a solution) just needed you to do something similar to the display board function, and then express blanks as numbers (I admit, I didn't have time to do that!)
Give user option to selectively place pieces onto board.
[edit | edit source]Currently when the sample game is set up, all of the pieces are positioned in certain places. Edit the program to give the user an option to create their own sample game.
Python Solution
Answer:
def InitialiseBoard(Board, SampleGame):
Piece = False #Sets variable piece to false.
if SampleGame == "Y":
for RankNo in range(1, BOARDDIMENSION + 1):
for FileNo in range(1, BOARDDIMENSION + 1):
Board[RankNo][FileNo] = " "
while Piece == False:
NewPiece = input("Would you like to add a piece? Y/N: ") #Asks user if they would like to add a piece to the board.
if NewPiece == "Y":
NewPieceFile = int(input("Enter the file of the new piece 1-8: ")) #Stores a value for the new pieces file.
NewPieceRank = int(input("Enter the rank of the new piece 1-8: ")) #Stores a value for the new pieces rank.
NewPieceType = "" #Stores pieces type as nothing.
while NewPieceType != "WS" and NewPieceType != "WR" and NewPieceType != "WM" and NewPieceType != "WG" and NewPieceType != "WN" and NewPieceType != "WE" and NewPieceType != "BS" and NewPieceType != "BR" and NewPieceType != "BM" and NewPieceType != "BG" and NewPieceType != "BN" and NewPieceType != "BE":
NewPieceType = input("Enter the type of the new piece: For example 'WM': ") #Stores pieces type as users input.
Piece = False #Piece is set to false to allow for more pieces to be added to the board.
Board[NewPieceRank][NewPieceFile] = NewPieceType
else:
Piece = True #Piece set to true preventing more pieces being added to the board, board displayed.
VB.NET solution
Answer:
Sub InitialiseBoard(ByRef Board(,) As String, ByVal SampleGame As Char)
Dim RankNo As Integer
Dim FileNo As Integer
Dim answer As String
If SampleGame = "Y" Then
For RankNo = 1 To BoardDimension
For FileNo = 1 To BoardDimension
Board(RankNo, FileNo) = " "
Next
Next
Do Until answer = "X"
Console.WriteLine("Enter p to place a new piece/x to exit or r to remove a piece")
answer = UCase(Console.ReadLine())
If answer = "P" Then
DisplayBoard(Board)
Console.WriteLine("Choose file: ")
FileNo = Console.ReadLine()
Console.WriteLine("Choose rank: ")
RankNo = Console.ReadLine()
Console.WriteLine("What type of piece: ")
answer = UCase(Console.ReadLine())
Board(RankNo, FileNo) = answer
DisplayBoard(Board)
ElseIf answer = "R" Then
DisplayBoard(Board)
Console.WriteLine("Choose file: ")
FileNo = Console.ReadLine()
Console.WriteLine("Choose rank: ")
RankNo = Console.ReadLine()
Board(RankNo, FileNo) = " "
DisplayBoard(Board)
Else
End If
Loop
Give an option to exit game
[edit | edit source]When asking for the coordinates for the startPosition, give an option for the user to exit game.
VB.Net Solution
Answer:
'Jonathan Middlemass, Beckfoot School
'Highlighted by Edd Norton, Ashville College
Sub GetMove(ByRef StartSquare As Integer, ByRef FinishSquare As Integer)
Dim TypeOfGame As Char
Console.WriteLine("press Q to quit game")
TypeOfGame = Console.ReadLine
If Asc(TypeOfGame) >= 97 And Asc(TypeOfGame) <= 122 Then
TypeOfGame = Chr(Asc(TypeOfGame) - 32)
End If
If TypeOfGame = "Q" Then
End
End If
Console.Write("Enter coordinates of square containing piece to move (file first): ")
StartSquare = Console.ReadLine
Console.Write("Enter coordinates of square to move piece to (file first): ")
FinishSquare = Console.ReadLine
End Sub
Java Solution
Answer:
void getMove(Position startPosition, Position finishPosition) {
String ExitGame = console.readLine("Enter cooordinates of square containing piece to move (file first) OR press X to exit: "); if (ExitGame.equalsIgnoreCase("x")) { System.exit(0); } else { try { Integer.parseInt (ExitGame); startPosition.coordinates = Integer.parseInt (ExitGame);; finishPosition.coordinates = console.readInteger("Enter cooordinates of square to move piece to (file first): "); //coordinate entered here will be for the position of the board intended to be moved to } catch (Exception e) { console.writeLine(e.getMessage()); } } }
Pascal Solution
Answer:
Procedure GetMove(Var StartSquare, FinishSquare : Integer);
Begin
// change made was 00 is now to quit Write('Enter coordinates of square containing piece to move (file first or 00 will quit): '); Readln(StartSquare); if (StartSquare = 00) then halt; Write('Enter coordinates of square to move piece to (file first): '); Readln(FinishSquare);
End;
Python Solution
Answer:
def GetTypeOfGame():### CHANGE
TypeOfGame = input(" Y: Sample Game N: New Game Q: Exit Game ")
if TypeOfGame=='Q':
quit()
return TypeOfGame
def GetMove(StartSquare, FinishSquare):###Quit before move played
Q=input("Enter Q to exit game: ")
if Q=='Q':
quit()
else:
StartSquare = int(input("Enter coordinates of square containing piece to move (file first): "))
FinishSquare = int(input("Enter coordinates of square to move piece to (file first): "))
return StartSquare, FinishSquare
if __name__ == "__main__":
Board = CreateBoard() #0th index not used
StartSquare = 0
FinishSquare = 0
PlayAgain = "Y"
while PlayAgain == "Y":
WhoseTurn = "W"
GameOver = False
SampleGame = GetTypeOfGame() ###NEEDS to be function
if ord(SampleGame) >= 97 and ord(SampleGame) <= 122:
SampleGame = chr(ord(SampleGame) - 32)
InitialiseBoard(Board, SampleGame)
#Python 3
Skill trees and levelling up
[edit | edit source]Add skill trees to the game so that pieces can learn new abilities and skills upon capturing enemy pieces. For students seeking a challenge at some advanced programming.
VB.Net solution
Answer:
'By Charlie Letts - 12/Co1 Riddlesdown Collegiate
Dim Points(1, 5) As Integer '2D array to store piece points: Points(Colour, Piece)
Dim Skill(1, 5, 2) '3D array to store piece skill points: Skill(Colour, Piece, SkillCategory)
Dim CurrentPieceVal As Integer = 0 'Stores an integer relating to the piece
Dim SkillChoice As String = "0" 'Stores a string which later is converted into an integer of what skill category is chosen
Sub Main()
Dim Board(BoardDimension, BoardDimension) As String
Dim GameOver As Boolean
Dim StartSquare As Integer
Dim FinishSquare As String = ""
Dim StartRank As Integer
Dim StartFile As Integer
Dim FinishRank As Integer
Dim FinishFile As Integer
Dim MoveIsLegal As Boolean
Dim PlayAgain As Char
Dim SampleGame As Char
Dim WhoseTurn As Char
Dim isTP As Boolean
For x As Integer = 0 To 1
For y As Integer = 0 To 5
For z As Integer = 0 To 2
Skill(x, y, z) = 0
Next
Next
Next
For Each element In Points 'Loops through each element in the point array and sets it to 0
element = 0
Next
PlayAgain = "Y"
Do
WhoseTurn = "W"
GameOver = False
Console.Write("Sample Game/New Game/Custom Game/Quit (Y/N/C/Q)? ")
SampleGame = Console.ReadLine
If Asc(SampleGame) >= 97 And Asc(SampleGame) <= 122 Then
SampleGame = Chr(Asc(SampleGame) - 32)
End If
InitialiseBoard(Board, SampleGame)
Do
DisplayBoard(Board)
DisplayWhoseTurnItIs(WhoseTurn)
MoveIsLegal = False
Do
isTP = GetMove(StartSquare, FinishSquare, Board, WhoseTurn) 'Grabs the returnes boolean to check if isTP = true
If isTP = True Then
MoveIsLegal = True
Else
StartRank = StartSquare Mod 10
StartFile = StartSquare \ 10
FinishRank = FinishSquare Mod 10
FinishFile = FinishSquare \ 10
MoveIsLegal = CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
If Not MoveIsLegal Then
Console.WriteLine("That is not a legal move - please try again")
End If
End If
Loop Until MoveIsLegal
If isTP = False Then
GameOver = CheckIfGameWillBeWon(Board, FinishRank, FinishFile)
MakeMove(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
If GameOver Then
DisplayWinner(WhoseTurn)
End If
End If
If WhoseTurn = "W" Then
WhoseTurn = "B"
Else
WhoseTurn = "W"
End If
Loop Until GameOver
Console.Write("Do you want to play again (enter Y for Yes)? ")
PlayAgain = Console.ReadLine
If Asc(PlayAgain) >= 97 And Asc(PlayAgain) <= 122 Then
PlayAgain = Chr(Asc(PlayAgain) - 32)
End If
Loop Until PlayAgain <> "Y"
End Sub
Function CheckRedumMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer, ByVal ColourOfPiece As Char, ByVal WhoseTurn As Char) As Boolean
Dim ForwardMoveDist As Integer = 1
Dim BackwardMoveDist As Integer = 0
If ColourOfPiece = "W" Then
ForwardMoveDist = ForwardMoveDist + Skill(0, CurrentPieceVal, 0)
BackwardMoveDist = BackwardMoveDist + Skill(0, CurrentPieceVal, 1)
If (FinishRank >= (StartRank - ForwardMoveDist)) And (FinishRank <= (StartRank + BackwardMoveDist)) Then
If FinishFile = StartFile And Board(FinishRank, FinishFile) = " " Then
Return True
ElseIf Abs(FinishFile - StartFile) = 1 And Board(FinishRank, FinishFile)(0) = "B" Then
Return True
End If
End If
Else
ForwardMoveDist = ForwardMoveDist + Skill(1, CurrentPieceVal, 0)
BackwardMoveDist = BackwardMoveDist + Skill(1, CurrentPieceVal, 1)
If FinishRank <= StartRank + ForwardMoveDist And FinishRank >= StartRank - BackwardMoveDist Then
If FinishFile = StartFile And Board(FinishRank, FinishFile) = " " Then
Return True
ElseIf Abs(FinishFile - StartFile) = 1 And Board(FinishRank, FinishFile)(0) = "W" Then
Return True
End If
End If
End If
Return False
End Function
Function CheckSarrumMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer, ByVal WhoseTurn As Char) As Boolean
Dim ForwardMoveDist As Integer = 1
Dim BackwardMoveDist As Integer = 1
If WhoseTurn = "W" Then
ForwardMoveDist = ForwardMoveDist + Skill(0, CurrentPieceVal, 0)
BackwardMoveDist = BackwardMoveDist + Skill(0, CurrentPieceVal, 1)
If Abs(FinishFile - StartFile) <= 1 And Abs(FinishRank - StartRank) <= 1 Then
Return True
ElseIf FinishRank >= StartRank - ForwardMoveDist And FinishRank <= StartRank + BackwardMoveDist And FinishFile = StartFile Then
Return True
End If
Else
ForwardMoveDist = ForwardMoveDist + Skill(1, CurrentPieceVal, 0)
BackwardMoveDist = BackwardMoveDist + Skill(1, CurrentPieceVal, 1)
If Abs(FinishFile - StartFile) <= 1 And Abs(FinishRank - StartRank) <= 1 Then
Return True
ElseIf FinishRank <= StartRank + ForwardMoveDist And FinishRank >= StartRank - BackwardMoveDist And FinishFile = StartFile Then
Return True
End If
End If
Return False
End Function
Function CheckGisgigirMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer, ByVal WhoseTurn As Char) As Boolean
Dim GisgigirMoveIsLegal As Boolean
Dim Count As Integer
Dim RankDifference As Integer
Dim FileDifference As Integer
Dim ForwardMoveDist As Integer = 1
Dim BackwardMoveDist As Integer = 1
GisgigirMoveIsLegal = False
RankDifference = FinishRank - StartRank
FileDifference = FinishFile - StartFile
If RankDifference = 0 Then
If FileDifference >= 1 Then
GisgigirMoveIsLegal = True
For Count = 1 To FileDifference - 1
If Board(StartRank, StartFile + Count) <> " " Then
GisgigirMoveIsLegal = False
End If
Next
ElseIf FileDifference <= -1 Then
GisgigirMoveIsLegal = True
For Count = -1 To FileDifference + 1 Step -1
If Board(StartRank, StartFile + Count) <> " " Then
GisgigirMoveIsLegal = False
End If
Next
End If
ElseIf FileDifference = 0 Then
If WhoseTurn = "W" Then
ForwardMoveDist = ForwardMoveDist + Skill(0, CurrentPieceVal, 0)
BackwardMoveDist = BackwardMoveDist + Skill(0, CurrentPieceVal, 1)
If RankDifference <= BackwardMoveDist And RankDifference > 0 Then
GisgigirMoveIsLegal = True
For Count = 1 To RankDifference - 1
If Board(StartRank + Count, StartFile) <> " " Then
GisgigirMoveIsLegal = False
End If
Next
ElseIf RankDifference >= 0 - ForwardMoveDist And RankDifference < 0 Then
GisgigirMoveIsLegal = True
For Count = -1 To RankDifference + 1 Step -1
If Board(StartRank + Count, StartFile) <> " " Then
GisgigirMoveIsLegal = False
End If
Next
End If
Else
ForwardMoveDist = ForwardMoveDist + Skill(1, CurrentPieceVal, 0)
BackwardMoveDist = BackwardMoveDist + Skill(1, CurrentPieceVal, 1)
If RankDifference <= ForwardMoveDist And RankDifference > 0 Then
GisgigirMoveIsLegal = True
For Count = 1 To RankDifference - 1
If Board(StartRank + Count, StartFile) <> " " Then
GisgigirMoveIsLegal = False
End If
Next
ElseIf RankDifference >= 0 - BackwardMoveDist And RankDifference < 0 Then
GisgigirMoveIsLegal = True
For Count = -1 To RankDifference + 1 Step -1
If Board(StartRank + Count, StartFile) <> " " Then
GisgigirMoveIsLegal = False
End If
Next
End If
End If
End If
Return GisgigirMoveIsLegal
End Function
Function CheckNabuMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer, ByVal WhoseTurn As Char) As Boolean
Dim ForwardMoveDist As Integer = 0
Dim BackwardMoveDist As Integer = 0
If WhoseTurn = "W" Then
ForwardMoveDist = ForwardMoveDist + Skill(0, CurrentPieceVal, 0)
BackwardMoveDist = BackwardMoveDist + Skill(0, CurrentPieceVal, 1)
If Abs(FinishFile - StartFile) = 1 And Abs(FinishRank - StartRank) = 1 Then
Return True
ElseIf FinishFile - StartFile = 0 And StartRank - FinishRank <= ForwardMoveDist And StartRank - FinishRank > 0 Then
Return True
ElseIf FinishFile - StartFile = 0 And FinishRank - StartRank <= BackwardMoveDist And FinishRank - StartRank > 0 Then
Return True
Else
Return False
End If
Else
ForwardMoveDist = ForwardMoveDist + Skill(1, CurrentPieceVal, 0)
BackwardMoveDist = BackwardMoveDist + Skill(1, CurrentPieceVal, 1)
If Abs(FinishFile - StartFile) = 1 And Abs(FinishRank - StartRank) = 1 Then
Return True
ElseIf FinishFile - StartFile = 0 And FinishRank - StartRank <= ForwardMoveDist And FinishRank - StartRank > 0 Then
Return True
ElseIf FinishFile - StartFile = 0 And StartRank - FinishRank <= BackwardMoveDist And StartRank - FinishRank > 0 Then
Return True
End If
End If
Return False
End Function
Function CheckMarzazPaniMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer, ByVal WhoseTurn As Char) As Boolean
Dim ForwardMoveDist As Integer = 1
Dim BackwardMoveDist As Integer = 1
If WhoseTurn = "W" Then
ForwardMoveDist = ForwardMoveDist + Skill(0, CurrentPieceVal, 0)
BackwardMoveDist = BackwardMoveDist + Skill(0, CurrentPieceVal, 1)
If (Abs(FinishFile - StartFile) = 1 And FinishRank - StartRank = 0) Or (FinishFile - StartFile = 0 And Abs(FinishRank - StartRank) <= ForwardMoveDist And StartRank - FinishRank > 0) Then
Return True
ElseIf (Abs(FinishFile - StartFile) = 1 And FinishRank - StartRank = 0) Or (FinishFile - StartFile = 0 And Abs(FinishRank - StartRank) <= BackwardMoveDist And FinishRank - StartRank > 0) Then
Return True
End If
Else
ForwardMoveDist = ForwardMoveDist + Skill(1, CurrentPieceVal, 0)
BackwardMoveDist = BackwardMoveDist + Skill(1, CurrentPieceVal, 1)
If (Abs(FinishFile - StartFile) = 1 And FinishRank - StartRank = 0) Or (FinishFile - StartFile = 0 And Abs(FinishRank - StartRank) <= ForwardMoveDist And FinishRank - StartRank > 0) Then
Return True
ElseIf (Abs(FinishFile - StartFile) = 1 And FinishRank - StartRank = 0) Or (FinishFile - StartFile = 0 And Abs(FinishRank - StartRank) <= BackwardMoveDist And StartRank - FinishRank > 0) Then
Return True
End If
End If
Return False
End Function
Function CheckEtluMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer, ByVal WhoseTurn As Char) As Boolean
Dim ForwardMoveDist As Integer = 2
Dim BackwardMoveDist As Integer = 2
If WhoseTurn = "W" Then
ForwardMoveDist = ForwardMoveDist + Skill(0, CurrentPieceVal, 0)
BackwardMoveDist = BackwardMoveDist + Skill(0, CurrentPieceVal, 1)
If Abs(FinishFile - StartFile) = 2 And Abs(FinishRank - StartRank) = 0 Or Abs(FinishFile - StartFile) = 0 And Abs(FinishRank - StartRank) = ForwardMoveDist And FinishRank - StartRank < 0 Then
Return True
ElseIf Abs(FinishFile - StartFile) = 2 And Abs(FinishRank - StartRank) = 0 Or Abs(FinishFile - StartFile) = 0 And Abs(FinishRank - StartRank) = BackwardMoveDist And FinishRank - StartRank > 0 Then
Return True
End If
Else
ForwardMoveDist = ForwardMoveDist + Skill(1, CurrentPieceVal, 0)
BackwardMoveDist = BackwardMoveDist + Skill(1, CurrentPieceVal, 1)
If Abs(FinishFile - StartFile) = 2 And Abs(FinishRank - StartRank) = 0 Or Abs(FinishFile - StartFile) = 0 And Abs(FinishRank - StartRank) = BackwardMoveDist And FinishRank - StartRank < 0 Then
Return True
ElseIf Abs(FinishFile - StartFile) = 2 And Abs(FinishRank - StartRank) = 0 Or Abs(FinishFile - StartFile) = 0 And Abs(FinishRank - StartRank) = ForwardMoveDist And FinishRank - StartRank > 0 Then
Return True
End If
End If
Return False
End Function
Function GetMove(ByRef StartSquare As String, ByRef FinishSquare As String, ByVal Board(,) As String, ByVal WhoseTurn As Char)
Do
Console.Write("Enter coordinates of square containing piece to move (file first) or enter Q to quit: ")
StartSquare = Console.ReadLine
Loop Until Board(Microsoft.VisualBasic.Right(StartSquare, 1), Microsoft.VisualBasic.Left(StartSquare, 1)) <> " "
If StartSquare.ToUpper = "Q" Then
Environment.Exit(0)
End If
StartSquare = Convert.ToInt32(StartSquare)
Do
Console.Write("Enter coordinates of square to move piece to (file first) or enter Q to quit: ")
FinishSquare = Console.ReadLine
If AscW(Microsoft.VisualBasic.Left(FinishSquare, 1)) >= 48 And AscW(Microsoft.VisualBasic.Left(FinishSquare, 1)) <= 57 Then
FinishSquare = Convert.ToInt32(FinishSquare)
End If
If WhoseTurn = "W" Then
If FinishSquare.ToUpper = "TP" And Skill(0, CurrentPieceVal, 2) >= 1 Then
CheckSarrumtp(WhoseTurn, Board, StartSquare) 'Calls the CheckSarrumtp sub
Return True
End If
Else
If FinishSquare.ToUpper = "TP" And Skill(1, CurrentPieceVal, 2) >= 1 Then
CheckSarrumtp(WhoseTurn, Board, StartSquare) 'Calls the CheckSarrumtp sub
Return True
End If
End If
If FinishSquare.ToUpper = "Q" Then
Environment.Exit(0)
End If
Loop Until AscW(Microsoft.VisualBasic.Left(FinishSquare, 1)) >= 48 And AscW(Microsoft.VisualBasic.Left(FinishSquare, 1)) <= 57
Return False
End Function
Sub PointsAdd(ByRef Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal WhoseTurn As Char)
Dim CurrentPiece As String = ""
Dim PiecePoints As Integer
Dim ShopChoice As String = ""
CurrentPiece = Board(StartRank, StartFile)
Select Case Board(StartRank, StartFile) ' Setting the variables depending on the piece
Case "WR"
Points(0, 0) += 5
PiecePoints = Points(0, 0)
CurrentPieceVal = 0
Case "WG"
Points(0, 1) += 5
PiecePoints = Points(0, 1)
CurrentPieceVal = 1
Case "WE"
Points(0, 2) += 5
PiecePoints = Points(0, 2)
CurrentPieceVal = 2
Case "WN"
Points(0, 3) += 5
PiecePoints = Points(0, 3)
CurrentPieceVal = 3
Case "WM"
Points(0, 4) += 5
PiecePoints = Points(0, 4)
CurrentPieceVal = 4
Case "WS"
Points(0, 5) += 5
PiecePoints = Points(0, 5)
CurrentPieceVal = 5
Case "BR"
Points(1, 0) += 5
PiecePoints = Points(1, 0)
CurrentPieceVal = 0
Case "BG"
Points(1, 1) += 5
PiecePoints = Points(1, 1)
CurrentPieceVal = 1
Case "BE"
Points(1, 2) += 5
PiecePoints = Points(1, 2)
CurrentPieceVal = 2
Case "BN"
Points(1, 3) += 5
PiecePoints = Points(1, 3)
CurrentPieceVal = 3
Case "BM"
Points(1, 4) += 5
PiecePoints = Points(1, 4)
CurrentPieceVal = 4
Case "BS"
Points(1, 5) += 5
PiecePoints = Points(1, 5)
CurrentPieceVal = 5
End Select
While (ShopChoice.ToUpper <> "Y" And ShopChoice.ToUpper <> "N")
Console.ForegroundColor = ConsoleColor.Cyan
Console.WriteLine("You have just earnt 5 points for your " & CurrentPiece & "! You're total points for " & CurrentPiece & " are now " & PiecePoints & ".")
Console.Write("Would you like to purchase a skill? (Y/N): ")
ShopChoice = Console.ReadLine()
End While
Console.ForegroundColor = ConsoleColor.White
If ShopChoice.ToUpper = "Y" Then
Shop(PiecePoints, WhoseTurn, CurrentPieceVal) 'If choice is 'Y' then open shop
End If
End Sub
Sub Shop(ByRef PiecePoints As Integer, ByVal WhoseTurn As Char, ByVal CurrentPieceVal As Integer)
Dim Purchase As Boolean = False
SkillChoice = "0"
While SkillChoice <> "1" And SkillChoice <> "2" And SkillChoice <> "3" And SkillChoice.ToUpper <> "Q"
Console.ForegroundColor = ConsoleColor.Yellow
Console.WriteLine()
Console.WriteLine("////////////////////////////////////////////////////////////////////////////////")
Console.WriteLine("Welcome to the skill shop, enter either 1, 2, 3 to purchase the corresponding skill. Or enter Q to leave the shop.")
Console.WriteLine()
Console.WriteLine("1. Forward Distance +1 (5 points)")
Console.WriteLine("2. Backward Distance +1 (5 points)")
Console.WriteLine("3. Teleport to Sarrum (20 points)")
Console.WriteLine()
Console.WriteLine("////////////////////////////////////////////////////////////////////////////////")
SkillChoice = Console.ReadLine()
End While
Console.ForegroundColor = ConsoleColor.White
If SkillChoice.ToUpper = "Q" Then
Environment.Exit(0)
Else
SkillChoice = Convert.ToInt32(SkillChoice) - 1 'Subtracts 1 because array index's start at 0
End If
If WhoseTurn = "W" Then
Select Case CurrentPieceVal
Case 0
If SkillChoice = 0 Or SkillChoice = 1 And Points(0, 0) >= 5 Then
Points(0, 0) -= 5 'Removes the points
Skill(0, CurrentPieceVal, SkillChoice) += 1 'Adds the skill to the piece
ElseIf SkillChoice = 2 And Points(0, 0) >= 20 Then
Points(0, 0) -= 20
Skill(0, CurrentPieceVal, SkillChoice) += 1
Else
Console.WriteLine("You do not have the required points to purchase this skill.")
End If
Case 1
If SkillChoice = 0 Or SkillChoice = 1 And Points(0, 1) >= 5 Then
Points(0, 1) -= 5
Skill(0, CurrentPieceVal, SkillChoice) += 1
ElseIf SkillChoice = 2 And Points(0, 1) >= 20 Then
Points(0, 1) -= 20
Skill(0, CurrentPieceVal, SkillChoice) += 1
Else
Console.WriteLine("You do not have the required points to purchase this skill.")
End If
Case 2
If SkillChoice = 0 Or SkillChoice = 1 And Points(0, 2) >= 5 Then
Points(0, 2) -= 5
Skill(0, CurrentPieceVal, SkillChoice) += 1
ElseIf SkillChoice = 2 And Points(0, 2) >= 20 Then
Points(0, 2) -= 20
Skill(0, CurrentPieceVal, SkillChoice) += 1
Else
Console.WriteLine("You do not have the required points to purchase this skill.")
End If
Case 3
If SkillChoice = 0 Or SkillChoice = 1 And Points(0, 3) >= 5 Then
Points(0, 3) -= 5
Skill(0, CurrentPieceVal, SkillChoice) += 1
ElseIf SkillChoice = 2 And Points(0, 3) >= 20 Then
Points(0, 3) -= 20
Skill(0, CurrentPieceVal, SkillChoice) += 1
Else
Console.WriteLine("You do not have the required points to purchase this skill.")
End If
Case 4
If SkillChoice = 0 Or SkillChoice = 1 And Points(0, 4) >= 5 Then
Points(0, 4) -= 5
Skill(0, CurrentPieceVal, SkillChoice) += 1
ElseIf SkillChoice = 2 And Points(0, 4) >= 20 Then
Points(0, 4) -= 20
Skill(0, CurrentPieceVal, SkillChoice) += 1
Else
Console.WriteLine("You do not have the required points to purchase this skill.")
End If
Case 5
If SkillChoice = 0 Or SkillChoice = 1 And Points(0, 5) >= 5 Then
Points(0, 5) -= 5
Skill(0, CurrentPieceVal, SkillChoice) += 1
ElseIf SkillChoice = 2 And Points(0, 5) >= 20 Then
Points(0, 5) -= 20
Skill(0, CurrentPieceVal, SkillChoice) += 1
Else
Console.WriteLine("You do not have the required points to purchase this skill.")
End If
End Select
Else
Select Case CurrentPieceVal
Case 0
If SkillChoice = 0 Or SkillChoice = 1 And Points(1, 0) >= 5 Then
Points(1, 0) -= 5
Skill(1, CurrentPieceVal, SkillChoice) += 1
ElseIf SkillChoice = 2 And Points(1, 0) >= 20 Then
Points(1, 0) -= 20
Skill(1, CurrentPieceVal, SkillChoice) += 1
Else
Console.WriteLine("You do not have the required points to purchase this skill.")
End If
Case 1
If SkillChoice = 0 Or SkillChoice = 1 And Points(1, 1) >= 5 Then
Points(1, 1) -= 5
Skill(1, CurrentPieceVal, SkillChoice) += 1
ElseIf SkillChoice = 2 And Points(1, 1) >= 20 Then
Points(1, 1) -= 20
Skill(1, CurrentPieceVal, SkillChoice) += 1
Else
Console.WriteLine("You do not have the required points to purchase this skill.")
End If
Case 2
If SkillChoice = 0 Or SkillChoice = 1 And Points(1, 2) >= 5 Then
Points(1, 2) -= 5
Skill(1, CurrentPieceVal, SkillChoice) += 1
ElseIf SkillChoice = 2 And Points(1, 2) >= 20 Then
Points(1, 2) -= 20
Skill(1, CurrentPieceVal, SkillChoice) += 1
Else
Console.WriteLine("You do not have the required points to purchase this skill.")
End If
Case 3
If SkillChoice = 0 Or SkillChoice = 1 And Points(1, 3) >= 5 Then
Points(1, 3) -= 5
Skill(1, CurrentPieceVal, SkillChoice) += 1
ElseIf SkillChoice = 2 And Points(1, 3) >= 20 Then
Points(1, 3) -= 20
Skill(1, CurrentPieceVal, SkillChoice) += 1
Else
Console.WriteLine("You do not have the required points to purchase this skill.")
End If
Case 4
If SkillChoice = 0 Or SkillChoice = 1 And Points(1, 4) >= 5 Then
Points(1, 4) -= 5
Skill(1, CurrentPieceVal, SkillChoice) += 1
ElseIf SkillChoice = 2 And Points(1, 4) >= 20 Then
Points(1, 4) -= 20
Skill(1, CurrentPieceVal, SkillChoice) += 1
Else
Console.WriteLine("You do not have the required points to purchase this skill.")
End If
Case 5
If SkillChoice = 0 Or SkillChoice = 1 And Points(1, 5) >= 5 Then
Points(1, 5) -= 5
Skill(1, CurrentPieceVal, SkillChoice) += 1
ElseIf SkillChoice = 2 And Points(1, 5) >= 20 Then
Points(1, 5) -= 20
Skill(1, CurrentPieceVal, SkillChoice) += 1
Else
Console.WriteLine("You do not have the required points to purchase this skill.")
End If
End Select
End If
End Sub
Sub CheckSarrumtp(ByVal WhoseTurn As Char, ByRef Board(,) As String, ByRef StartSquare As String)
Dim SarrumPosX As Integer = 0
Dim SarrumPosY As Integer = 0
Dim CurrentPiece As String = ""
Dim Sarrumtp As Boolean = False
Select Case CurrentPieceVal 'Translates the CurrentPieceVal integer into the piece initials
Case 0
If WhoseTurn = "W" Then
CurrentPiece = "WR"
Else
CurrentPiece = "BR"
End If
Case 1
If WhoseTurn = "W" Then
CurrentPiece = "WG"
Else
CurrentPiece = "BG"
End If
Case 2
If WhoseTurn = "W" Then
CurrentPiece = "WE"
Else
CurrentPiece = "BE"
End If
Case 3
If WhoseTurn = "W" Then
CurrentPiece = "WN"
Else
CurrentPiece = "BN"
End If
Case 4
If WhoseTurn = "W" Then
CurrentPiece = "WM"
Else
CurrentPiece = "BM"
End If
Case 5
If WhoseTurn = "W" Then
CurrentPiece = "WS"
Else
CurrentPiece = "BS"
End If
End Select
For i As Integer = 0 To BoardDimension - 1 'Loops through the board to find the sarrum
For k As Integer = 0 To BoardDimension - 1
If WhoseTurn = "W" Then
If Board(i, k) = "WS" Then
SarrumPosY = i
SarrumPosX = k
Exit For
Exit For
End If
Else
If Board(i, k) = "BS" Then
SarrumPosY = i
SarrumPosX = k
Exit For
Exit For
End If
End If
Next
Next
For i As Integer = (SarrumPosY - 1) To (SarrumPosY + 1) 'Loops through every square around the sarrum to check for an empty space
For k As Integer = (SarrumPosX - 1) To (SarrumPosX + 1)
If Board(i, k) = " " Then
Board(Microsoft.VisualBasic.Right(StartSquare, 1), Microsoft.VisualBasic.Left(StartSquare, 1)) = " " 'Removes the piece in old location
Board(i, k) = CurrentPiece 'Adds piece in new location
Sarrumtp = True
Return
End If
Next
Next
If Sarrumtp = False Then
Console.WriteLine("You cannot teleport to the Sarrum right now.")
End If
End Sub
Python Solution
Answer:
Java Solution
Answer:
Pascal Solution
Answer:
C# Solution
Answer:
VB6.0 Solution
Answer:
Add more options to menu
[edit | edit source]When you start capture the Sarrum you are asked:
"Do you want to play the sample game (enter Y for Yes)? ",
Add an option that would allow you to say No to start a new game and then an option to close the program.
VB.Net solution
Answer:
Sub InitialiseBoard(ByRef Board(,) As String, ByVal SampleGame As Char)
' ...
Board(6, 8) = "BR"
ElseIf SampleGame = "C" Then
End
ElseIf SampleGame = "N" Then
For RankNo = 1 To BoardDimension
' ...
Board(RankNo, FileNo) = " "
End If
Next
Next
ElseIf SampleGame <> "N" Or SampleGame <> "Y" Or SampleGame <> "C" Then
Console.WriteLine("This is not part of the menu")
Main()
End If
End Sub
Dim Count As Integer
Dim RankDifference As Integer
Dim FileDifference As Integer
MoveIsLegal = False
OR
Sub InitialiseBoard(ByRef Board(,) As String, ByVal SampleGame As Char)
Dim RankNo As Integer
Dim FileNo As Integer
Dim ans As String
If SampleGame = "Y" Then
For RankNo = 1 To BoardDimension
For FileNo = 1 To BoardDimension
Board(RankNo, FileNo) = " "
Next
Next
Board(1, 2) = "BG"
Board(1, 4) = "BS"
Board(1, 8) = "WG"
Board(2, 1) = "WR"
Board(3, 1) = "WS"
Board(3, 2) = "BE"
Board(3, 8) = "BE"
Board(6, 8) = "BR"
Else
If SampleGame.ToString.ToLower <> "y" Then
Console.WriteLine("Start New Game(enter Y to start new game)")
ans = Console.ReadLine
If ans.ToLower <> "y" Then
Environment.Exit(0)
Else
For RankNo = 1 To BoardDimension
For FileNo = 1 To BoardDimension
If RankNo = 2 Then
Board(RankNo, FileNo) = "BR"
ElseIf RankNo = 7 Then
Board(RankNo, FileNo) = "WR"
ElseIf RankNo = 1 Or RankNo = 8 Then
If RankNo = 1 Then Board(RankNo, FileNo) = "B"
If RankNo = 8 Then Board(RankNo, FileNo) = "W"
Select Case FileNo
Case 1, 8
Board(RankNo, FileNo) = Board(RankNo, FileNo) & "G"
Case 2, 7
Board(RankNo, FileNo) = Board(RankNo, FileNo) & "E"
Case 3, 6
Board(RankNo, FileNo) = Board(RankNo, FileNo) & "N"
Case 4
Board(RankNo, FileNo) = Board(RankNo, FileNo) & "M"
Case 5
Board(RankNo, FileNo) = Board(RankNo, FileNo) & "S"
End Select
Else
Board(RankNo, FileNo) = " "
End If
Next
Next
End If
End If
End If
End Sub
Python Solution
Answer:
def InitialiseBoard(Board, SampleGame):
if SampleGame == "Y":
for RankNo in range(1, BOARDDIMENSION + 1):
for FileNo in range(1, BOARDDIMENSION + 1):
Board[RankNo][FileNo] = " "
Board[1][2] = "BG"
Board[1][4] = "BS"
Board[1][8] = "WG"
Board[2][1] = "WR"
Board[3][1] = "WS"
Board[3][2] = "BE"
Board[3][8] = "BE"
Board[6][8] = "BR"
else:
ExitProgram = input("(N) to start New Game. Any button to Quit")
if ExitProgram.upper() == 'N':
pass
else:
exit()
if __name__ == "__main__":
if ord(SampleGame) >= 97 and ord(SampleGame) <= 122:
SampleGame = chr(ord(SampleGame) - 32)
while SampleGame != 'Y' and SampleGame != 'N':
SampleGame = input("Do you want to play the sample game (enter Y for Yes or N for No)? ")
if ord(SampleGame) >= 97 and ord(SampleGame) <= 122:
SampleGame = chr(ord(SampleGame) - 32)
InitialiseBoard(Board, SampleGame)
Java Solution
Answer:
char getTypeOfGame() { char sampleGame; console.println("Welcome to 'CAPTURE THE SARRUM!'"); console.println(""); console.println("Choose your option:"); console.println("1. Play the real game (enter N for No)"); console.println("2. Play the sample game (enter Y for Yes)"); console.println("3. Exit CAPTURE THE SARRUM (enter Q for Yes)"); console.println(""); sampleGame = console.readChar(); return sampleGame; }
Pascal Solution
Answer:
Writeln('Do you want to play the sample game?');
Write('Enter Y for Yes, n to quit the program without playing, or enter anything else to play a new game. ');
Readln(SampleGame);
If SampleGame= 'n' then Exit;
// LouisdM
C# Solution
Answer:
public static char GetTypeOfGame()
{
char TypeOfGame;
string a;
char[] options = new char[3] {'S','N','Q'};
do {
Console.WriteLine("What type of game would you like to play?");
Console.WriteLine("=========================================");
Console.WriteLine("S = Sample Game");
Console.WriteLine("N = Normal Game");
Console.WriteLine("Q = Quit");
Console.WriteLine("=========================================");
TypeOfGame = char.Parse(Console.ReadLine());
a = Convert.ToString(TypeOfGame);
a = a.ToUpper();
TypeOfGame = Convert.ToChar(a);
if (options.Contains(TypeOfGame) != true) {
Console.WriteLine("Error, please make a valid choice!");
}
} while (options.Contains(TypeOfGame) != true);
return TypeOfGame;
}
VB6.0 Solution
Answer:
Give user option to randomly place pieces onto board
[edit | edit source]Currently when the board is initialised, all of the pieces are positioned in the same place. Edit the program to give the user an option to randomly place the pieces onto the board.
VB.Net solution
Answer:
Sub Main()
'...
Console.Write("Do you want to play the sample game (enter Y for Yes, or R to randomly place pieces on the board)?") 'adding new option to menu
'...
End sub
Sub InitialiseBoard(ByRef Board(,) As String, ByVal SampleGame As Char)
'...
ElseIf SampleGame = "R" Then
Dim random As New Random
Dim white As Array = {"WG", "WG", "WE", "WE", "WN", "WN", "WM", "WS", "WR", "WR", "WR", "WR", "WR", "WR", "WR", "WR"}
Dim black As Array = {"BG", "BG", "BE", "BE", "BN", "BN", "BM", "BS", "BR", "BR", "BR", "BR", "BR", "BR", "BR", "BR"}
Dim pieceplaced As Boolean
For RankNo = 1 To BoardDimension
For FileNo = 1 To BoardDimension
Board(RankNo, FileNo) = " "
Next
Next
For i = 0 To white.Length - 1
pieceplaced = False
While pieceplaced = False
RankNo = random.Next(1, 8)
FileNo = random.Next(1, 8)
If Board(RankNo, FileNo) = " " Then
Board(RankNo, FileNo) = white(i)
pieceplaced = True
End If
End While
Next
For i = 0 To black.Length - 1
pieceplaced = False
While pieceplaced = False
RankNo = random.Next(1, 8)
FileNo = random.Next(1, 8)
If Board(RankNo, FileNo) = " " Then
Board(RankNo, FileNo) = black(i)
pieceplaced = True
End If
End While
Next
End If
End Sub
VB.Net solution
Answer:
ElseIf SampleGame = "R" Then
Dim WhitePieces(15) As String
Dim BlackPieces(15) As String
For i = 1 To 8
WhitePieces(i) = "WR"
BlackPieces(i) = "BR"
Next
WhitePieces(9) = "WG" : WhitePieces(10) = "WG" : WhitePieces(11) = "WE" : WhitePieces(12) = "WE" : WhitePieces(13) = "WN" : WhitePieces(14) = "WN" : WhitePieces(15) = "WM"
BlackPieces(9) = "BG" : BlackPieces(10) = "BG" : BlackPieces(11) = "BE" : BlackPieces(12) = "BE" : BlackPieces(13) = "BN" : BlackPieces(14) = "BN" : BlackPieces(15) = "BM"
'The fact that some pieces may overwrite others is fine, as long as the two sarrums are placed on the board
For i = 1 To Rnd() * 10 + 5
Board(Rnd() * 7 + 1, Rnd() * 7 + 1) = WhitePieces(Rnd() * 14 + 1)
Next
For i = 1 To Rnd() * 10 + 5
Board(Rnd() * 7 + 1, Rnd() * 7 + 1) = BlackPieces(Rnd() * 14 + 1)
Next
Board(Rnd() * 7 + 1, Rnd() * 7 + 1) = "WS"
Board(Rnd() * 7 + 1, Rnd() * 7 + 1) = "BS"
For j = 1 To 8
For s = 1 To 8
If Board(j, s) = "" Then
Board(j, s) = " "
End If
Next
Next
Python Solution
Answer:
import random #Allows the program to use the random module when selecting an integer.
def InitialiseBoard(Board, SampleGame):
if SampleGame == "Y":
for RankNo in range(1, BOARDDIMENSION + 1):
for FileNo in range(1, BOARDDIMENSION + 1):
Board[RankNo][FileNo] = " "
for Piece in range(0,random.randint(1,32)): #Adds a random number of pieces from 1-32.
NewPieceFile = random.randint(1,8)
NewPieceRank = random.randint(1,8)
NewPieceType = ["WR", "WM", "WG", "WN", "WE", "BR", "BM", "BG", "BN", "BE"]
NewPieceType = random.choice(NewPieceType)
Board[NewPieceRank][NewPieceFile] = NewPieceType
else:
break
Board[8][random.randint(1,8)] = "WS"
Board[1][random.randint(1,8)] = "BS"
Java Solution
Answer:
public Main() {
String[][] board = new String[BOARD_DIMENSION + 1][BOARD_DIMENSION + 1];
boolean gameOver;
int startSquare = 0;
int finishSquare = 0;
int startRank = 0;
int startFile = 0;
int finishRank = 0;
int finishFile = 0;
boolean moveIsLegal;
char playAgain;
char selectedGame;
char whoseTurn;
Position startPosition = new Position();
Position finishPosition = new Position();
playAgain = 'Y';
do {
whoseTurn = 'W';
gameOver = false;
console.print("What game would you like to play?\nS for Sample Game\nN for Normal Game\nR for Random Game\nQ for Quit "); // Adds in options for a random game
selectedGame = console.readChar();
if ((int)selectedGame >= 97 && (int)selectedGame <= 122) {
selectedGame = (char)((int)selectedGame - 32);
}
initialiseBoard(board, selectedGame);
do {
displayBoard(board);
displayWhoseTurnItIs(whoseTurn);
moveIsLegal = false;
do {
getMove(startPosition, finishPosition);
startSquare = startPosition.coordinates;
finishSquare = finishPosition.coordinates;
startRank = startSquare % 10;
startFile = startSquare / 10;
finishRank = finishSquare % 10;
finishFile = finishSquare / 10;
moveIsLegal = checkMoveIsLegal(board, startRank, startFile, finishRank, finishFile, whoseTurn);
if (!moveIsLegal) {
console.println("That is not a legal move - please try again");
}
} while (!moveIsLegal);
gameOver = checkIfGameWillBeWon(board, finishRank, finishFile);
makeMove(board, startRank, startFile, finishRank, finishFile, whoseTurn);
if (gameOver) {
displayWinner(whoseTurn);
}
if (whoseTurn == 'W') {
whoseTurn = 'B';
} else {
whoseTurn = 'W';
}
} while (!gameOver);
console.print("Do you want to play again (enter Y for Yes)? ");
playAgain = console.readChar();
if ((int)playAgain > 97 && (int)playAgain <= 122) {
playAgain = (char)((int)playAgain - 32);
}
} while (playAgain == 'Y');
}
void initialiseBoard(String[][] board, char selectedGame) {
int rankNo;
int fileNo;
if (selectedGame == 'S') {
for (rankNo = 1; rankNo <= BOARD_DIMENSION; rankNo++) {
for (fileNo = 1; fileNo <= BOARD_DIMENSION; fileNo++) {
board[rankNo][fileNo] = " ";
}
}
board[1][2] = "BG";
board[1][4] = "BS";
board[1][8] = "WG";
board[2][1] = "WR";
board[3][1] = "WS";
board[3][2] = "BE";
board[3][8] = "BE";
board[6][8] = "BR";
} else if (selectedGame == 'N') {
for (rankNo = 1; rankNo <= BOARD_DIMENSION; rankNo++) {
for (fileNo = 1; fileNo <= BOARD_DIMENSION; fileNo++) {
if (rankNo == 2) {
board[rankNo][fileNo] = "BR";
} else {
if (rankNo == 7) {
board[rankNo][fileNo] = "WR";
} else {
if ((rankNo == 1) || (rankNo == 8)) {
if (rankNo == 1) {
board[rankNo][fileNo] = "B";
}
if (rankNo == 8) {
board[rankNo][fileNo] = "W";
}
switch (fileNo) {
case 1:
case 8:
board[rankNo][fileNo] = board[rankNo][fileNo] + "G";
break;
case 2:
case 7:
board[rankNo][fileNo] = board[rankNo][fileNo] + "E";
break;
case 3:
case 6:
board[rankNo][fileNo] = board[rankNo][fileNo] + "N";
break;
case 4:
board[rankNo][fileNo] = board[rankNo][fileNo] + "M";
break;
case 5:
board[rankNo][fileNo] = board[rankNo][fileNo] + "S";
break;
}
} else {
board[rankNo][fileNo] = " ";
}
}
}
}
}
}
else if (selectedGame == 'R'){ //Random game option selected
for (rankNo = 1; rankNo <= BOARD_DIMENSION; rankNo++) for (fileNo = 1; fileNo <= BOARD_DIMENSION; fileNo++) board[rankNo][fileNo] = " "; //Fills all spaces with blanks
int randomFile;
int randomRank;
for(int i=0;i<8;i++){ //Fills in the eight black redum pieces
randomFile = 1 + (int)(Math.random() * BOARD_DIMENSION);
randomRank = 1 + (int)(Math.random() * BOARD_DIMENSION - 1); //Makes sure the redum pieces cannot spawn on the last rank on the opposite side
if (board[randomRank][randomFile].equals(" ")) board[randomRank][randomFile] = "BR";
else i--;
}
for(int i=0;i<8;i++){ //Fills in the eight white redum pieces
randomFile = 1 + (int)(Math.random() * BOARD_DIMENSION);
randomRank = 2 + (int)(Math.random() * BOARD_DIMENSION - 1); //Makes sure the redum pieces cannot spawn on the last rank on the opposite side
if (board[randomRank][randomFile].equals(" ")) board[randomRank][randomFile] = "WR";
else i--;
}
String[] randomPieces = {"G","E","N","M","N","E","G","S"}; //Array of the various non-redum pieces
for(int i=0;i<2;i++){ //for loop of length 2 to have two sets; one for each colour
String colour;
if (i == 0)colour = "B";
else colour = "W";
for(int ii=0;ii<randomPieces.length;ii++){
randomFile = 1 + (int)(Math.random() * BOARD_DIMENSION);
randomRank = 1 + (int)(Math.random() * BOARD_DIMENSION);
if (board[randomRank][randomFile].equals(" ")) board[randomRank][randomFile] = colour + randomPieces[ii];
else ii--;
}
}
}
else if (selectedGame == 'Q'){System.exit(0);}
}
Pascal Solution
Answer:
Var
index: integer;
Row: array [1..8] of integer ;
column:array [1..8] of integer;
RankNo : Integer;
FileNo : Integer;
Begin
Randomize; //-----------uses time to randomize pointer otherwise every time program is run the same random number is used
for index:= 1 to 8 do
begin
Row[index]:= index; // putting it into an array makes sure that the no same co-ordinate is repeated so you don't get (2,2) and (2,2) again
column[index]:= index;
end;
for index:= 1 to 8 do
begin
Row[index]:= Row[index + Random(8-index)];// randomize the order of values in the array
column[index]:= column[index + Random(8-index)]
end;
If SampleGame = 'Y'
Then
Begin
For RankNo := 1 To BoardDimension
Do
For FileNo := 1 To BoardDimension
Do Board[RankNo, FileNo] := ' ';
Board[Row[1], column[1]] := 'BG';
Board[Row[2], column[2]] := 'BS';
Board[Row[3], column[3]] := 'WG';
Board[Row[4], column[4]] := 'WR';
Board[Row[5], column[5]] := 'WS';
Board[Row[6], column[6]] := 'BE';
Board[Row[7], column[7]] := 'BE';
Board[Row[8], column[8]] := 'BR';
End
//By Arif Elahi
C# Solution
Answer:
VB6.0 Solution
Answer:
Promote Marzaz Pani to Kashshaptu when it reaches home rank
[edit | edit source]Add a rule that Marzaz Pani (royal attendant) pieces can be promoted to a Kashshaptu (witch) piece if it reaches the front rank (the eighth rank for a white redum, the first rank for a black redum). (NB Makemove() already contains code for promoting Redum to Marzaz Pani) This would involve adding the Kashshaptu (witch) piece - which could have the same movement as a queen in chess.
VB.Net solution
Answer:
Function CheckKashshaptuMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer) As Boolean
Dim KashshaptuMoveIsLegal As Boolean = False
Dim Count As Integer
Dim RankDifference As Integer
Dim FileDifference As Integer
RankDifference = FinishRank - StartRank ' Negative if moving Bottom to Top.
FileDifference = FinishFile - StartFile ' Negative if moving Right to Left.
' Much the same as Checking Gisgigir Move.
If RankDifference = 0 Then ' Moving Horizontally.
If FileDifference >= 1 Then ' Moving Left to Right.
KashshaptuMoveIsLegal = True
For Count = 1 To FileDifference - 1 Step 1
Debug.WriteLine(Board(StartRank, StartFile + Count))
If Board(StartRank, StartFile + Count) <> " " Then
KashshaptuMoveIsLegal = False ' There is something in our path so move is not legal.
End If
Next
ElseIf FileDifference <= -1 Then ' Moving Right to Left.
KashshaptuMoveIsLegal = True
For Count = -1 To FileDifference + 1 Step -1
If Board(StartRank, StartFile + Count) <> " " Then
KashshaptuMoveIsLegal = False
End If
Next
End If
ElseIf FileDifference = 0 Then ' Moving Vertically
If RankDifference >= 1 Then ' Moving Top to Bottom.
KashshaptuMoveIsLegal = True
For Count = 1 To RankDifference - 1 Step 1
If Board(StartRank + Count, StartFile) <> " " Then
KashshaptuMoveIsLegal = False
End If
Next
ElseIf RankDifference <= -1 Then ' Moving Bottom to Top.
KashshaptuMoveIsLegal = True
For Count = -1 To RankDifference + 1 Step -1
If Board(StartRank + Count, StartFile) <> " " Then
KashshaptuMoveIsLegal = False
End If
Next
End If
ElseIf Abs(RankDifference) = Abs(FileDifference) Then ' Moving Diagonally.
KashshaptuMoveIsLegal = True
Dim RankChange As Integer
Dim FileChange As Integer
If RankDifference >= 1 Then
RankChange = 1
Else
RankChange = -1
End If
If FileDifference >= 1 Then
FileChange = 1
Else
FileChange = -1
End If
For Count = 1 To RankDifference Step 1
If Board(StartRank + (Count * RankChange), StartFile + (Count * FileChange)) <> " " Then
KashshaptuMoveIsLegal = False
End If
Next
End If
Return KashshaptuMoveIsLegal
End Function
Function CheckMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer, ByVal WhoseTurn As Char) As Boolean
' ...
Select Case PieceType
' ...
Case "K" ' Kashshaptu
Return CheckKashshaptuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
Case Else
Return False
End Select
End Function
Sub MakeMove(ByRef Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer, ByVal WhoseTurn As Char)
If WhoseTurn = "W" And FinishRank = 1 And Board(StartRank, StartFile)(1) = "R" Then
' ...
ElseIf WhoseTurn = "B" And FinishRank = 8 And Board(StartRank, StartFile)(1) = "R" Then
' ...
' Marzaz Pani to Kashshaptu upon reaching opponent's side wih Marzaz Pani.
' However, a Marzaz Pani starts on Rank 8 for White and Rank 1 for Black meaning that
' it could quickly and easily be abused and upgraded. Perhaps swap 8 and 1 around?
ElseIf WhoseTurn = "W" And FinishRank = 8 And Board(StartRank, StartFile)(1) = "M" Then
Board(FinishRank, FinishFile) = "WK"
Board(StartRank, StartFile) = " "
ElseIf WhoseTurn = "B" And FinishRank = 1 And Board(StartRank, StartFile)(1) = "M" Then
Board(FinishRank, FinishFile) = "BK"
Board(StartRank, StartFile) = " "
Else
' ...
End If
End Sub
Python Solution
Answer:
def CheckKashshaptuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile):
CheckKashshaptuMoveIsLegal = False
RankDifference = FinishRank - StartRank
FileDifference = FinishFile - StartFile
#This is to ensure that the path of the Kashshaptu is checked properly.
#For example, if you used RankDifference in the loop below then
#if RankDifference was 0 then the move would be legal despite colliding with other pieces.
Displacement = RankDifference if RankDifference > FileDifference else FileDifference
if (abs(RankDifference) == abs(FileDifference)) or (RankDifference == 0) or (FileDifference == 0):
CheckKashshaptuMoveIsLegal = True
ChangeCheck = lambda x: 1 if x>0 else 0 if x==0 else -1
RankIncrement = ChangeCheck(RankDifference)
FileIncrement = ChangeCheck(FileDifference)
RankChange = RankIncrement
FileChange = FileIncrement
#Checking if the next place is empty is the same as the check for the Gisgigir with small changes to include all directions in one piece of code.
for Count in range(1, Displacement):
if Board[StartRank + RankChange][StartFile + FileChange] != " ":
CheckKashshaptuMoveIsLegal = False
RankChange += RankIncrement
FileChange += FileIncrement
return CheckKashshaptuMoveIsLegal
#Python 3
Java Solution
Answer:
void makeMove(String[][] board, int startRank, int startFile, int finishRank, int finishFile, char whoseTurn) {
if ((whoseTurn == 'W') && (finishRank == 1) && (board[startRank][startFile].charAt(1) == 'R')) {
board[finishRank][finishFile] = "WM";
board[startRank][startFile] = " ";
}
else {
if ((whoseTurn == 'B') && (finishRank == 8) && (board[startRank][startFile].charAt(1) == 'R')) {
board[finishRank][finishFile] = "BM";
board[startRank][startFile] = " ";
}
if ((whoseTurn == 'W') && (finishRank == 1) && (board[startRank][startFile].charAt(1) == 'M')) {
board[finishRank][finishFile] = "WK";
board[startRank][startFile] = " ";
}
else {
if ((whoseTurn == 'B') && (finishRank == 8) && (board[startRank][startFile].charAt(1) == 'M')) {
board[finishRank][finishFile] = "BK";
board[startRank][startFile] = " ";
}
else {
board[finishRank][finishFile] = board[startRank][startFile];
board[startRank][startFile] = " ";
}
}
}
}
void makeMove(String[][] board, int startRank, int startFile, int finishRank, int finishFile, char whoseTurn) {
if ((whoseTurn == 'W') && (finishRank == 1) && (board[startRank][startFile].charAt(1) == 'R')) {
board[finishRank][finishFile] = "WM";
board[startRank][startFile] = " ";
}
else {
if ((whoseTurn == 'B') && (finishRank == 8) && (board[startRank][startFile].charAt(1) == 'R')) {
board[finishRank][finishFile] = "BM";
board[startRank][startFile] = " ";
}
if ((whoseTurn == 'W') && (finishRank == 1) && (board[startRank][startFile].charAt(1) == 'M')) {
board[finishRank][finishFile] = "WK";
board[startRank][startFile] = " ";
}
else {
if ((whoseTurn == 'B') && (finishRank == 8) && (board[startRank][startFile].charAt(1) == 'M')) {
board[finishRank][finishFile] = "BK";
board[startRank][startFile] = " ";
}
else {
board[finishRank][finishFile] = board[startRank][startFile];
board[startRank][startFile] = " ";
}
}
}
}
Pascal Solution
Answer:
***This code may look long but the code allowing the piece to move like a Rook from chess is
copied from the function CheckGisgigirMoveIsLegal and modified slightly by
just changing some variable names, to move diagonally check the code before the last End ***
Function CheckKashshaptuMoveIsLegal(Var Board : TBoard; StartRank, StartFile, FinishRank, FinishFile : Integer): Boolean;
Var
amountFile: Integer;
amountRank: Integer;
MoveIsLegal : Boolean;
Count : Integer;
RankDifference : Integer;
FileDifference : Integer;
Begin
MoveIsLegal := False;
RankDifference := FinishRank - StartRank;
FileDifference := FinishFile - StartFile;
If RankDifference = 0
Then
Begin
If FileDifference >= 1
Then
Begin
MoveIsLegal := True;
For Count := 1 To FileDifference - 1
Do
Begin
If Board[StartRank, StartFile + Count] <> ' '
Then MoveIsLegal := False
End;
End
Else
Begin
If FileDifference <= -1
Then
Begin
MoveIsLegal := True;
For Count := -1 DownTo FileDifference + 1
Do
Begin
If Board[StartRank, StartFile + Count] <> ' '
Then MoveIsLegal := False
End;
End;
End;
End
Else
Begin
If FileDifference = 0
Then
Begin
If RankDifference >= 1
Then
Begin
MoveIsLegal := True;
For Count := 1 To RankDifference - 1
Do
Begin
If Board[StartRank + Count, StartFile] <> ' '
Then MoveIsLegal := False
End;
End
Else
Begin
If RankDifference <= -1
Then
Begin
MoveIsLegal := True;
For Count := -1 DownTo RankDifference + 1
Do
Begin
If Board[StartRank + Count, StartFile] <> ' '
Then MoveIsLegal := False
End;
End;
End;
End;
End;
MoveIsLegal:= False;
amountFile:= FinishFile - StartFile;
amountRank:=FinishRank - StartRank;
If AmountRank = AmountFile
then MoveIsLegal:= True;
CheckKashshaptuMoveIsLegal:= MoveIslegal
End;
By Arif Elahi
C# Solution
Answer:
public static Boolean CheckKashshaptuMoveIsLegal(string[,] Board, int StartRank, int StartFile, int FinishRank, int FinishFile)
{
Boolean KashshaptuMoveIsLegal;
int Count;
int RankDifference;
int FileDifference;
KashshaptuMoveIsLegal = false;
RankDifference = FinishRank - StartRank;
FileDifference = FinishFile - StartFile;
if (RankDifference == 0)
{
if (FileDifference >= 1)
{
KashshaptuMoveIsLegal = true;
for (Count = 1; Count <= FileDifference - 1; Count++)
if (Board[StartRank, StartFile + Count] != " ")
KashshaptuMoveIsLegal = false;
}
else
if (FileDifference <= -1)
{
KashshaptuMoveIsLegal = true;
for (Count = -1; Count >= FileDifference + 1; Count--)
if (Board[StartRank, StartFile + Count] != " ")
KashshaptuMoveIsLegal = false;
}
}
else if (FileDifference == 0)
if (RankDifference >= 1)
{
KashshaptuMoveIsLegal = true;
for (Count = 1; Count <= RankDifference - 1; Count++)
{
if (Board[StartRank + Count, StartFile] != " ")
KashshaptuMoveIsLegal = false;
}
}
else
if (RankDifference <= -1)
{
KashshaptuMoveIsLegal = true;
for (Count = -1; Count >= RankDifference + 1; Count--)
if (Board[StartRank + Count, StartFile] != " ")
KashshaptuMoveIsLegal = false;
}
return KashshaptuMoveIsLegal;
}
public static Boolean CheckMoveIsLegal(string[,] Board, int StartRank, int StartFile, int FinishRank, int FinishFile, char WhoseTurn)
{
char PieceType;
char PieceColour;
Boolean MoveIsLegal = true;
if ((FinishFile == StartFile) && (FinishRank == StartRank))
MoveIsLegal = false;
PieceType = Board[StartRank, StartFile][1];
PieceColour = Board[StartRank, StartFile][0];
if (WhoseTurn == 'W')
{
if (PieceColour != 'W')
MoveIsLegal = false;
if (Board[FinishRank, FinishFile][0] == 'W')
MoveIsLegal = false;
}
else
{
if (PieceColour != 'B')
MoveIsLegal = false;
if (Board[FinishRank, FinishFile][0] == 'B')
MoveIsLegal = false;
}
if (MoveIsLegal)
switch (PieceType)
{
case 'R':
MoveIsLegal = CheckRedumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, PieceColour);
break;
case 'S':
MoveIsLegal = CheckSarrumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
case 'M':
MoveIsLegal = CheckMarzazPaniMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
case 'G':
MoveIsLegal = CheckGisgigirMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
case 'N':
MoveIsLegal = CheckNabuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
case 'E':
MoveIsLegal = CheckEtluMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
case 'K': //Add this one
MoveIsLegal = CheckKashshaptuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
default:
MoveIsLegal = false;
break;
}
return MoveIsLegal;
}
public static void MakeMove(ref string[,] Board, int StartRank, int StartFile, int FinishRank, int FinishFile, char WhoseTurn)
{
if ((WhoseTurn == 'W') && (FinishRank == 1) && (Board[StartRank, StartFile][1] == 'R'))
{
Board[FinishRank, FinishFile] = "WK"; //Instead of WM change it to WK
Board[StartRank, StartFile] = " ";
}
else
if ((WhoseTurn == 'B') && (FinishRank == 8) && (Board[StartRank, StartFile][1] == 'R'))
{
Board[FinishRank, FinishFile] = "BK"; //Instead of WM change it to WK
Board[StartRank, StartFile] = " ";
}
else
{
Board[FinishRank, FinishFile] = Board[StartRank, StartFile];
Board[StartRank, StartFile] = " ";
}
}
//UTC Reading
VB6.0 Solution
Answer:
Prevent pieces from moving backwards
[edit | edit source]Add a rule to CheckMoveIsLegal that means all pieces can only move forward and can not retreat
VB.Net solution
Answer:
Function CheckMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer, ByVal WhoseTurn As Char) As Boolean
' ...
If WhoseTurn = "W" Then
' ...
If StartRank < FinishRank Then
Return False
End If
Else
' ...
If StartRank > FinishRank Then
Return False
End If
End If
' ...
End Function
Python Solution
Answer:
def CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn):
if WhoseTurn == "W":
if PieceColour != "W":
MoveIsLegal = False
if(FinishRank > StartRank): ###### **Edited part of the code**
MoveIsLegal = False ###### **Edited part of the code**
else:
if PieceColour != "B":
MoveIsLegal = False
if(FinishRank < StartRank): ###### **Edited part of the code**
MoveIsLegal = False ###### **Edited part of the code**
#------------------------------------------------------------------------------------------------------------------
#whole sub with edited part
def CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn):
MoveIsLegal = True
if (FinishFile == StartFile) and (FinishRank == StartRank):
MoveIsLegal = False
else:
PieceType = Board[StartRank][StartFile][1]
PieceColour = Board[StartRank][StartFile][0]
if FinishRank == 0 or FinishFile == 0: #
MoveIsLegal = False #
if WhoseTurn == "W":
if PieceColour != "W":
MoveIsLegal = False
if(FinishRank > StartRank): ######
MoveIsLegal = False ######
if Board[FinishRank][FinishFile][0] == "W":
MoveIsLegal = False
else:
if PieceColour != "B":
MoveIsLegal = False
if(FinishRank < StartRank): ######
MoveIsLegal = False ######
if Board[FinishRank][FinishFile][0] == "B":
MoveIsLegal = False
if MoveIsLegal == True:
if PieceType == "R":
MoveIsLegal = CheckRedumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, PieceColour)
elif PieceType == "S":
MoveIsLegal = CheckSarrumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
elif PieceType == "M":
MoveIsLegal = CheckMarzazPaniMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
elif PieceType == "G":
MoveIsLegal = CheckGisgigirMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
elif PieceType == "N":
MoveIsLegal = CheckNabuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
elif PieceType == "E":
MoveIsLegal = CheckEtluMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
return MoveIsLegal
#Python solution by Jan-Christian Escayg [Bullers Squaa]
#Big up London
Java Solution
Answer:
boolean checkMoveIsLegal(String[][] board, int startRank, int startFile, int finishRank, int finishFile, char whoseTurn) {
char pieceType;
char pieceColour;
boolean moveIsLegal = true;
if ((finishFile == startFile) && (finishRank == startRank)) {
moveIsLegal = false;
}
pieceType = board[startRank][startFile].charAt(1);
pieceColour = board[startRank][startFile].charAt(0);
if (whoseTurn == 'W') {
if (pieceColour != 'W') {
moveIsLegal = false;
}
if (board[finishRank][finishFile].charAt(0) == 'W') {
moveIsLegal = false;
}
if (finishRank > startRank){
moveIsLegal = false;
}
} else {
if (pieceColour != 'B') {
moveIsLegal = false;
}
if (board[finishRank][finishFile].charAt(0) == 'B') {
moveIsLegal = false;
}
if (finishRank < startRank){
moveIsLegal = false;
}
}
if (moveIsLegal) {
switch (pieceType) {
case 'R':
moveIsLegal = checkRedumMoveIsLegal(board, startRank, startFile, finishRank, finishFile, pieceColour);
break;
case 'S':
moveIsLegal = checkSarrumMoveIsLegal(board, startRank, startFile, finishRank, finishFile);
break;
case 'M':
moveIsLegal = checkMarzazPaniMoveIsLegal(board, startRank, startFile, finishRank, finishFile);
break;
case 'G':
moveIsLegal = checkGisgigirMoveIsLegal(board, startRank, startFile, finishRank, finishFile);
break;
case 'N':
moveIsLegal = checkNabuMoveIsLegal(board, startRank, startFile, finishRank, finishFile);
break;
case 'E':
moveIsLegal = checkEtluMoveIsLegal(board, startRank, startFile, finishRank, finishFile);
break;
default:
moveIsLegal = false;
break;
}
}
return moveIsLegal;
}
//Ainsley Rutterford.
Pascal Solution
Answer:
If WhoseTurn = 'W'
Then
Begin
If PieceColour <> 'W'
Then MoveIsLegal := False;
If Board[FinishRank, FinishFile][1] = 'W'
Then MoveIsLegal := False;
If (FinishRank > StartRank)
Then MoveIsLegal := False;
End
Else
Begin
If PieceColour <> 'B'
Then MoveIsLegal := False;
If Board[FinishRank, FinishFile][1] = 'B'
Then MoveIsLegal := False;
If (FinishRank < StartRank)
Then MoveIsLegal := False;
End;
By Eddie V
C# Solution
Answer:
public static Boolean CheckMoveIsLegal(string[,] Board, int StartRank, int StartFile, int FinishRank, int FinishFile, char WhoseTurn)
{
char PieceType;
char PieceColour;
Boolean MoveIsLegal = true;
if ((FinishFile == StartFile) && (FinishRank == StartRank))
MoveIsLegal = false;
PieceType = Board[StartRank, StartFile][1];
PieceColour = Board[StartRank, StartFile][0];
if (WhoseTurn == 'W')
{
if (PieceColour != 'W' || Board[FinishRank, FinishFile][0] == 'W' || FinishRank > StartRank)
{
MoveIsLegal = false;
}
}
else
{
if (PieceColour != 'B' || Board[FinishRank, FinishFile][0] == 'B' || FinishRank < StartRank)
{
MoveIsLegal = false;
}
}
// Answer once again coming from the fabulous institution that is UTC Reading ヽ༼ຈل͜ຈ༽ノ Raise Your Dangersヽ༼ຈل͜ຈ༽ノ
VB6.0 Solution
Answer:
Add new piece that behaves like knight in chess
[edit | edit source]Add a new piece that behaves like a knight in chess - see here for details
VB.Net solution
Answer:
Function checkKnightMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer) As Boolean
If (Abs(FinishFile - StartFile) = 1 And Abs(FinishRank - StartRank) = 2) Or (Abs(FinishRank - StartRank) = 1 And Abs(FinishFile - StartFile) = 2) Then
Return True
End If
Return False
End Function
'Stan - Ecclesbourne, A Level
Python Solution
Answer:
def CheckKnightMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile):
CheckKnightMoveIsLegal = False
if (FinishFile == StartFile + 2 and FinishRank == StartRank + 1) or (FinishFile == StartFile - 2 and FinishRank == StartRank + 1) or (FinishFile == StartFile - 2 and FinishRank == StartRank - 1) or (FinishFile == StartFile + 2 and FinishRank == StartRank - 1) or (FinishFile == StartFile + 1 and FinishRank == StartRank + 2) or (FinishFile == StartFile - 1 and FinishRank == StartRank +2 ) or (FinishFile == StartFile + 1 and FinishRank == StartRank - 2) or (FinishFile == StartFile - 1 and FinishRank == StartRank - 2):
CheckKnightMoveIsLegal = True
return(CheckKnightMoveIsLegal)
# Previous code does work; however it could move an extra space. The 'FinishFile == StartFile + 3' is now 'FinishFile == StartFile + 2' so it follows the Knights movement pattern.
# Python by Dill ICHS
#This is a better way,
def CheckKnightMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile):
CheckKnightMoveIsLegal = False
if (abs(FinishFile - StartFile) == 2 and abs(FinishRank - StartRank) == 1 or abs(FinishFile - StartFile) == 1 and abs(FinishRank - StartRank) == 2):
CheckKnightMoveIsLegal = True
return CheckKnightMoveIsLegal
# Python 3, By Rahul ICHS
def CheckKnightMoveIsLegal(Board, StartSquare, FinishSquare):
CheckKnightMoveIsLegal = True if abs(FinishSquare - StartSquare) == (12 or 21) else False
#Python 3, una línea por Mohsin ICHS
Java Solution
Answer:
boolean checkKnightMoveIsLegal(String[][] board, int startRank, int startFile, int finishRank, int finishFile){
boolean knightMoveIsLegal = false;
if ((abs(finishFile - startFile) == 2 && abs(finishRank - startRank) == 1) || (abs(finishFile - startFile) == 1 && abs(finishRank - startRank) == 2))
{
knightMoveIsLegal = true;
}
return knightMoveIsLegal;
}
Remember to add case 'K' to switch statement in checkMoveIsLegal method and make the board bigger
Amy Rainbow + Rajan , HGS
Pascal Solution
Answer:
-------------------------------------------------------------------------------------------------------------------------------
JACK SWEASEY OF STEYNING GRAMMAR
To make a knight like piece all you have to do is edit the Etlu code like such:
Function CheckEtluMoveIsLegal(Var Board : TBoard; StartRank, StartFile, FinishRank, FinishFile : Integer) : Boolean;
Begin
CheckEtluMoveIsLegal := False;
If (Abs(FinishFile - StartFile) = 2) And (Abs(FinishRank - StartRank) = 1)
Or (Abs(FinishFile - StartFile) = 1) And (Abs(FinishRank - StartRank) = 2)
Then CheckEtluMoveIsLegal := True;
End;
If you do not notice the change, you change the 0 in (Abs(FinishRank - StartRank) = 1) and (Abs(FinishFile - StartFile) = 1) to a 1 which I have already done. It's pretty ez pz.
-------------------------------------------------------------------------------------------------------------------------------
C# Solution Jamal Arif of Nelson and Colne College
Answer:
//Create the following subroutine:
public static Boolean CheckKnightMoveIsLegal(string[,] Board, int StartRank, int StartFile, int FinishRank, int FinishFile)
{
Boolean KnightMoveIsLegal = false;
if ((Math.Abs(FinishFile - StartFile) == 2) && (Math.Abs(FinishRank - StartRank) == 1)
|| (Math.Abs(FinishFile - StartFile) == 1) && (Math.Abs(StartRank - FinishRank) == 2))
{
KnightMoveIsLegal = true;
}
return KnightMoveIsLegal;
}
// Then in the CheckMoveIsLegal subroutine, add another case statement like this :
case 'k':
MoveIsLegal = CheckKnightMoveIsLegal(Board, StartRank,StartFile, FinishRank, FinishFile);
break;
default:
// Finally, in the InitialiseBoard subroutine add the following in the else statement right at the end:
else
{
Board[RankNo, FileNo] = " ";
Board[6, 1] = "Wk";
}
//This actually puts the piece on the board.
VB6.0 Solution
Answer:
Allow Sarrum and Gisgigir to castle (as with king and rook in chess)
[edit | edit source]Allow a Sarrum (king) and Gisgigir (chariot) to castle (as in chess with a king and rook).
See here for details on castling in chess
VB.Net solution
Answer:
Function CheckSarrumMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer) As Boolean
If Abs(FinishFile - StartFile) <= 1 And Abs(FinishRank - StartRank) <= 1 Then
Return True
End If
' Castling sarum(king) with gisgigir(rook)
If (StartRank = 1 Or StartRank = 8) And StartFile = 5 And Abs(FinishFile - StartFile) = 2 And Abs(FinishRank - StartRank) = 0 Then
Return True
End If
Return False
End Function
Sub MakeMove(ByRef Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer, ByVal WhoseTurn As Char)
If WhoseTurn = "W" And FinishRank = 1 And Board(StartRank, StartFile)(1) = "R" Then
Board(FinishRank, FinishFile) = "WM"
Board(StartRank, StartFile) = " "
ElseIf WhoseTurn = "B" And FinishRank = 8 And Board(StartRank, StartFile)(1) = "R" Then
Board(FinishRank, FinishFile) = "BM"
Board(StartRank, StartFile) = " "
ElseIf WhoseTurn = "W" And StartRank = 8 And FinishRank = 8 And Abs(StartFile - FinishFile) = 2 And FinishFile = StartFile + 2 And Board(StartRank, StartFile)(1) = "S" Then ' Castling king side only (white)
Board(FinishRank, FinishFile) = Board(StartRank, StartFile)
Board(StartRank, StartFile + 1) = "WG"
Board(StartRank, StartFile) = " "
Board(FinishRank, FinishFile + 1) = " "
ElseIf WhoseTurn = "B" And StartRank = 1 And FinishRank = 1 And Abs(StartFile - FinishFile) = 2 And FinishFile = StartFile + 2 And Board(StartRank, StartFile)(1) = "S" Then ' Castling king side only (black)
Board(FinishRank, FinishFile) = Board(StartRank, StartFile)
Board(StartRank, StartFile + 1) = "BG"
Board(StartRank, StartFile) = " "
Board(FinishRank, FinishFile + 1) = " "
ElseIf WhoseTurn = "W" And StartRank = 8 And FinishRank = 8 And Abs(StartFile - FinishFile) = 2 And FinishFile = StartFile - 2 And Board(StartRank, StartFile)(1) = "S" Then ' Castling queen side only (white)
Board(FinishRank, FinishFile) = Board(StartRank, StartFile)
Board(FinishRank, FinishFile + 1) = "WG"
Board(StartRank, StartFile) = " "
Board(FinishRank, FinishFile - 2) = " "
ElseIf WhoseTurn = "B" And StartRank = 1 And FinishRank = 1 And Abs(StartFile - FinishFile) = 2 And FinishFile = StartFile - 2 And Board(StartRank, StartFile)(1) = "S" Then ' Castling queen side only (black)
Board(FinishRank, FinishFile) = Board(StartRank, StartFile)
Board(FinishRank, FinishFile + 1) = "WG"
Board(StartRank, StartFile) = " "
Board(FinishRank, FinishFile - 2) = " "
Else
Board(FinishRank, FinishFile) = Board(StartRank, StartFile)
Board(StartRank, StartFile) = " "
End If
End Sub
'-jC March '15
Python Solution
Answer:
Java Solution
Answer:
boolean checkSarrumMoveIsLegal(String[][] board, int startRank, int startFile, int finishRank, int finishFile) {
boolean sarrumMoveIsLegal = false;
if ((startFile == 5) && (( startRank == 1)||( startRank == 8)) && ((finishFile == 3)||(finishFile == 7)) && startRank == finishRank) {
//If if statement is true then player is attempting at castling
//queenside
if(finishFile == 3){
for(int i = 2; i < 5 ; i++){
if (!board[startRank][i].equals(" ")) {
return false;
}
}
if((board[startRank][1].charAt(0) != board[startRank][startFile].charAt(0))||board[startRank][1].charAt(1) != 'G'){
return false;
}
}
//kingside
if(finishFile == 7){
for(int i = 6; i < 8 ; i++){
if (!board[startRank][i].equals(" ")) {
return false;
}
}
if((board[startRank][8].charAt(0) != board[startRank][startFile].charAt(0))||board[startRank][8].charAt(1) != 'G'){
return false;
}
}
sarrumMoveIsLegal = true;
}
if ((abs(finishFile - startFile) <= 1) && (abs(finishRank - startRank) <= 1)) {
sarrumMoveIsLegal = true;
}
return sarrumMoveIsLegal;
}
void makeMove(String[][] board, int startRank, int startFile, int finishRank, int finishFile, char whoseTurn) {
if(board[startRank][startFile].charAt(1) == 'S' && (finishRank == startRank) && (finishFile == 3 || finishFile == 7) && startFile == 5){
if (finishFile == 3){
board[startRank][5] = " ";
board[startRank][1] = " ";
board[startRank][3] = whoseTurn + "S";
board[startRank][4] = whoseTurn + "R";
}
else{
board[startRank][5] = " ";
board[startRank][8] = " ";
board[startRank][7] = whoseTurn + "S";
board[startRank][6] = whoseTurn + "R";
}
}
if ((whoseTurn == 'W') && (finishRank == 1) && (board[startRank][startFile].charAt(1) == 'R')) {
board[finishRank][finishFile] = "WM";
board[startRank][startFile] = " ";
} else {
if ((whoseTurn == 'B') && (finishRank == 8) && (board[startRank][startFile].charAt(1) == 'R')) {
board[finishRank][finishFile] = "BM";
board[startRank][startFile] = " ";
} else {
board[finishRank][finishFile] = board[startRank][startFile];
board[startRank][startFile] = " ";
}
}
}
^_^ Reading School
Pascal Solution
Answer:
Not full castling but hard enough. Checks to make sure Gisgigir and Sarrum in starting position and nothing between
Function CheckSarrumMoveIsLegal(Var Board : TBoard; StartRank, StartFile, FinishRank, FinishFile : Integer; WhoseTurn:Char) : Boolean;
var count:integer;
rank:integer;
fileCheck:integer;
numErrors:integer;
Begin
CheckSarrumMoveIsLegal :=False;
numErrors:=0;
//original check to see if moved 1 space in any direction
If (Abs(FinishFile - StartFile) <= 1) And (Abs(FinishRank - StartRank) <= 1)
Then CheckSarrumMoveIsLegal := True
//new code check to see if moved by 2 columns and 0 rows - potential Gisgigiring
else if (StartFile=5) and (Abs(FinishFile - StartFile) = 2) and (Abs(FinishRank - StartRank) =0)then
begin
//if they have then sent up rank and file
if WhoseTurn = 'W' then rank:=8 else rank:=1;
if FinishFile < StartFile then Filecheck:=1 else Filecheck:=8;
//Check that Gisgigir and Sarrum are in the original co-ordinate
if (Board[Rank,Filecheck][2]='G') or (Board[Rank,5][2]='S') then
begin
//Now check to see if the co-ordinates for any of the rest of the files in that rank are not empty
for count := 2 to 7 do
if (count <>5) and ((Board[Rank, Count][1]='B') or (Board[Rank,Count][1]='W')) then numErrors:=numErrors+1;
//If there are no errors move the Gisgigir - the Sarrum will be moved as part of the MakeMove function
if numErrors=0 then
begin
if filecheck=1 then board[rank,4]:=WhoseTurn+'G'
else board[rank,6]:=WhoseTurn+'G';
board[rank,filecheck]:=' ';
checkSarrumMoveIsLegal:=True
end
end;
end;
End;
Gill Meek
-------------------------------------------------------------------------------------------------------------------------------
FULL SOLUTION WITH PROPER CASTLING BY JACK SWEASEY FROM STEYNING GRAMMAR
Extra Global Variables:
CastleTake : Boolean;
BMove : Integer;
WMove : Integer;
Custom procedures follow:
Procedure OfferCastleW;
Var
Castle:Char;
Begin
Writeln('Do you want to castle? (Y for Yes)');
Readln(Castle);
If Castle='Y'
Then
Begin
Board[8,7]:='WS';
Board[8,6]:='WG';
Board[8,5]:=' ';
Board[8,8]:=' ';
CastleTake:=True;
end
Else
end;
Procedure OfferCastleB;
Var
Castle:Char;
Begin
Writeln('Do you want to castle? (Y for Yes)');
Readln(Castle);
If Castle='Y'
Then
Begin
Board[1,7]:='BS';
Board[1,6]:='BG';
Board[1,5]:=' ';
Board[1,8]:=' ';
CastleTake:=True;
end
Else
end;
Procedure CheckWMove;
Begin
If (Board[8,5]<>'WS') or (Board[8,8]<>'WG')
Then
WMove:=WMove+1;
end;
Procedure CheckBMove;
Begin
If (Board[1,5]<>'BS') or (Board[1,8]<>'BG')
Then
BMove:=BMove+1;
end;
Procedure CheckCastle;
Begin
If WhoseTurn='W'
Then
Begin
If (Board[8,5]='WS') and (Board[8,8]='WG') and (WMove=1)
Then
If (Board[8,6]=' ') and ((Board[8,7])=' ')
Then
Begin
OfferCastleW;
end;
end
Else
Begin
If (Board[1,5]='BS') and (Board[1,8]='BG') and (BMove=1)
Then
If ((Board[1,6])=' ') and ((Board[1,7])=' ')
Then
Begin
OfferCastleB;
end;
end;
end;
Edited main code with edits commented:
Begin
PlayAgain := 'Y';
//WMove:=1;
//BMove:=1;
Repeat
WhoseTurn := 'W';
GameOver := False;
Write('Do you want to play the sample game (enter Y for Yes)? ');
Readln(SampleGame);
If (Ord(SampleGame) >= 97) and (Ord(SampleGame) <= 122)
Then SampleGame := Chr(Ord(SampleGame) - 32);
InitialiseBoard(Board, SampleGame);
Repeat
DisplayBoard(Board);
DisplayWhoseTurnItIs(WhoseTurn);
MoveIsLegal := False;
//CheckWMove;
//CheckBMove;
//CheckCastle;
//If CastleTake=False
//Then
//Begin
Repeat
GetMove(StartSquare, FinishSquare);
StartRank := StartSquare Mod 10;
StartFile := StartSquare Div 10;
FinishRank := FinishSquare Mod 10;
FinishFile := FinishSquare Div 10;
MoveIsLegal := CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn);
If Not MoveIsLegal
Then Writeln('That is not a legal move - please try again');
Until MoveIsLegal;
//end;
//If CastleTake=False
//Then
//Begin
GameOver := CheckIfGameWillBeWon(Board, FinishRank, FinishFile);
MakeMove(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn);
If GameOver
Then DisplayWinner(WhoseTurn);
//end;
//CastleTake:=False;
If WhoseTurn = 'W'
Then WhoseTurn := 'B'
Else WhoseTurn := 'W';
Until GameOver;
Write('Do you want to play again (enter Y for Yes)? ');
Readln(PlayAgain);
If (Ord(PlayAgain) >= 97) and (Ord(PlayAgain) <= 122)
Then PlayAgain := Chr(Ord(PlayAgain) - 32);
Until PlayAgain <> 'Y';
End.
C# Solution
Answer:
VB6.0 Solution
Answer:
Track number of moves
[edit | edit source]Add variables to keep track of how many moves each player has had. Add an option to limit a game to 10, 20, or 50 moves - with who ever has the most pieces left after said moves declared the winner.
VB.Net solution
Answer:
Sub Main()
Dim Board(BoardDimension, BoardDimension) As String
' ...
Dim MoveCount As Double = 0
Dim GameLength As Integer = -1
PlayAgain = "Y"
Do
WhoseTurn = "W"
GameOver = False
Console.Write("Do you want to play the sample game (enter Y for Yes)? ")
SampleGame = UCase(Console.ReadLine)
Console.Write("Do you want to limit game moves? Enter a number or -1 for no limit: ")
' ...
Do
DisplayBoard(Board)
DisplayWhoseTurnItIs(WhoseTurn)
MoveIsLegal = False
MoveCount = MoveCount + 0.5
If GameLength <> -1 Then
Console.WriteLine("This is turn number " & Math.Round(MoveCount, 0, MidpointRounding.AwayFromZero) & "/" & GameLength)
End If
' ...
Loop Until GameOver Or MoveCount = GameLength
If GameOver = False Then
Console.WriteLine("Maximum moves reached.")
Dim BlackCount As Integer = 0
Dim WhiteCount As Integer = 0
' Nested for loop to check the whole board and count pieces
For i As Integer = 1 To BoardDimension
For j As Integer = 1 To BoardDimension
If Board(i, j)(0) = "B" Then
BlackCount = BlackCount + 1
ElseIf Board(i, j)(0) = "W" Then
WhiteCount = WhiteCount + 1
End If
Next
Next
If BlackCount > WhiteCount Then
Console.WriteLine("Black wins! (B " & BlackCount & ":" & WhiteCount & " W)")
ElseIf WhiteCount > BlackCount Then
Console.WriteLine("White wins! (B " & BlackCount & ":" & WhiteCount & " W)")
Else
Console.WriteLine("Draw! (B " & BlackCount & ":" & WhiteCount & " W)")
End If
End If
Console.Write("Do you want to play again (enter Y for Yes)? ")
' ...
Loop Until PlayAgain <> "Y"
End Sub
' (Viktor I - Highcliffe Sixth)
VB.Net solution alternative
Answer:
' this solution doesnt count the moves of each individual player, but of both of the players,
Dim MoveCounter As Integer
Dim MoveLimit As Integer
MoveLimit = 50 ' change this number to allow more or less moves
MoveCounter = 0 ' set this to anyother number to start at a higher number of moves e.g start at 10 moves rather than 1
PlayAgain = "Y"
Do
WhoseTurn = "W"
GameOver = False
Console.Write("Do you want to play the sample game (enter Y for Yes)? ")
SampleGame = Console.ReadLine
If Asc(SampleGame) >= 97 And Asc(SampleGame) <= 122 Then
SampleGame = Chr(Asc(SampleGame) - 32)
End If
InitialiseBoard(Board, SampleGame)
Do
DisplayBoard(Board)
DisplayWhoseTurnItIs(WhoseTurn)
MoveIsLegal = False
Do
GetMove(StartSquare, FinishSquare)
StartRank = StartSquare Mod 10
StartFile = StartSquare \ 10
FinishRank = FinishSquare Mod 10
FinishFile = FinishSquare \ 10
MoveIsLegal = CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
If Not MoveIsLegal Then
Console.WriteLine("That is not a legal move - please try again")
End If
Loop Until MoveIsLegal
If MoveIsLegal Then
MoveCounter = MoveCounter + 1
Console.WriteLine("Total number of moves made is " & MoveCounter)
End If
.
.
.
Do loop until Gameover or MoveCounter = Movelimit
' from NewVIc Sixth form college
Python Solution
Answer:
#tracks moves with max. moves too
if __name__ == "__main__":
MaxMoveConf=input("Want to play with max moves: ")##confirm whether to use, beneficial later
if MaxMoveConf=="Y":
MaxMoves=int(input("Enter max number of moves: "))#gets max number of moves
Board = CreateBoard() #0th index not used
StartSquare = 0
FinishSquare = 0
PlayAgain = "Y"
WMoves = 0#counter for number of moves made
BMoves = 0
W = 0#counter for pieces left
B = 0
while PlayAgain == "Y":
WhoseTurn = "W"
GameOver = False
SampleGame = input("Do you want to play the sample game (enter Y for Yes)? ")
if ord(SampleGame) >= 97 and ord(SampleGame) <= 122:
SampleGame = chr(ord(SampleGame) - 32)
InitialiseBoard(Board, SampleGame)
while not(GameOver):
DisplayBoard(Board)
DisplayWhoseTurnItIs(WhoseTurn)
if WhoseTurn=="W":#if W turn, +1 to W counter
WMoves += 1
else: #if B turn, +1 to B counter
BMoves += 1
MoveIsLegal = False
while not(MoveIsLegal):
StartSquare, FinishSquare = GetMove(StartSquare, FinishSquare)
StartRank = StartSquare % 10
StartFile = StartSquare // 10
FinishRank = FinishSquare % 10
FinishFile = FinishSquare // 10
MoveIsLegal = CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
if not(MoveIsLegal):
print("That is not a legal move - please try again")
GameOver = CheckIfGameWillBeWon(Board, FinishRank, FinishFile)
MakeMove(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
print(WMoves, " moves made by Whites. ", BMoves, " moves made by Blacks.")#display no. of moves
if WMoves>=MaxMoves or BMoves>=MaxMoves:#if either exceeds max moves
for Rank in range(1, BOARDDIMENSION+1):#counts number of pieces left on board
for File in range(1, BOARDDIMENSION+1):
if Board[Rank][File][0]=="W":#distinguishes colour
W+=1
elif Board[Rank][File][0]=="B":
B+=1
if B>W:#if more B pieces than W, B wins
print("Blacks win")
elif W>B:#if more W pieces than B, W wins
print("Whites win")
else:#if any other circumstance, DRAW
print("Draw")
GameOver=True #makes GameOver true so procedure to end game carried out
if GameOver and MaxMoveConf!="Y": #user has choice to play with max moves or not
DisplayWinner(WhoseTurn) #if doesnt use max moves, sarrum capture still determines winner
if WhoseTurn == "W":
WhoseTurn = "B"
else:
WhoseTurn = "W"
PlayAgain = input("Do you want to play again (enter Y for Yes)? ")
if ord(PlayAgain) >= 97 and ord(PlayAgain) <= 122:
PlayAgain = chr(ord(PlayAgain) - 32)
#By Hussain Syed, ICHS
----------------------------------------------------------------------------------------------------------
#If you just want to track the White, Black and Overall moves without a piece limit - follow the code below.
#The changes are within the (#)'s, This code is derived from Hussain Syed ICHS, just simplified it to track number of moves alone
if __name__ == "__main__":
Board = CreateBoard() #0th index not used
StartSquare = 0
FinishSquare = 0
PlayAgain = "Y"
#############################################################################################################
TotalMoves = 0 #Each variable is assigned to 0 to start of with, Total Moves, White Moves, Black Moves
WMoves = 0
BMoves = 0
while PlayAgain == "Y":
WhoseTurn = "W"
GameOver = False
SampleGame = GetTypeOfGame()
InitialiseBoard(Board, SampleGame)
while not(GameOver):
DisplayBoard(Board)
DisplayWhoseTurnItIs(WhoseTurn)
#Display No. of Moves of each colour and the overall moves, has to be within this loop in order to display -
#it just before the next player enters their coordinates
print(WMoves,"move(s) made by White.", BMoves,"move(s) made by Black.", TotalMoves,"move(s) made overall.")
if WhoseTurn=="W":#If W turn, +1 to W counter
WMoves = WMoves+1
else: #If B turn, +1 to B counter
BMoves = BMoves+1
TotalMoves = WMoves + BMoves #TotalMoves overall, Add them both together
#This is printed above this section of the code to -
#display it before the player enters the coordinates
############################################################################################################
MoveIsLegal = False
while not(MoveIsLegal):
StartSquare, FinishSquare = GetMove(StartSquare, FinishSquare)
StartRank = StartSquare % 10
StartFile = StartSquare // 10
FinishRank = FinishSquare % 10
FinishFile = FinishSquare // 10
MoveIsLegal = CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
if not(MoveIsLegal):
print("That is not a legal move - please try again")
GameOver = CheckIfGameWillBeWon(Board, FinishRank, FinishFile)
MakeMove(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
if GameOver:
DisplayWinner(WhoseTurn)
if WhoseTurn == "W":
WhoseTurn = "B"
else:
WhoseTurn = "W"
PlayAgain = input("Do you want to play again (enter Y for Yes)? ").upper()
Java Solution
Answer:
void displayNumberOfMoves(char whoseTurn) {
if (whoseTurn == 'W') ++noOfWhiteMoves;
else if (whoseTurn == 'B') ++noOfBlackMoves;
System.out.println("\n*Number of moves made by White: " + noOfWhiteMoves +'*');
System.out.println("*Number of moves made by Black: " + noOfBlackMoves + '*');
}
Pascal Solution
Answer:
SET TWO GLOBAL VARIABLES 'BMOVES' AND 'WMOVES' AS 'INTEGER'
SET THEIR INITIAL VALUE TO 0
AFTER A MOVE IS MADE:
MakeMove(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn);
If WhoseTurn = 'B'
Then BMoves := BMoves + 1
Else WMoves := Wmoves + 1;
If GameOver
INSIDE THE 'DISPLAYWINNER' PROCEDURE:
If WhoseTurn = 'W'
Then Writeln('Black''s Sarrum has been captured. White wins in ',WMoves,' moves!')
Else Writeln('White''s Sarrum has been captured. Black wins in ',BMoves,' moves!');
C# Solution
Answer:
//Create the variables above static main void
static int BlackMoves = 0;
static int WhiteMoves = 0;
public static Boolean CheckMoveIsLegal(string[,] Board, int StartRank, int StartFile, int FinishRank, int FinishFile, char WhoseTurn)
{
char PieceType;
char PieceColour;
Boolean MoveIsLegal = true;
if ((FinishFile == StartFile) && (FinishRank == StartRank))
MoveIsLegal = false;
PieceType = Board[StartRank, StartFile][1];
PieceColour = Board[StartRank, StartFile][0];
if (WhoseTurn == 'W')
{
if (PieceColour != 'W')
MoveIsLegal = false;
if (Board[FinishRank, FinishFile][0] == 'W')
MoveIsLegal = false;
}
else
{
if (PieceColour != 'B')
MoveIsLegal = false;
if (Board[FinishRank, FinishFile][0] == 'B')
MoveIsLegal = false;
}
if (MoveIsLegal)
switch (PieceType)
{
case 'R':
MoveIsLegal = CheckRedumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, PieceColour);
break;
case 'S':
MoveIsLegal = CheckSarrumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
case 'M':
MoveIsLegal = CheckMarzazPaniMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
case 'G':
MoveIsLegal = CheckGisgigirMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
case 'N':
MoveIsLegal = CheckNabuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
case 'E':
MoveIsLegal = CheckEtluMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
default:
MoveIsLegal = false;
break;
}
//This is the new code
if (WhoseTurn == 'B' && MoveIsLegal == true)
{
BlackMoves++;
}
else if (WhoseTurn == 'W' && MoveIsLegal == true)
{
WhiteMoves++;
}
return MoveIsLegal;
//Output it here
public static void DisplayWhoseTurnItIs(char WhoseTurn)
{
if (WhoseTurn == 'W')
Console.WriteLine("It is White's turn" + Environment.NewLine + "White moves are " + WhiteMoves);
else
Console.WriteLine("It is Black's turn" + Environment.NewLine + "Black moves are " + BlackMoves);
Console.WriteLine("White's score is " + WhiteScore);
Console.WriteLine("Black's score is " + BlackScore);
}
//UTC Reading
VB6.0 Solution
Answer:
Allow the player to save the game
[edit | edit source]This is not a short game, so allow a player to save the game by saving the board array and which play goes first.
VB.Net solution
Answer:
Imports System.Text 'Make sure you add this at the top! ~ Edd Norton, Ashville College
'Also, Make sure to add a call function somewhere in the GetMove subroutine
Sub SaveGame(ByVal Board(,) As String, ByVal whoseTurn As Char)
Dim sb As New StringBuilder
For i = 1 To BoardDimension
For j = 1 To BoardDimension
sb.AppendFormat("{0},{1},{2}{3}", i, j, Board(i, j), Environment.NewLine)
Next
Next
IO.File.WriteAllText("game.txt", sb.ToString())
IO.File.WriteAllText("turn.txt", whosTurn)
End Sub
Sub LoadGame(ByRef Board(,) As String, ByRef whoseTurn As Char)
whoseTurn = IO.File.ReadAllText("turn.txt")
Dim lines() As String = IO.File.ReadAllLines("game.txt")
For Each line As String In lines
Dim index() As String = line.Split(",") 'e.g. 5,4,BG
Board(index(0), index(1)) = index(2) 'BG
Next
'Insert breakpoints & debug to understand what this code does
End Sub
' ****''Didn't really understand that so I made my own. Also I used what is taught in the 'Nelson Thornes' textbook.'' ****
' *Note: Change the FileName text to the file you want to save it to (eg. C:\Users\Owner\Desktop\John\test.txt) which is mine. *
Imports System.IO ' Add this at the very top, where you'll find Import System.Math
Sub Main()
Dim Board(BoardDimension, BoardDimension) As String
' ...
' After list of declerations add two more:
Dim GameSave As Char
Dim GameLoad As Char
PlayAgain = "Y"
Do
WhoseTurn = "W"
GameOver = False
Console.Write("Would you like to load your last game (enter Y for Yes?) ")
GameLoad = UCase(Console.ReadLine)
If GameLoad = "Y" Then
LoadGame(Board, WhoseTurn)
Else
Console.Write("Do you want to play the sample game (enter Y for Yes)? ")
SampleGame = Console.ReadLine
If Asc(SampleGame) >= 97 And Asc(SampleGame) <= 122 Then
SampleGame = Chr(Asc(SampleGame) - 32)
End If
InitialiseBoard(Board, SampleGame)
End If
Do
DisplayBoard(Board)
Console.Write("Would you like to save the game (enter Y for Yes)?: ")
GameSave = UCase(Console.ReadLine)
If GameSave = "Y" Then
SaveGame(Board, WhoseTurn)
End If
DisplayWhoseTurnItIs(WhoseTurn)
MoveIsLegal = False
' All of this code goes above the last Do Loop (which gets the users move).
' Then add the two Sub Routines wherever you want: (I added mine directly underneath the SubMain())
Sub SaveGame(ByVal Board(,) As String, ByVal WhoseTurn As Char)
Dim CurrentFileWriter As StreamWriter
Dim FileName As String
FileName = "C:\Users\Owner\Desktop\John\test.txt"
CurrentFileWriter = New StreamWriter(FileName)
CurrentFileWriter.WriteLine(WhoseTurn)
For RankNo = 1 To BoardDimension
For FileNo = 1 To BoardDimension
CurrentFileWriter.WriteLine(Board(RankNo, FileNo))
Next
Next
CurrentFileWriter.Close()
Console.WriteLine("Your game has been saved!")
End Sub
Sub LoadGame(ByRef Board(,) As String, ByRef WhoseTurn As Char)
Dim CurrentFileReader As StreamReader
Dim FileName As String
FileName = "C:\Users\Owner\Desktop\John\test.txt"
CurrentFileReader = New StreamReader(FileName)
WhoseTurn = CurrentFileReader.ReadLine()
For RankNo = 1 To BoardDimension
For FileNo = 1 To BoardDimension
Board(RankNo, FileNo) = CurrentFileReader.ReadLine()
Next
Next
CurrentFileReader.Close()
End Sub
Python Solution
Answer:
<!-- the method to save using csv file has been added at the bottom-->
#Added in saving turn
import json #Imports json to the program.
def SaveGame(Board, WhoseTurn):
file = open('Board.txt', 'w') #Opens file in write mode
data = json.dumps(Board) # data = structured board
file.write(data + '\n') #Writes board to first line
file.write(WhoseTurn) #Writes turn to second line
file.close()
def LoadBoard():
file = open("Board.txt", "r") #Opens the file in read mode
Board = file.readline() #Reads the first line
return json.loads(Board) #Structures it
def LoadTurn():
file = open("Board.txt", "r") #Opens the file in read mode
WhoseTurn = file.readline(1) #Reads the second line
return WhoseTurn #Return the turn
if __name__ == "__main__":
Board = CreateBoard() #0th index not used
StartSquare = 0
FinishSquare = 0
PlayAgain = "Y"
while PlayAgain == "Y":
WhoseTurn = "W"
GameOver = False
LoadChoice = input("Do you want to load the previous game? (enter L)")
if LoadChoice.upper()== "L": #Ask if wants to load game
Board = LoadBoard()
WhoseTurn = LoadTurn()
else:
SampleGame = input("Do you want to play the sample game (enter Y for Yes)? ")
if ord(SampleGame) >= 97 and ord(SampleGame) <= 122:
SampleGame = chr(ord(SampleGame) - 32)
InitialiseBoard(Board, SampleGame)
while not(GameOver):
DisplayBoard(Board)
DisplayWhoseTurnItIs(WhoseTurn)
MoveIsLegal = False
while not(MoveIsLegal):
StartSquare, FinishSquare = GetMove(StartSquare, FinishSquare)
StartRank = StartSquare % 10
StartFile = StartSquare // 10
FinishRank = FinishSquare % 10
FinishFile = FinishSquare // 10
MoveIsLegal = CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
if not(MoveIsLegal):
print("That is not a legal move - please try again")
GameOver = CheckIfGameWillBeWon(Board, FinishRank, FinishFile)
MakeMove(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
SaveGame(Board, WhoseTurn)
if GameOver:
DisplayWinner(WhoseTurn)
if WhoseTurn == "W":
WhoseTurn = "B"
else:
WhoseTurn = "W"
PlayAgain = input("Do you want to play again (enter Y for Yes)? ")
if ord(PlayAgain) >= 97 and ord(PlayAgain) <= 122:
PlayAgain = chr(ord(PlayAgain) - 32)
------------------------------------------------------------------------------------
Here is how to do it using csv, this is done using procedure called SaveBoard() and LoadBoard()
def SaveBoard(Board):
filename = "csvfile.csv"
file = open(filename, "w")
for line in Board:
csvline = ", ".join(line)
file.write(csvline + "\n")
file.close()
def LoadBoard(Board):
filename = "csvfile.csv"
file = open(filename, "r")
num = 0
for csvlines in file:
lines = csvlines.rstrip('\n') ## this removes the character "\n"
lines = lines.split(", ")
Board[num] = lines
num = num + 1
by Dulan
-------------------- Another way of saving to csv file----------------------
def SaveGame(Board):
csvfile = open("savefile.csv","w")
for RankCount in range(1,BOARDDIMENSION+1):
for FileCount in range(1,BOARDDIMENSION+1):
csvfile.write(Board[RankCount][FileCount]+',')
csvfile.write("\n")
csvfile.close()
print("Game Saved")
def LoadGame(Board):
csvfile = open("savefile.csv", "r").readlines()
currentLine = 0
for RankCount in range(1,BOARDDIMENSION+1):
for FileCount in range(1,BOARDDIMENSION+1):
Board[RankCount][FileCount] = csvfile[currentLine][:2]
currentLine += 1
print(Board)
Aidan.D
Java Solution
Answer:
// save game
do {
displayBoard(board);
displayWhoseTurnItIs(whoseTurn);
moveIsLegal = false;
do {
char saveGme = console.readChar("Would you like to save the game? ");
if(saveGme == 'Y' || saveGme == 'y'){
write.openFile("saveData.txt", false);
console.println(whoseTurn);
write.writeToTextFile(String.valueOf(whoseTurn));
write.closeFile();
write.openFile("gameData.txt",false);
for(int x = 1; x<=BOARD_DIMENSION;x++){
for(int y = 1; y<=BOARD_DIMENSION;y++){
if(board[x][y].charAt(0) == 'B' || board[x][y].charAt(0) == 'W'){
write.writeToTextFile(board[x][y]);
String x1 = String.valueOf(x);
String y1 = String.valueOf(y);
write.writeToTextFile(x1+y1);
}
}
}
write.closeFile();
//this goes around line 110
//load game
void initialiseBoard(String[][] board, char sampleGame, char whoseTurn) {
int rankNo;
int fileNo;
if (sampleGame == 'Y') {
for (rankNo = 1; rankNo <= BOARD_DIMENSION; rankNo++) {
for (fileNo = 1; fileNo <= BOARD_DIMENSION; fileNo++) {
board[rankNo][fileNo] = " ";
}
}
board[1][2] = "BG";
board[1][4] = "BS";
board[1][8] = "WG";
board[2][1] = "WR";
board[3][1] = "WS";
board[3][2] = "BE";
board[3][8] = "BE";
board[6][8] = "BR";
}
else if(sampleGame == 'L' || sampleGame == 'l'){
for (rankNo = 1; rankNo <= BOARD_DIMENSION; rankNo++) {
for (fileNo = 1; fileNo <= BOARD_DIMENSION; fileNo++) {
board[rankNo][fileNo] = " ";
}
}
read.openTextFile("gameData.txt");
String x = read.readLine();
while(x!=null){
String y = read.readLine();
int y1 = Integer.parseInt(String.valueOf(y.charAt(0)));
int y2 = Integer.parseInt(String.valueOf(y.charAt(1)));
board[y1][y2] = x;
x = read.readLine();
}
}
// to load whoseTurn
initialiseBoard(board, sampleGame, whoseTurn);
if(sampleGame == 'L' || sampleGame == 'l'){
read.openTextFile("saveData.txt");
whoseTurn = read.readChar();
read.closeFile();
//this goes around line 102
//Alternative Solution for save game:
}
public void save_game(String[][] board, char whoseturn) { //this is all new
AQAWriteTextFile2015 currentfile;
currentfile = new AQAWriteTextFile2015(); //and this
currentfile.openFile("Game.txt",false);
int x, y;
currentfile.writeToTextFile(String.valueOf(whoseturn));
for (x = 1; x <= 8; x++) {
for (y = 1; y <= 8; y++) {
console.println(board[x][y]);
currentfile.writeToTextFile(board[x][y],"\r\n");
}
}
currentfile.closeFile();
}
Pascal Solution
Answer:
Procedure SaveBoard(Var Board : TBoard);
var
fptr:text;
i,j:integer;
save:char;
begin
Write('Do you want a save a game? (Enter Y for yes)');
Readln(save);
If (Ord(save) >= 97) and (Ord(save) <= 122)
Then save := Chr(Ord(save) - 32);
if save='Y' then
begin
assign(fptr,'SBoard.txt');
reset(fptr);
rewrite(fptr);
for i := 1 to 8 do
begin
for j := 1 to 8 do
begin
if j=8 then
writeln(fptr,Board[i,j])
else
begin
write(fptr,Board[i,j]);
write(fptr,',')
end
end;
end;
close(fptr);
end;
end;
Procedure LoadBoard(Var Board : Tboard);
var
fptr:text;
i,j,x,check:integer;
line:string;
load:char;
begin
Write('Do you want a load a game? (Enter Y for yes)');
Readln(load);
If (Ord(load) >= 97) and (Ord(load) <= 122)
Then load := Chr(Ord(load) - 32);
if load='Y' then
begin
assign(fptr,'SBoard.txt');
reset(fptr);
i:=1;
repeat
readln(fptr,line);
j:=1;
x:=1;
repeat
begin
if (line[x]<>',') and (line[x+1]<>',') then
begin
Board[i,j][1]:=line[x];
Board[i,j][2]:=line[x+1];
end;
if line [x]=','then
j:=j+1;
x:=x+1;
end;
until j=9;
i:=i+1;
until i=9;
close(fptr);
end;
end;
//You need to put the Save board procedure after the make move procedure
//Also make sure to call the procedure 'LoadBoard' in the main program after 'InitialiseBoard(Board, SampleGame);' piece of code.
//I updated it because it wasn't loading the last column. It now runs through the whole array and includes column 8.
//Additionally, Why have 2 text files one for load and one for save? Just make it save the previous game into 1 text file! Also added/fixed (as it was saving into SBoard and the load procedure was loading Lboard...)
//Lastly, it will crash if nothing is in the text file, so before testing the loading out, make sure you play the game once and have saved it (so something is in the text file)- Then try and load it!
//updated and fixed
C# Solution
Answer:
public void SaveGame(string[,] Board, char whosTurn)
{
var sb = new StringBuilder();
for (i = 1; i <= BoardDimension; i++)
for (j = 1; j <= BoardDimension; j++)
sb.AppendFormat("{0},{1},{2}\n", i, j, Board(i, j));
IO.File.WriteAllText("game.txt", sb.ToString());
IO.File.WriteAllText("turn.txt", whosTurn);
}
public void LoadGame(ref string[,] Board, ref char whosTurn)
{
whosTurn = Char.Parse(IO.File.ReadAllText("turn.txt"));
string[] lines = IO.File.ReadAllLines("game.txt");
foreach (string line in lines)
{
string[] index = line.Split(','); //e.g. 5,4,BG
Board(index[0], index[1]) = index[2];
}
//Insert breakpoints & debug to understand what this code does
}
OR alternative answer
using System.IO; // add this at the top
static void Main(string[] args)
{
//...
do
{
WhoseTurn = 'W';
GameOver = false;
Console.Write("Do you want to play the sample game (enter Y for Yes or X for Saved game)? ");
SampleGame = char.Parse(Console.ReadLine());
if ((int)SampleGame >= 97 && (int)SampleGame <= 122)
SampleGame = (char)((int)SampleGame - 32);
if (SampleGame == 'X') // new stuff
{
loadGame(ref Board, ref WhoseTurn);
}
else
{
InitialiseBoard(ref Board, SampleGame);
}
do
{
/...
do
{
//...
} while (!MoveIsLegal);
/...
saveGame(Board, WhoseTurn, ref GameOver ); // code added here
} while (!GameOver);
//...
} while (PlayAgain == 'Y');
}
private static void loadGame(ref string[,] Board, ref char WhoseTurn)
{
StreamReader gameFile = new StreamReader("gameFile.txt");
int RankNo = 0, FileNo = 0;
WhoseTurn = char.Parse(gameFile.ReadLine());
for (RankNo = 1; RankNo <= BoardDimension; RankNo++)
for (FileNo = 1; FileNo <= BoardDimension; FileNo++)
Board[RankNo, FileNo] = gameFile.ReadLine();
gameFile.Close();
DisplayBoard(Board);
}
private static void saveGame(string[,] Board, char WhoseTurn, ref bool GameOver)
{
string ans = "";
int RankNo = 0, FileNo = 0;
StreamWriter gameFile = new StreamWriter("gameFile.txt");
Console.WriteLine("Do you want to save and exit the Game?");
ans = Console.ReadLine();
if (ans.ToUpper() == "Y")
{
GameOver = true;
gameFile.WriteLine(WhoseTurn );
for (RankNo = 1; RankNo <= BoardDimension; RankNo++)
for (FileNo = 1; FileNo <= BoardDimension; FileNo++)
gameFile.WriteLine(Board[RankNo, FileNo]);
}
gameFile.Close() ;
}
{{CPTAnswerTabEnd}}
VB6.0 Solution
{{CPTAnswerTab}}
<syntaxhighlight lang="vb">
Prevent program from crashing, when entering incorrect coordinates
[edit | edit source]There are 2 coordinates to enter. If the first is entered incorrectly, you can still enter the second and then it crashes. Fix this.
VB.Net solution
Answer:
Sub GetMove(ByRef StartSquare As Integer, ByRef FinishSquare As Integer, ByVal Board As Array, ByVal WhoseTurn As Char)
Dim LegalMoveCount As Integer = 0
Dim StartRank
Dim StartFile
'This solution assumes that an integer is being entered, if a non-integer is entered it will still crash due to
'A first chance exception of type "System.InvalidCastException"
Do
Console.Write("Enter coordinates of square containing piece to move (file first): ")
StartSquare = Console.ReadLine
StartRank = StartSquare Mod 10
StartFile = StartSquare \ 10
Loop Until (StartRank > 0 And StartRank < 9) And (StartFile > 0 And StartFile < 9)
'...
End Sub
'**********************************************************Another solution is shown below****************************************************************
'A new function is created to validate the inputs
Function Validate(ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer) As Boolean
Dim IsValid As Boolean
ValidateRankAndFile = True
If StartRank < 1 Or StartRank > BoardDimension Then IsValid = False 'instead of BoardDimension you can substitute the number 8 into
If StartFile < 1 Or StartFile > BoardDimension Then IsValid = False 'e.g. If StartRank < 1 or StartRank >8 Then IsValid = False
If FinishRank < 1 Or FinishRank > BoardDimension Then IsValid = False
If FinishFile < 1 Or FinishFile > BoardDimension Then IsValid = False
Return IsValid
End Function
' This Function Validate is called in the SubMain()
Sub Main()
'.......
If Validate(StartRank, StartFile, FinishRank, FinishFile) Then
MoveIsLegal = CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
End If
'........
End Sub
'End of solution
******************************* Another solution (doesnt create any new subs) *******************************************
Function CheckMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer, ByVal WhoseTurn As Char) As Boolean
'........
If StartRank < 1 Or StartRank > BoardDimension Or
StartFile < 1 Or StartFile > BoardDimension Or
FinishRank < 1 Or FinishRank > BoardDimension Or
FinishFile < 1 Or FinishFile > BoardDimension Then
Console.WriteLine("You have used an incorrect coordinate!")
Return False
End If
'........
Python Solution
Answer:
def GetMove(StartSquare, FinishSquare):
while True:
StartSquare = int(input("Enter coordinates of square containing piece to move (file first): "))
if (StartSquare >= 11) and (StartSquare <= 88) and (StartSquare % 10 >= 1) and (StartSquare % 10 <= 8):
break
while True:
FinishSquare = int(input("Enter coordinates of square to move piece to (file first): "))
if (FinishSquare >= 11) and (FinishSquare <= 88) and (FinishSquare % 10 >= 1) and (FinishSquare % 10 <= 8):
break
return StartSquare, FinishSquare
Java Solution
Answer:
//Place in checkIfMoveIsLegal function
if ((startRank >8) || (startFile < 0) || (finishRank >8) || (finishRank < 0) ) {
System.out.println("\n**Incorrect co-ordinates entered.**\n");
moveIsLegal = false;
return moveIsLegal;
}
Nonso Makwe
__________________________________________________________________________________________________________________________
boolean checkMoveIsLegal(String[][] board, int startRank, int startFile, int finishRank, int finishFile, char whoseTurn) {
char pieceType;
char pieceColour;
boolean moveIsLegal = true;
if ((finishFile == startFile) && (finishRank == startRank)) {
moveIsLegal = false;
}
if (startRank < 1 || startFile < 1 || finishRank < 1 || finishFile < 1 || startRank > 8 || startFile > 8 || finishRank > 8 || finishFile > 8) {
//Here it checks if any entered coordinate is outside the range
console.println("\n***An incorrect coordinate has been entered, please try again***\n");
moveIsLegal = false;
} else {
//else the program continues with the original procedure
pieceType = board[startRank][startFile].charAt(1);
pieceColour = board[startRank][startFile].charAt(0);
if (whoseTurn == 'W') {
if (pieceColour != 'W') {
moveIsLegal = false;
}
if (board[finishRank][finishFile].charAt(0) == 'W') {
moveIsLegal = false;
}
} else {
if (pieceColour != 'B') {
moveIsLegal = false;
}
if (board[finishRank][finishFile].charAt(0) == 'B') {
moveIsLegal = false;
}
}
if (moveIsLegal) {
switch (pieceType) {
case 'R':
moveIsLegal = checkRedumMoveIsLegal(board, startRank, startFile, finishRank, finishFile, pieceColour);
break;
case 'S':
moveIsLegal = checkSarrumMoveIsLegal(board, startRank, startFile, finishRank, finishFile);
break;
case 'M':
moveIsLegal = checkMarzazPaniMoveIsLegal(board, startRank, startFile, finishRank, finishFile);
break;
case 'G':
moveIsLegal = checkGisgigirMoveIsLegal(board, startRank, startFile, finishRank, finishFile);
break;
case 'N':
moveIsLegal = checkNabuMoveIsLegal(board, startRank, startFile, finishRank, finishFile);
break;
case 'E':
moveIsLegal = checkEtluMoveIsLegal(board, startRank, startFile, finishRank, finishFile);
break;
default:
moveIsLegal = false;
break;
}
}
}
return moveIsLegal;
}
'Sanyan Rahman - SJC College
Pascal Solution
Answer:
Procedure GetMove(Var StartSquare, FinishSquare : Integer);
Begin
Write('Enter coordinates of square containing piece to move (file first): ');
Repeat
Readln(StartSquare);
Until
(StartSquare <=88) and (StartSquare >= 11) and
((StartSquare mod 10)<=8) And ((StartSquare mod 10)<>0);
Write('Enter coordinates of square to move piece to (file first): ');
Repeat
Readln(FinishSquare);
Until
(FinishSquare <=88) and (FinishSquare >= 11) and
((FinishSquare mod 10)<=8) And ((FinishSquare mod 10)<>0);
End;
OR
Function CheckMoveIsLegal(Var Board : TBoard; StartRank, StartFile, FinishRank, FinishFile : Integer;
WhoseTurn : Char) : Boolean;
Var
PieceType : Char;
PieceColour : Char;
MoveIsLegal : Boolean;
Begin
MoveIsLegal := True;
If (FinishFile = StartFile) And (FinishRank = StartRank)
Then MoveIsLegal := False
<big>'''Else if (FinishFile > 8) or (FinishFile < 1) or (FinishRank > 8) or (FinishRank < 1)'''
</big> then
MoveIsLegal := False
Else
Begin
PieceType := Board[StartRank, StartFile][2];
PieceColour := Board[StartRank, StartFile][1];
If WhoseTurn = 'W'
Then
Begin
If PieceColour <> 'W'
Then MoveIsLegal := False;
If Board[FinishRank, FinishFile][1] = 'W'
Then MoveIsLegal := False;
End
Else
Begin
If PieceColour <> 'B'
Then MoveIsLegal := False;
If Board[FinishRank, FinishFile][1] = 'B'
Then MoveIsLegal := False
End;
If MoveIsLegal = True
Then
Begin
Case PieceType Of
'R' : MoveIsLegal := CheckRedumMoveIsLegal(Board, StartRank, StartFile, FinishRank,
FinishFile, PieceColour);
'S' : MoveIsLegal := CheckSarrumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
'M' : MoveIsLegal := CheckMarzazPaniMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
'G' : MoveIsLegal := CheckGisgigirMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
'N' : MoveIsLegal := CheckNabuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
'E' : MoveIsLegal := CheckEtluMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
End;
End;
End;
CheckMoveIsLegal := MoveIsLegal;
End;
or can use this code which will check to make sure something entered, that it is a number, and that both digits in the number are valid
Valid:=False;
Write('Enter coordinates of square containing piece to move (file first): ');
//Readln(StartSquare);
readln(Temp1);
Write('Enter coordinates of square to move piece to (file first): ');
//Readln(FinishSquare);
readln(Temp2);
//If two characters in each temp number are between 1 and the Board Dimension
if(temp1<>'') and (temp2<>'')
and(temp1[1]>'0') and (temp1[1]<=inttostr(BoardDimension))
and (temp1[2]>'0') and (temp1[2]<=inttostr(BoardDimension))
and (temp2[1]>'0') and (temp2[1]<=inttostr(BoardDimension))
and (temp2[2]>'0') and (temp2[2]<=inttostr(BoardDimension))then
begin
//then convert the temp numbers to integers
StartSquare:=strtoint(Temp1);
FinishSquare:=strToInt(Temp2);
//set valid to be true
Valid:=True;
end
else
writeln('Must enter something, cannot use characters and zeros are invalid coordinates');
until valid=true;
end;
C# Solution
Answer:
public static Boolean CheckMoveIsLegal(string[,] Board, int StartRank, int StartFile, int FinishRank, int FinishFile, char WhoseTurn)
{
char PieceType;
char PieceColour;
Boolean MoveIsLegal = true;
if (StartRank < 1 || StartRank > 8 || StartFile < 1 || StartFile > 8 ||
FinishRank < 1 || FinishRank > 8 || FinishFile < 1 || FinishRank > 8 )
{
MoveIsLegal = false;
return MoveIsLegal;
}
// ......
}
OR can change getMove
public static void GetMove(ref int StartSquare, ref int FinishSquare)
{
do
{
Console.Write("Enter cooordinates of square containing piece to move (file first): ");
StartSquare = int.Parse(Console.ReadLine());
} while (StartSquare % 10 < 1 || StartSquare % 10 > 8 || StartSquare / 10 < 1 || StartSquare / 10 > 8);
do
{
Console.Write("Enter cooordinates of square to move piece to (file first): ");
FinishSquare = int.Parse(Console.ReadLine());
} while (FinishSquare % 10 < 1 || FinishSquare % 10 > 8 || FinishSquare / 10 < 1 || FinishSquare / 10 > 8);
}
VB6.0 Solution
Answer:
thunderthighs
Add a new piece to the game: Kashshaptu
[edit | edit source]Add the Kashshaptu to the game, the Kashshaptu can move in any direction, any number of spaces, but cannot jump. Replace the Marzaz Pani with this piece.
VB.Net solution
Answer:
'code courtesy of John Chamberlain
Function CheckKashshaptuMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer) As Boolean
Dim KashshaptuMoveIsLegal As Boolean = False
Dim Count As Integer
Dim RankDifference As Integer
Dim FileDifference As Integer
RankDifference = FinishRank - StartRank ' Negative if moving Bottom to Top.
FileDifference = FinishFile - StartFile ' Negative if moving Right to Left.
' Much the same as Checking Gisgigir Move.
If RankDifference = 0 Then ' Moving Horizontally.
If FileDifference >= 1 Then ' Moving Left to Right.
KashshaptuMoveIsLegal = True
For Count = 1 To FileDifference - 1 Step 1
Debug.WriteLine(Board(StartRank, StartFile + Count))
If Board(StartRank, StartFile + Count) <> " " Then
KashshaptuMoveIsLegal = False ' There is something in our path so move is not legal.
End If
Next
ElseIf FileDifference <= -1 Then ' Moving Right to Left.
KashshaptuMoveIsLegal = True
For Count = -1 To FileDifference + 1 Step -1
If Board(StartRank, StartFile + Count) <> " " Then
KashshaptuMoveIsLegal = False
End If
Next
End If
ElseIf FileDifference = 0 Then ' Moving Vertically
If RankDifference >= 1 Then ' Moving Top to Bottom.
KashshaptuMoveIsLegal = True
For Count = 1 To RankDifference - 1 Step 1
If Board(StartRank + Count, StartFile) <> " " Then
KashshaptuMoveIsLegal = False
End If
Next
ElseIf RankDifference <= -1 Then ' Moving Bottom to Top.
KashshaptuMoveIsLegal = True
For Count = -1 To RankDifference + 1 Step -1
If Board(StartRank + Count, StartFile) <> " " Then
KashshaptuMoveIsLegal = False
End If
Next
End If
ElseIf Abs(RankDifference) = Abs(FileDifference) Then ' Moving Diagonally.
KashshaptuMoveIsLegal = True
Dim RankChange As Integer
Dim FileChange As Integer
If RankDifference >= 1 Then
RankChange = 1
Else
RankChange = -1
End If
If FileDifference >= 1 Then
FileChange = 1
Else
FileChange = -1
End If
For Count = 1 To RankDifference Step 1
If Board(StartRank + (Count * RankChange), StartFile + (Count * FileChange)) <> " " Then
KashshaptuMoveIsLegal = False
End If
Next
End If
Return KashshaptuMoveIsLegal
End Function
Function CheckMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer, ByVal WhoseTurn As Char) As Boolean
' ...
Select Case PieceType
' ...
Case "K" ' Kashshaptu
Return CheckKashshaptuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
Case Else
Return False
End Select
End Function
Sub InitialiseBoard(ByRef Board(,) As String, ByVal SampleGame As Char)
' ...
Case 4
Board(RankNo, FileNo) = Board(RankNo, FileNo) & "K" 'to replace the Marzaz pani
' ...
End Sub
Python Solution
Answer:
def CheckKashaptuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile):
#Assuming the Kashaptu can move identically to the queen in chess
KashaptuMoveIsLegal = False
RankDifference = FinishRank - StartRank
FileDifference = FinishFile - StartFile
if abs(RankDifference) == abs(FileDifference):
KashaptuMoveIsLegal = True
elif RankDifference == 0:
if FileDifference >= 1:
KashaptuMoveIsLegal = True
for Count in range(1, FileDifference):
if Board[StartRank][StartFile + Count] != " ":
KashaptuMoveIsLegal = False
elif FileDifference <= -1:
KashaptuMoveIsLegal = True
for Count in range(-1, FileDifference, -1):
if Board[StartRank][StartFile + Count] != " ":
KashaptuMoveIsLegal = False
elif FileDifference == 0:
if RankDifference >= 1:
KashaptuMoveIsLegal = True
for Count in range(1, RankDifference):
if Board[StartRank + Count][StartFile] != " ":
KashaptuMoveIsLegal = False
elif RankDifference <= -1:
KashaptuMoveIsLegal = True
for Count in range(-1, RankDifference, -1):
if Board[StartRank + Count][StartFile] != " ":
KashaptuMoveIsLegal = False
return KashaptuMoveIsLegal
def CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn):
MoveIsLegal = True
if (FinishFile == StartFile) and (FinishRank == StartRank):
MoveIsLegal = False
else:
PieceType = Board[StartRank][StartFile][1]
PieceColour = Board[StartRank][StartFile][0]
if WhoseTurn == "W":
if PieceColour != "W":
MoveIsLegal = False
if Board[FinishRank][FinishFile][0] == "W":
MoveIsLegal = False
else:
if PieceColour != "B":
MoveIsLegal = False
if Board[FinishRank][FinishFile][0] == "B":
MoveIsLegal = False
if MoveIsLegal == True:
if PieceType == "R":
MoveIsLegal = CheckRedumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, PieceColour)
elif PieceType == "S":
MoveIsLegal = CheckSarrumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
elif PieceType == "M":
MoveIsLegal = CheckMarzazPaniMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
elif PieceType == "G":
MoveIsLegal = CheckGisgigirMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
elif PieceType == "N":
MoveIsLegal = CheckNabuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
elif PieceType == "E":
MoveIsLegal = CheckEtluMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
elif PieceType == "K":
MoveIsLegal = CheckKashaptuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
return MoveIsLegal
def InitialiseBoard(Board, SampleGame):
if SampleGame == "Y":
for RankNo in range(1, BOARDDIMENSION + 1):
for FileNo in range(1, BOARDDIMENSION + 1):
Board[RankNo][FileNo] = " "
Board[1][2] = "BG"
Board[1][4] = "BS"
Board[1][8] = "WG"
Board[2][1] = "WR"
Board[3][1] = "WS"
Board[3][2] = "BE"
Board[3][8] = "BE"
Board[6][8] = "BR"
else:
for RankNo in range(1, BOARDDIMENSION + 1):
for FileNo in range(1, BOARDDIMENSION + 1):
if RankNo == 2:
Board[RankNo][FileNo] = "BR"
elif RankNo == 7:
Board[RankNo][FileNo] = "WR"
elif RankNo == 1 or RankNo == 8:
if RankNo == 1:
Board[RankNo][FileNo] = "B"
if RankNo == 8:
Board[RankNo][FileNo] = "W"
if FileNo == 1 or FileNo == 8:
Board[RankNo][FileNo] = Board[RankNo][FileNo] + "G"
elif FileNo == 2 or FileNo == 7:
Board[RankNo][FileNo] = Board[RankNo][FileNo] + "E"
elif FileNo == 3 or FileNo == 6:
Board[RankNo][FileNo] = Board[RankNo][FileNo] + "N"
elif FileNo == 4:
Board[RankNo][FileNo] = Board[RankNo][FileNo] + "K"
#The Kashshaptu takes the place of the Marzaz Pani
elif FileNo == 5:
Board[RankNo][FileNo] = Board[RankNo][FileNo] + "S"
else:
Board[RankNo][FileNo] = " "
#Edited By Billy Barringer
#Big Up SE9
Java Solution
Answer:
boolean checkKashshaptuMoveIsLegal(String[][] board, int startRank,
int startFile, int finishRank, int finishFile) {
boolean kashshaptuMoveIsLegal;
int count;
int rankDifference = finishRank - startRank;
int fileDifference = finishFile - startFile;
int rankCoefficient = (int) signum(rankDifference);
int fileCoefficient = (int) signum(fileDifference);
int countDivider;
if (Math.abs(rankCoefficient) + Math.abs(fileCoefficient) == 2) {
countDivider = 2;
} else {
countDivider = 1;
}
int countMax = (((rankDifference * rankCoefficient) + (fileDifference * fileCoefficient)) / countDivider);
kashshaptuMoveIsLegal = true;
for (count = 1; count < countMax; count++) {
if (!board[startRank + (count * rankCoefficient)][startFile
+ (count * fileCoefficient)].equals(" ")) {
kashshaptuMoveIsLegal = false;
}
}
return kashshaptuMoveIsLegal;
}
Alex Drogemuller, Reading School - thanks to Ed "keen" Smart for the help
boolean checkKashshaptuMoveIsLegal(String[][] board, int startRank, int startFile, int finishRank, int finishFile){
boolean KashshaptuMoveIsLegal = false;
int Count = 0;
int RankDifference = 0;
int FileDifference = 0;
RankDifference = finishRank - startRank;
FileDifference = finishFile - startFile;
if (RankDifference == 0)
{
if (FileDifference >= 1)
{
KashshaptuMoveIsLegal = true;
for (Count = 1; Count < FileDifference; Count++)
{
console.println(board[startRank][startFile + Count]);
if ( ! board[startRank][startFile + Count].equals(" "))
{
KashshaptuMoveIsLegal = false;
}
}
}
else if (FileDifference <= -1)
{
KashshaptuMoveIsLegal = true;
for (Count = -1; Count > FileDifference; Count--)
{
if ( ! board[startRank][startFile + Count].equals(" "))
{
KashshaptuMoveIsLegal = false;
}
}
}
}
else if (FileDifference == 0)
{
if (RankDifference >= 1)
{
KashshaptuMoveIsLegal = true;
for (Count = 1; Count < RankDifference; Count++)
{
if ( ! board[startRank + Count][startFile].equals(" "))
{
KashshaptuMoveIsLegal = false;
}
}
}
else if (RankDifference <= -1)
{
KashshaptuMoveIsLegal = true;
for (Count = -1; Count > RankDifference; Count--)
{
if ( ! board[startRank + Count][startFile].equals(" "))
{
KashshaptuMoveIsLegal = false;
}
}
}
}
else if (abs(RankDifference) == abs(FileDifference))
{
KashshaptuMoveIsLegal = true;
int RankChange = 0;
int FileChange = 0;
if (RankDifference >= 1)
{
RankChange = 1;
}
else
{
RankChange = -1;
}
if (FileDifference >= 1)
{
FileChange = 1;
}
else
{
FileChange = -1;
}
for (Count = 1; Count <= RankDifference; Count++)
{
if ( ! board[startRank + (Count * RankChange)][startFile + (Count * FileChange)].equals(" "))
{
KashshaptuMoveIsLegal = false;
}
}
}
return KashshaptuMoveIsLegal;
}
Amy Rainbow, HGS
boolean checkKashshaptuMoveIsLegal(String[][] board, int startRank,
int startFile, int finishRank, int finishFile) {
boolean KashshaptuMoveIsLegal = false;
if (abs(finishFile - startFile) == abs(finishRank - startRank)) {
int sdFile = (int) signum(finishFile - startFile);
int sdRank = (int) signum(finishRank - startRank);
for (int i = 1; i < abs(startFile - finishFile); i++) {
int cFile = startFile + (sdFile * i);
int cRank = startRank + (sdRank * i);
if (board[cRank][cFile] != " ") {
return false;
}
}
KashshaptuMoveIsLegal = true;
} else if ((finishRank == startRank && finishFile != startFile)
|| (finishRank != startRank && finishFile == startFile)) {
int sdFile = (int) signum(finishFile - startFile);
int sdRank = (int) signum(finishRank - startRank);
if (sdFile == 0) {
for(int i = 1; i < abs(finishRank - startRank); i++) {
int cRank = startRank + (sdRank * i);
if (board[cRank][startFile] != " ") {
return false;
}
}
KashshaptuMoveIsLegal = true;
} else {
for(int i = 1; i < abs(finishFile - startFile); i++) {
int cFile = startFile + (sdFile * i);
if (board[startRank][cFile] != " ") {
return false;
}
}
KashshaptuMoveIsLegal = true;
}
}
return KashshaptuMoveIsLegal;
}
Essentially this was copied from the Nabu solution and then reused
to allow vertical and horizontal movement so credit goes to Zephyr 12
whoever they are.
Chris Drogemuller - Reading School
Pascal Solution
Answer:
Subroutines Created/Changed/Removed:
•CheckKashshaptuMoveIsLegal (Added)
•CheckMarzazPaniMoveIsLegal (Removed)
•CheckMoveIsLegal (Changed)
•InitialiseBoard (Changed)
•Main Code (Changed)
Code (Only Changed Subroutines and Main Program):
Var //Added Variables
MoveNo, MoveNo1 : Integer; //This adds the two variables to keep track of the turn number for both players
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//CHECKS IF THE KASHSHAPTU MOVE IS LEGAL
Function CheckKashshaptuMoveIsLegal(Var Board : TBoard; StartRank, StartFile, FinishRank, FinishFile : Integer) : Boolean; //This procedure was added by copying the Gisgigir
Var //procedure and changing the name, I also added a
KashshaptuMoveIsLegal : Boolean; //piece of code to support diagonal movement (below)
Count : Integer;
RankDifference : Integer;
FileDifference : Integer;
Begin
KashshaptuMoveIsLegal := False;
RankDifference := FinishRank - StartRank;
FileDifference := FinishFile - StartFile;
If ((WhoseTurn = 'W') AND (MoveNo >= 7)) OR ((WhoseTurn = 'B') AND (MoveNo1 >= 7)) THEN
begin
If RankDifference = 0
Then
Begin
If FileDifference >= 1
Then
Begin
KashshaptuMoveIsLegal := True;
For Count := 1 To FileDifference - 1
Do
Begin
If Board[StartRank, StartFile + Count] <> ' '
Then KashshaptuMoveIsLegal := False
End;
End
Else
Begin
If FileDifference <= -1
Then
Begin
KashshaptuMoveIsLegal := True;
For Count := -1 DownTo FileDifference + 1
Do
Begin
If Board[StartRank, StartFile + Count] <> ' '
Then KashshaptuMoveIsLegal := False
End;
End;
End;
End
ELSE If ((Abs(FinishFile - StartFile)) = (Abs(FinishRank - StartRank))) //This allows it to move diagonally, this was taken from the Nabu unit procedure and edited
Then //This makes sure that the value of squares moved across is the same as up/down. This means the unit
begin //can move diagonally.
KashshaptuMoveIsLegal := True;
end //
Else
Begin
If FileDifference = 0
Then
Begin
If RankDifference >= 1
Then
Begin
KashshaptuMoveIsLegal := True;
For Count := 1 To RankDifference - 1
Do
Begin
If Board[StartRank + Count, StartFile] <> ' '
Then KashshaptuMoveIsLegal := False
End;
End
Else
Begin
If RankDifference <= -1
Then
Begin
KashshaptuMoveIsLegal := True;
For Count := -1 DownTo RankDifference + 1
Do
Begin
If Board[StartRank + Count, StartFile] <> ' '
Then KashshaptuMoveIsLegal := False
End;
End;
End;
End;
End;
End;
CheckKashshaptuMoveIsLegal := KashshaptuMoveIsLegal;
End;
//END OF KASHSHAPTU
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Function CheckMoveIsLegal(Var Board : TBoard; StartRank, StartFile, FinishRank, FinishFile : Integer;
WhoseTurn : Char) : Boolean;
Var
PieceType : Char;
PieceColour : Char;
MoveIsLegal : Boolean;
Begin
MoveIsLegal := True;
If (FinishFile = StartFile) And (FinishRank = StartRank)
Then MoveIsLegal := False
Else
Begin
PieceType := Board[StartRank, StartFile][2];
PieceColour := Board[StartRank, StartFile][1];
If WhoseTurn = 'W'
Then
Begin
If PieceColour <> 'W'
Then MoveIsLegal := False;
If Board[FinishRank, FinishFile][1] = 'W'
Then MoveIsLegal := False;
End
Else
Begin
If PieceColour <> 'B'
Then MoveIsLegal := False;
If Board[FinishRank, FinishFile][1] = 'B'
Then MoveIsLegal := False
End;
If MoveIsLegal = True
Then
Begin
Case PieceType Of
'R' : MoveIsLegal := CheckRedumMoveIsLegal(Board, StartRank, StartFile, FinishRank,
FinishFile, PieceColour);
'S' : MoveIsLegal := CheckSarrumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
'K' : MoveIsLegal := CheckKashshaptuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile); //Changed to Kashshaptu
'G' : MoveIsLegal := CheckGisgigirMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
'N' : MoveIsLegal := CheckNabuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
'E' : MoveIsLegal := CheckEtluMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
End;
End;
End;
CheckMoveIsLegal := MoveIsLegal;
End;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Procedure InitialiseBoard(Var Board : TBoard; SampleGame : Char);
Var
RankNo : Integer;
FileNo : Integer;
Begin
If SampleGame = 'Y'
Then
Begin
For RankNo := 1 To BoardDimension
Do
For FileNo := 1 To BoardDimension
Do Board[RankNo, FileNo] := ' ';
Board[1, 2] := 'BG';
Board[1, 4] := 'BS';
Board[1, 8] := 'WG';
Board[2, 1] := 'WR';
Board[3, 1] := 'WS';
Board[3, 2] := 'BE';
Board[3, 8] := 'BE';
Board[6, 8] := 'BR';
End
Else
For RankNo := 1 To BoardDimension
Do
For FileNo := 1 To BoardDimension
Do
If RankNo = 2
Then Board[RankNo, FileNo] := 'BR'
Else
If RankNo = 7
Then Board[RankNo, FileNo] := 'WR'
Else
If (RankNo = 1) Or (RankNo = 8)
Then
Begin
If RankNo = 1
Then Board[RankNo, FileNo] := 'B';
If RankNo = 8
Then Board[RankNo, FileNo] := 'W';
Case FileNo Of
1, 8 : Board[RankNo, FileNo] := Board[RankNo, FileNo] + 'G';
2, 7 : Board[RankNo, FileNo] := Board[RankNo, FileNo] + 'E';
3, 6 : Board[RankNo, FileNo] := Board[RankNo, FileNo] + 'N';
4 : Board[RankNo, FileNo] := Board[RankNo, FileNo] + 'K'; //Changed Marzaz Pani to Kashshaptu
5 : Board[RankNo, FileNo] := Board[RankNo, FileNo] + 'S';
End;
End
Else Board[RankNo, FileNo] := ' '
End;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Begin
Randomize;
MoveNo:=0;
MoveNo1:=0;
PlayAgain := 'Y';
Repeat
RollDiceToStart;
GameOver := False;
GetTypeOfGame;
Repeat
DisplayBoard(Board);
DisplayWhoseTurnItIs(WhoseTurn);
MoveIsLegal := False;
IF WhoseTurn = 'W' THEN
begin
MoveNo:=MoveNo+1
end //TURN COUNTER//
ELSE IF WhoseTurn = 'B' THEN
begin
MoveNo1:=MoveNo1+1
end;
Repeat
GetMove(StartSquare, FinishSquare);
StartRank := StartSquare Mod 10;
StartFile := StartSquare Div 10;
FinishRank := FinishSquare Mod 10;
FinishFile := FinishSquare Div 10;
MoveIsLegal := CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn);
If Not MoveIsLegal
Then Writeln('That is not a legal move - please try again');
Until MoveIsLegal;
GameOver := CheckIfGameWillBeWon(Board, FinishRank, FinishFile);
MakeMove(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn);
If GameOver
Then DisplayWinner(WhoseTurn);
If WhoseTurn = 'W'
Then WhoseTurn := 'B'
Else WhoseTurn := 'W';
Until GameOver;
Write('Do you want to play again (enter Y for Yes)? ');
Readln(PlayAgain);
If (Ord(PlayAgain) >= 97) and (Ord(PlayAgain) <= 122)
Then PlayAgain := Chr(Ord(PlayAgain) - 32);
Until PlayAgain <> 'Y';
End.
C# Solution
Answer:
//George Boulton HGS Sixth Form
public static Boolean CheckKashshaptuMoveIsLegal(string[,] Board, int StartRank, int StartFile, int FinishRank, int FinishFile)
{
Boolean KashshaptuMoveIsLegal;
KashshaptuMoveIsLegal = false;
int RankDifference = FinishRank - StartRank;
int FileDifference = FinishFile - StartFile;
int Count;
if (RankDifference == 0)
{
if (FileDifference >= 1)
{
KashshaptuMoveIsLegal = true;
for (Count = 1; Count <= FileDifference - 1; Count++)
if (Board[StartRank, StartFile + Count] != " ")
KashshaptuMoveIsLegal = false;
}
else
if (FileDifference <= -1)
{
KashshaptuMoveIsLegal = true;
for (Count = -1; Count >= FileDifference + 1; Count--)
if (Board[StartRank, StartFile + Count] != " ")
KashshaptuMoveIsLegal = false;
}
}
else if (FileDifference == 0)
{
if (RankDifference >= 1)
{
KashshaptuMoveIsLegal = true;
for (Count = 1; Count <= RankDifference - 1; Count++)
{
if (Board[StartRank + Count, StartFile] != " ")
KashshaptuMoveIsLegal = false;
}
}
else
if (RankDifference <= -1)
{
KashshaptuMoveIsLegal = true;
for (Count = -1; Count >= RankDifference + 1; Count--)
if (Board[StartRank + Count, StartFile] != " ")
KashshaptuMoveIsLegal = false;
}
}
else if (Math.Abs(RankDifference) == Math.Abs(FileDifference))
{
KashshaptuMoveIsLegal = true;
if (RankDifference == FileDifference)
{
if (RankDifference > 0)
for (int i = 1; i <= RankDifference - 1; i++)
{
KashshaptuMoveIsLegal = true;
if (Board[StartRank + i, StartFile + i] != " ")
KashshaptuMoveIsLegal = false;
}
else
{
for (int i = -1; i >= RankDifference + 1; i--)
{
KashshaptuMoveIsLegal = true;
if (Board[StartRank + i, StartFile + i] != " ")
KashshaptuMoveIsLegal = false;
}
}
}
if (RankDifference == -FileDifference)
{
if (RankDifference > 0)
for (int i = 1; i <= RankDifference - 1; i++)
{
KashshaptuMoveIsLegal = true;
if (Board[StartRank + i, StartFile - i] != " ")
KashshaptuMoveIsLegal = false;
}
else
{
for (int i = -1; i >= RankDifference + 1; i--)
{
KashshaptuMoveIsLegal = true;
if (Board[StartRank + i, StartFile - i] != " ")
KashshaptuMoveIsLegal = false;
}
}
}
}
return KashshaptuMoveIsLegal;
}
VB6.0 Solution
Answer:
Add a variable to display the number of pieces each player has
[edit | edit source]An option will appear after or before a move is made so that the user can choose to see the number of pieces he or she has left on the board.
VB.Net solution
Answer:
Sub Main()
Dim Board(BoardDimension, BoardDimension) As String
' ...
Do
' ...
Do
DisplayBoard(Board)
Dim BlackCount As Integer = 0
Dim WhiteCount As Integer = 0
' Nested for loop to check the whole board and count pieces
For i As Integer = 1 To BoardDimension
For j As Integer = 1 To BoardDimension
If Board(i, j)(0) = "B" Then
BlackCount = BlackCount + 1
ElseIf Board(i, j)(0) = "W" Then
WhiteCount = WhiteCount + 1
End If
Next
Next
DisplayWhoseTurnItIs(WhoseTurn)
' Display correct variable depending on whose turn it is
If WhoseTurn = "W" Then
Console.WriteLine("You have " & WhiteCount & " pieces left.")
ElseIf WhoseTurn = "B" Then
Console.WriteLine("You have " & BlackCount & " pieces left.")
End If
' ...
Loop Until GameOver
' ...
Loop Until PlayAgain <> "Y"
End Sub
Python Solution
Answer:
def PiecesLeft(Board):
BCount = 0
WCount = 0
for y in range(1,9):
for x in range(1,9):
if Board[y][x][0] == "B":
BCount += 1
elif Board[y][x][0] == "W":
WCount += 1
return BCount,WCount
------------------------------------------
if __name__ == "__main__":
Board = CreateBoard() #0th index not used
StartSquare = 0
FinishSquare = 0
PlayAgain = "Y"
while PlayAgain == "Y":
WhoseTurn = "W"
GameOver = False
SampleGame = raw_input("Do you want to play the sample game (enter Y for Yes)? ")
if ord(SampleGame) >= 97 and ord(SampleGame) <= 122:
SampleGame = chr(ord(SampleGame) - 32)
InitialiseBoard(Board, SampleGame)
while not(GameOver):
DisplayBoard(Board)
DisplayWhoseTurnItIs(WhoseTurn)
MoveIsLegal = False
while not(MoveIsLegal):
StartSquare, FinishSquare = GetMove(StartSquare, FinishSquare)
StartRank = StartSquare % 10
StartFile = StartSquare / 10
FinishRank = FinishSquare % 10
FinishFile = FinishSquare / 10
MoveIsLegal = CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
if not(MoveIsLegal):
print "That is not a legal move - please try again"
GameOver = CheckIfGameWillBeWon(Board, FinishRank, FinishFile)
MakeMove(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
#CHANGED
<u>BPieces, WPieces = PiecesLeft(Board)
print ("Number of White Pieces Left:", WPieces)
print ("Number of Black Pieces Left:", BPieces)</u>
if GameOver:
DisplayWinner(WhoseTurn)
if WhoseTurn == "W":
WhoseTurn = "B"
else:
WhoseTurn = "W"
PlayAgain = raw_input("Do you want to play again (enter Y for Yes)? ")
if ord(PlayAgain) >= 97 and ord(PlayAgain) <= 122:
PlayAgain = chr(ord(PlayAgain) - 32)
#Python 2.7 - Jordan Watson [Big up Bullers]
Java Solution
Answer:
void displayNumberOfPiecesLeft (String[][] board) {
int noOfWhitePiecesLeft,rankNo,fileNo,noOfBlackPiecesLeft;
noOfWhitePiecesLeft = 0;
noOfBlackPiecesLeft = 0;
for (rankNo = 1; rankNo <= BOARD_DIMENSION; rankNo++) {
for (fileNo = 1; fileNo <= BOARD_DIMENSION; fileNo++) {
if (board[fileNo][rankNo].charAt(0) == 'W') noOfWhitePiecesLeft++;
if (board[fileNo][rankNo].charAt(0) == 'B') noOfBlackPiecesLeft++;
}
}
System.out.println("Number of White pieces left: " + noOfWhitePiecesLeft );
System.out.println("Number of Black pieces left: " + noOfBlackPiecesLeft + '\n');
}
//Nonso Makwe
Pascal Solution
Answer:
C# Solution
Answer:
VB6.0 Solution
Answer:
Add taken pieces Counter
[edit | edit source]Separate taken pieces counter for White and Black
VB.Net solution
Answer:
Sub Main()
' ...
' WhiteScore is how many Black pieces White has taken and vice-versa.
Dim WhiteScore As Integer
Dim BlackScore As Integer
PlayAgain = "Y"
Do
' Initial Values
WhiteScore = 0
BlackScore = 0
WhoseTurn = "W"
' ...
Do
DisplayBoard(Board)
DisplayWhoseTurnItIs(WhoseTurn)
' Display current pieces taken score.
Console.WriteLine("White has taken {0} pieces. Black has taken {1} pieces.", WhiteScore, BlackScore)
MoveIsLegal = False
' ...
GameOver = CheckIfGameWillBeWon(Board, FinishRank, FinishFile)
MakeMove(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn, WhiteScore, BlackScore)
If GameOver Then
DisplayWinner(WhoseTurn)
' Display final pieces taken score.
Console.WriteLine("White took {0} pieces. Black took {1} pieces.", WhiteScore, BlackScore)
End If
' ...
Loop Until GameOver
' ...
Loop Until PlayAgain <> "Y"
End Sub
Sub MakeMove(ByRef Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer, ByVal WhoseTurn As Char, ByRef WhiteScore As Integer, ByRef BlackScore As Integer)
If
' ...
Else
' If white has taken a piece, increment their score and the same for black.
' Fortunately, taking own pieces is prevented by CheckMoveIsLegal so we don't need to check that here.
If WhoseTurn = "W" And Board(FinishRank, FinishFile) <> " " Then
WhiteScore += 1
ElseIf WhoseTurn = "B" And Board(FinishRank, FinishFile) <> " " Then
BlackScore += 1
End If
Board(FinishRank, FinishFile) = Board(StartRank, StartFile)
Board(StartRank, StartFile) = " "
End If
End Sub
Python Solution
Answer:
def PiecesTaken(Board):
wTaken = 16
bTaken = 16
for x in range(1,BOARDDIMENSION+1):
for y in range(1,BOARDDIMENSION+1):
if Board[x][y][0]== "W":
wTaken = wTaken - 1
if Board[x][y][0]=="B":
bTaken = bTaken - 1
print(wTaken,"white pieces taken.",bTaken,"black pieces taken.")
Java Solution
Answer:
int piecesTakenByWhite(String board[][]){
int piecesTakenByWhite = 0;
for(int c=1; c<=BOARD_DIMENSION; c++){
for(int r=1; r<=BOARD_DIMENSION; r++){
if(board[c][r].charAt(0)=='B'){
piecesTakenByWhite++;
}
}
}
int noOfWhiteTaken=16-piecesTakenByWhite;
return noOfWhiteTaken;
}
int piecesTakenByBlack(String board[][]){
int piecesTakenByBlack = 0;
for(int c=1; c<=BOARD_DIMENSION; c++){
for(int r=1; r<=BOARD_DIMENSION; r++){
if(board[c][r].charAt(0)=='W'){
piecesTakenByBlack++;
}
}
}
int noOfBlackTaken=16-piecesTakenByBlack;
return noOfBlackTaken;
}
console.println("White has taken " + piecesTakenByWhite(board) + " pieces");
console.println("Black has taken " + piecesTakenByBlack(board) + " pieces");
//The console.println goes under makemove near line 90.
Pascal Solution
Answer:
Procedure TakenPieces (var Board: TBoard);
var
i,j,wtaken,btaken:integer;
begin
wtaken:=16;
btaken:=16;
for i:= 1 to BoardDimension do
begin
for j:= 1 to BoardDimension do
begin
if Board[i,j][1]='W' then
wtaken:=wtaken-1;
if Board[i,j][1]='B' then
btaken:=btaken-1;
end;
end;
writeln('Number of white pieces taken: ',wtaken);
writeln('Number of black pieces taken: ',btaken);
end;
C# Solution
Answer:
VB6.0 Solution
Answer:
Prevent pieces moving off the top or left edge of the board
[edit | edit source]Currently, you can move pieces into the 0 files or ranks.
VB.Net solution
Answer:
Function CheckMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer,
ByVal FinishRank As Integer, ByVal FinishFile As Integer, ByVal WhoseTurn As Char) As Boolean
' ...
If FinishRank > 8 Or FinishRank < 1 Or FinishFile > 8 Or FinishFile < 1 Then
Return False
End If
' ...
End Function
Python Solution
Answer:
def CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn):
MoveIsLegal = True
if (FinishFile == StartFile) and (FinishRank == StartRank):
MoveIsLegal = False
else:
PieceType = Board[StartRank][StartFile][1]
PieceColour = Board[StartRank][StartFile][0]
'''if FinishRank == 0 or FinishFile == 0:
MoveIsLegal = False'''
if WhoseTurn == "W":
if PieceColour != "W":
MoveIsLegal = False
if Board[FinishRank][FinishFile][0] == "W":
MoveIsLegal = False
else:
if PieceColour != "B":
MoveIsLegal = False
if Board[FinishRank][FinishFile][0] == "B":
MoveIsLegal = False
if MoveIsLegal == True:
if PieceType == "R":
MoveIsLegal = CheckRedumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, PieceColour)
elif PieceType == "S":
MoveIsLegal = CheckSarrumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
elif PieceType == "M":
MoveIsLegal = CheckMarzazPaniMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
elif PieceType == "G":
MoveIsLegal = CheckGisgigirMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
elif PieceType == "N":
MoveIsLegal = CheckNabuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
elif PieceType == "E":
MoveIsLegal = CheckEtluMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
return MoveIsLegal
Java Solution
Answer:
void getMove(Position startPosition, Position finishPosition) {
boolean moveIsLegal = false;
do {
startPosition.coordinates = console
.readInteger("Enter cooordinates of square containing piece to move (file first): ");
finishPosition.coordinates = console
.readInteger("Enter cooordinates of square to move piece to (file first): ");
if ((startPosition.coordinates % 10 == 0)
|| (startPosition.coordinates % 10 == 9)
|| (startPosition.coordinates / 10 <= 0)
|| (startPosition.coordinates / 10 >= 9)
|| (finishPosition.coordinates % 10 == 0)
|| (finishPosition.coordinates % 10 == 9)
|| (finishPosition.coordinates / 10 <= 0)
|| (finishPosition.coordinates / 10 >= 9)) {
console.println("That is not a legal move - please try again");
} else {
moveIsLegal = true;
}
} while (moveIsLegal == false);
}
Alex Drogemuller
void getMove(Position startPosition, Position finishPosition) {
int coordinates = console.readInteger("Enter coordinates of square containing piece to move (file first):");
while(coordinates>=88 || coordinates<=11 || coordinates==20 || coordinates==30 || coordinates==40 || coordinates==50 || coordinates==60 || coordinates==70 || coordinates==80||
coordinates==19 || coordinates==29 || coordinates==39 || coordinates==49 || coordinates==59 || coordinates==69 || coordinates==79){
coordinates = console.readInteger("Incorrect coordinates.\nEnter coordinates of square containing piece to move (file first):");
}
startPosition.coordinates=coordinates;
coordinates = console.readInteger("Enter cooordinates of square to move piece to (file first):");
while(coordinates>=88 || coordinates<=11 || coordinates==20 || coordinates==30 || coordinates==40 || coordinates==50 || coordinates==60 || coordinates==70 || coordinates==80||
coordinates==19 || coordinates==29 || coordinates==39 || coordinates==49 || coordinates==59 || coordinates==69 || coordinates==79){
coordinates = console.readInteger("Incorrect coordinates.\nEnter coordinates of square containing piece to move (file first):");
}
finishPosition.coordinates = coordinates;
}
== Bill Gale - Calday Grange Grammar School ==
come on guys... its like just one if statement and adding parameters...
boolean checkMoveIsLegal(String[][] board, int startRank, int startFile, int finishRank, int finishFile, char whoseTurn, Position finishPosition) {
// some AQA code.
if (finishPosition.coordinates > 88){
moveIsLegal = false;
return moveIsLegal;
}
//... Add all the rest of the method.
Bob Singh
Pascal Solution
Answer:
Function CheckMoveIsLegal(Var Board : TBoard; StartRank, StartFile, FinishRank, FinishFile : Integer;
WhoseTurn : Char) : Boolean;
Var
PieceType : Char;
PieceColour : Char;
MoveIsLegal : Boolean;
Begin
MoveIsLegal := True;
If (FinishFile = StartFile) And (FinishRank = StartRank)
Then MoveIsLegal := False
Else if (FinishFile = 0) or (FinishRank = 0) then MoveIsLegal:= False
Else
Begin
PieceType := Board[StartRank, StartFile][2];
PieceColour := Board[StartRank, StartFile][1];
If WhoseTurn = 'W'
Then
Begin
If PieceColour <> 'W'
Then MoveIsLegal := False;
If Board[FinishRank, FinishFile][1] = 'W'
Then MoveIsLegal := False;
End
Else
Begin
If PieceColour <> 'B'
Then MoveIsLegal := False;
If Board[FinishRank, FinishFile][1] = 'B'
Then MoveIsLegal := False
End;
If MoveIsLegal = True
Then
Begin
Case PieceType Of
'R' : MoveIsLegal := CheckRedumMoveIsLegal(Board, StartRank, StartFile, FinishRank,
FinishFile, PieceColour);
'S' : MoveIsLegal := CheckSarrumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
'M' : MoveIsLegal := CheckMarzazPaniMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
'G' : MoveIsLegal := CheckGisgigirMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
'N' : MoveIsLegal := CheckNabuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
'E' : MoveIsLegal := CheckEtluMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
End;
End;
End;
CheckMoveIsLegal := MoveIsLegal;
End;
or can use this when getting coordinates in the first place.
Procedure GetMove(Var StartSquare, FinishSquare : Integer);
//Procedure changed to ensure that something is entered and that it is a number and that both
//digits in the number are between 1 and BoardDimension
var Temp1, Temp2: String;
Valid:Boolean;
Begin
repeat
Valid:=False;
Write('Enter coordinates of square containing piece to move (file first): ');
//Readln(StartSquare);
readln(Temp1);
Write('Enter coordinates of square to move piece to (file first): ');
//Readln(FinishSquare);
readln(Temp2);
//If two characters in each temp number are between 1 and the Board Dimension
if(temp1<>'') and (temp2<>'')
and(temp1[1]>'0') and (temp1[1]<=inttostr(BoardDimension))
and (temp1[2]>'0') and (temp1[2]<=inttostr(BoardDimension))
and (temp2[1]>'0') and (temp2[1]<=inttostr(BoardDimension))
and (temp2[2]>'0') and (temp2[2]<=inttostr(BoardDimension))then
begin
//then convert the temp numbers to integers
StartSquare:=strtoint(Temp1);
FinishSquare:=strToInt(Temp2);
//set valid to be true
Valid:=True;
end
else
writeln('Must enter something, cannot use characters and zeros are invalid coordinates');
until valid=true;
end;
C# Solution
Answer:
public static Boolean CheckMoveIsLegal(string[,] Board, int StartRank, int StartFile, int FinishRank, int FinishFile, char WhoseTurn)
{
char PieceType;
char PieceColour;
Boolean MoveIsLegal = true;
if (StartRank < 1 || StartRank > 8 || FinishRank < 1 || FinishRank > 8 || StartFile < 1 || StartFile > 8 || FinishFile < 1 || FinishFile > 8) // Checks if the pieces go off the array
{
MoveIsLegal = false; // if the IF statement above is true then the Move is false.
}
else // if the pieces are in the array then all of the following happens
{
if ((FinishFile == StartFile) && (FinishRank == StartRank))
{
MoveIsLegal = false;
}
PieceType = Board[StartRank, StartFile][1];
PieceColour = Board[StartRank, StartFile][0];
if (WhoseTurn == 'W')
{
if (PieceColour != 'W')
{
MoveIsLegal = false;
}
if (Board[FinishRank, FinishFile][0] == 'W')
{
MoveIsLegal = false;
}
}
else
{
if (PieceColour != 'B')
{
MoveIsLegal = false;
}
if (Board[FinishRank, FinishFile][0] == 'B')
{
MoveIsLegal = false;
}
}
if (MoveIsLegal)
{
switch (PieceType)
{
case 'R':
MoveIsLegal = CheckRedumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, PieceColour);
break;
case 'S':
MoveIsLegal = CheckSarrumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
case 'M':
MoveIsLegal = CheckMarzazPaniMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
case 'G':
MoveIsLegal = CheckGisgigirMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
case 'N':
MoveIsLegal = CheckNabuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
case 'E':
MoveIsLegal = CheckEtluMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
case 'K':
MoveIsLegal = CheckKashaptuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile); /////////////////////
break;
default:
MoveIsLegal = false;
break;
}
}
}
return MoveIsLegal;
}
VB6.0 Solution
Answer:
A-level Computing/AQA/Problem Solving, Programming, Data Representation and Practical Exercise/Skeleton code/2015 Exam/Section D
Allow the Redum to move two pieces as its first move.
[edit | edit source]Pawns in chess are allowed a "double" move, however only out of their starting position.
VB.Net solution
Answer:
'code courtesy of John Chamberlain
Function CheckRedumMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer, ByVal ColourOfPiece As Char) As Boolean
If ColourOfPiece = "W" Then
If (FinishRank = StartRank - 1) Or ((StartRank = 7) And (FinishRank = StartRank - 2)) Then
If FinishFile = StartFile And Board(FinishRank, FinishFile) = " " Then
Return True
ElseIf Abs(FinishFile - StartFile) = 1 And Board(FinishRank, FinishFile)(0) = "B" Then
Return True
End If
End If
Else
If (FinishRank = StartRank + 1)Or ((StartRank = 2) And (FinishRank = StartRank + 2)) Then
If FinishFile = StartFile And Board(FinishRank, FinishFile) = " " Then
Return True
ElseIf Abs(FinishFile - StartFile) = 1 And Board(FinishRank, FinishFile)(0) = "W" Then
Return True
End If
End If
End If
Return False
End Function
Python Solution
Answer:
def CheckRedumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, ColourOfPiece):
CheckRedumMoveIsLegal = False
if ColourOfPiece == "W":
#CHANGED IF CONDITION
if (FinishRank == StartRank - 1) or (FinishRank == StartRank - 2 and StartRank == 7):
if FinishFile == StartFile and Board[FinishRank][FinishFile] == " ":
CheckRedumMoveIsLegal = True
elif abs(FinishFile - StartFile) == 1 and Board[FinishRank][FinishFile][0] == "B":
CheckRedumMoveIsLegal = True
#CHANGED IF CONDITION
elif (FinishRank == StartRank + 1) or (FinishRank == StartRank + 2 and StartRank == 2):
if FinishFile == StartFile and Board[FinishRank][FinishFile] == " ":
CheckRedumMoveIsLegal = True
elif abs(FinishFile - StartFile) == 1 and Board[FinishRank][FinishFile][0] == "W":
CheckRedumMoveIsLegal = True
return CheckRedumMoveIsLegal
#Python 2.7 - George Williams
Java Solution
Answer:
boolean checkRedumMoveIsLegal(String[][] board, int startRank,int startFile, int finishRank, int finishFile, char colourOfPiece) {
boolean redumMoveIsLegal = false;
if (colourOfPiece == 'W') {
//double move
if (startRank == 7 && finishRank == startRank - 2) {
if ((finishFile == startFile) && (board[finishRank][finishFile].equals(" "))) {
redumMoveIsLegal = true;
}
}
//other moves
if (finishRank == startRank - 1) {
//single move
if ((finishFile == startFile) && (board[finishRank][finishFile].equals(" "))) {
redumMoveIsLegal = true;
}
//taking another piece
else {
if ((abs(finishFile - startFile) == 1) && (board[finishRank][finishFile].charAt(0) == 'B')) {
redumMoveIsLegal = true;
}
}
}
}
else {
//double move
if (startRank == 2 && finishRank == startRank + 2) {
if ((finishFile == startFile) && (board[finishRank][finishFile].equals(" "))) {
redumMoveIsLegal = true;
}
}
//other moves
if (finishRank == startRank + 1) {
//single move
if ((finishFile == startFile) && (board[finishRank][finishFile].equals(" "))) {
redumMoveIsLegal = true;
}
//taking another peice
else {
if ((abs(finishFile - startFile) == 1) && (board[finishRank][finishFile].charAt(0) == 'W')) {
redumMoveIsLegal = true;
}
}
}
}
return redumMoveIsLegal;
}
Mikhail Z Hussain - Reading school
Pascal Solution
Answer:
Function CheckRedumMoveIsLegal(Var Board : TBoard; StartRank, StartFile, FinishRank, FinishFile : Integer;
ColourOfPiece : Char) : Boolean;
Begin
CheckRedumMoveIsLegal := False;
If ColourOfPiece = 'W'
Then
Begin
If (FinishRank = StartRank - 1 ) or ((StartRank=7) and (FinishRank = StartRank - 2) )//added or statement
Then
Begin
If (FinishFile = StartFile) And (Board[FinishRank, FinishFile] = ' ')
Then CheckRedumMoveIsLegal := True
Else
Begin
If (Abs(FinishFile - StartFile) = 1) And
(Board[FinishRank, FinishFile][1] = 'B')
Then CheckRedumMoveIsLegal := True
End
End
End
Else
Begin
If (FinishRank = StartRank + 1) or ((StartRank=2) and (FinishRank=StartRank+2))//added or statement
Then
Begin
If (FinishFile = StartFile) And (Board[FinishRank, FinishFile] = ' ')
Then CheckRedumMoveIsLegal := True
Else
Begin
If (Abs(FinishFile - StartFile) = 1) And
(Board[FinishRank, FinishFile][1] = 'W')
Then CheckRedumMoveIsLegal := True;
End
End
End;
End;
C# Solution
Answer:
public static Boolean CheckRedumMoveIsLegal(string[,] Board, int StartRank, int StartFile, int FinishRank, int FinishFile, char ColourOfPiece)
{
Boolean RedumMoveIsLegal = false;
if (ColourOfPiece == 'W')
{
if (FinishRank == StartRank - 1)
if ((FinishFile == StartFile) && (Board[FinishRank, FinishFile] == " "))
RedumMoveIsLegal = true;
else
if ((Math.Abs(FinishFile - StartFile) == 1) && (Board[FinishRank, FinishFile][0] == 'B'))
RedumMoveIsLegal = true;
if (StartRank == 7)
{
if (FinishRank == StartRank -2)
{
if ((FinishFile == StartFile) && (Board[FinishRank, FinishFile] == " "))
RedumMoveIsLegal = true;
else
if ((Math.Abs(FinishFile - StartFile) == 1) && (Board[FinishRank, FinishFile][0] == 'B'))
RedumMoveIsLegal = true;
}
}
}
else
{
if (FinishRank == StartRank + 1)
if ((FinishFile == StartFile) && (Board[FinishRank, FinishFile] == " "))
RedumMoveIsLegal = true;
else
if ((Math.Abs(FinishFile - StartFile) == 1) && (Board[FinishRank, FinishFile][0] == 'W'))
RedumMoveIsLegal = true;
if (StartRank ==2)
{
if (FinishRank == StartRank +2)
{
if ((FinishFile == StartFile) && (Board[FinishRank, FinishFile] == " "))
RedumMoveIsLegal = true;
else
if ((Math.Abs(FinishFile - StartFile) == 1) && (Board[FinishRank, FinishFile][0] == 'W'))
RedumMoveIsLegal = true;
}
}
}
return RedumMoveIsLegal;
//done by TSpencerJones
VB6.0 Solution
Answer:
Print if moving piece does not belong to current player
[edit | edit source]The initial program does not allow a player to move their enemy's pieces but only prints the normal "please try again" message. This prints a specialised message if you try to move a piece which does not belong to you.
VB.Net solution
Answer:
If PieceColour <> WhoseTurn Then
Console.WriteLine()
Console.WriteLine("That is not your piece.")
Return False
End If
If Board(FinishRank, FinishFile)(0) = WhoseTurn Then
Return False
End If
Python Solution
Answer:
def CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn):
MoveIsLegal = True
if (FinishFile == StartFile) and (FinishRank == StartRank):
MoveIsLegal = False
else:
PieceType = Board[StartRank][StartFile][1]
PieceColour = Board[StartRank][StartFile][0]
if WhoseTurn == "W":
if PieceColour != "W":
MoveIsLegal = False
print("That is not your piece - please try again")
if Board[FinishRank][FinishFile][0] == "W":
MoveIsLegal = False
else:
if PieceColour != "B":
MoveIsLegal = False
print("That is not your piece - please try again")
if Board[FinishRank][FinishFile][0] == "B":
MoveIsLegal = False
if MoveIsLegal == True:
if PieceType == "R":
MoveIsLegal = CheckRedumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, PieceColour)
elif PieceType == "S":
MoveIsLegal = CheckSarrumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
elif PieceType == "M":
MoveIsLegal = CheckMarzazPaniMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
elif PieceType == "G":
MoveIsLegal = CheckGisgigirMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
elif PieceType == "N":
MoveIsLegal = CheckNabuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
elif PieceType == "E":
MoveIsLegal = CheckEtluMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
return MoveIsLegal
Patch file: not-your-piece.patch
Java Solution
Answer:
boolean checkMoveIsLegal(String[][] board, int startRank, int startFile, int finishRank, int finishFile, char whoseTurn) {
//....
if (whoseTurn == 'W') {
if (pieceColour != 'W') {
moveIsLegal = false;
console.println("That is not your piece.");//adds warning
}
if (board[finishRank][finishFile].charAt(0) == 'W') {
moveIsLegal = false;
}
} else {
if (pieceColour != 'B') {
moveIsLegal = false;
console.println("That is not your piece.");//adds warning
}
if (board[finishRank][finishFile].charAt(0) == 'B') {
moveIsLegal = false;
}
}
//.....
return moveIsLegal;
}
//
Pascal Solution
Answer:
C# Solution
Answer:
VB6.0 Solution
Answer:
Remove the restriction of one tile on the Nabu
[edit | edit source]Make the Nabu like a bishop in chess, can move any number of tiles diagonally.
VB.Net solution
Answer:
Function CheckNabuMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer) As Boolean
Dim StepRank As Integer
Dim StepFile As Integer
Dim CheckPosRank As Integer
Dim CheckPosFile As Integer
Dim LegalMove As Boolean = True
If Abs(FinishFile - StartFile) <> Abs(FinishRank - StartRank) Then
LegalMove = False
Else
If FinishFile < StartFile Then StepFile = -1 Else StepFile = 1
If FinishRank < StartRank Then StepRank = -1 Else StepRank = 1
CheckPosRank = StartRank
CheckPosFile = StartFile
Do
CheckPosRank=CheckPosRank+StepRank
CheckPosFile = CheckPosFile + StepFile
If Board(CheckPosRank, CheckPosFile) <> " " Then LegalMove = False
Loop Until (CheckPosRank = FinishRank) And (CheckPosFile = FinishFile) Or Not LegalMove
End If
If (CheckPosRank = FinishRank) And (CheckPosFile = FinishFile) Then LegalMove = True
Return LegalMove
End Function
'Uploaded by an AS Student
Python Solution
Answer:
def CheckNabuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile):
NabuMoveIsLegal = False
RankDifference = FinishRank - StartRank
FileDifference = FinishFile - StartFile
if abs(RankDifference) == abs(FileDifference):
NabuMoveIsLegal = True
if FileDifference == RankDifference:
if RankDifference > 0:
NabuMoveIsLegal = True
for Count in range(1, RankDifference):
if Board[StartRank + Count][StartFile + Count] != " ":
NabuMoveIsLegal = False
elif RankDifference < 0:
NabuMoveIsLegal = True
for Count in range(-1, RankDifference, -1):
if Board[StartRank + Count][StartFile + Count] != " ":
NabuMoveIsLegal = False
elif FileDifference == -RankDifference:
if RankDifference > 0:
for Count in range(1, RankDifference):
if Board[StartRank + Count][StartFile - Count] != " ":
NabuMoveIsLegal = False
elif RankDifference < 0:
for Count in range(-1, RankDifference, -1):
if Board[StartRank + Count][StartFile - Count] != " ":
NabuMoveIsLegal = False
return NabuMoveIsLegal
# Python 3, by Xsanda
A easier solution
def CheckNabuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile):
CheckNabuMoveIsLegal = False
if abs(FinishFile - StartFile) == abs(FinishRank - StartRank):
CheckNabuMoveIsLegal = True
return CheckNabuMoveIsLegal
# Python 3 Nothingtoseehere
Java Solution
Answer:
boolean checkNabuMoveIsLegal(String[][] board, int startRank, int startFile, int finishRank, int finishFile) {
boolean nabuMoveIsLegal = false;
if ((abs(finishFile - startFile) <= 8) && (abs(finishRank - startRank) <= 8)) {
nabuMoveIsLegal = true;
}
return nabuMoveIsLegal;
}
Bob Singh
/*The above solution does not take into
*account the chance of there being pieces
*in the way. This one does
*/
boolean checkNabuMoveIsLegal(String[][] board, int startRank, int startFile, int finishRank, int finishFile) {
int dFile = Math.abs(startFile - finishFile);
int dRank = Math.abs(startRank - finishRank);
if (dFile == dRank){//on a diagonal
int sdFile = -(int) Math.signum(startFile - finishFile);
int sdRank = -(int) Math.signum(startRank - finishRank);
for (int i = 1; i < dFile; i ++){//no obstructing pieces
int cFile = startFile + (sdFile * i);
int cRank = startRank + (sdRank * i);
int marker = 0;
if (board[cRank][cFile] != " "){
return false;
}
}
return true;
}
else{
return false;
}
}
//Zephyr 12
Pascal Solution
Answer:
Function CheckNabuMoveIsLegal(Var Board : TBoard; StartRank, StartFile, FinishRank, FinishFile : Integer) : Boolean;
Begin
CheckNabuMoveIsLegal := False;
If (Abs(FinishFile - StartFile) = Abs(FinishRank - StartRank)) //Checks if rank and file differenece equal
Then CheckNabuMoveIsLegal := True;
End;
//#Daz
C# Solution
Answer:
//I'm sure this isn't the best way to do it, but it works.
public static Boolean CheckNabuMoveIsLegal(string[,] Board, int StartRank, int StartFile, int FinishRank, int FinishFile, char WhoseTurn)
{
Boolean NabuMoveIsLegal = false;
int dFile = Math.Abs(StartFile - FinishFile);
if (WhoseTurn == 'B')
{
if ((Math.Abs(FinishFile - StartFile) <= 9) && (Math.Abs(FinishRank - StartRank) <= 9))
{
for (int i = 1; i < dFile; i++)
{
if (Board[(Math.Abs(StartFile + i)), (Math.Abs(StartRank + i))] != " ")
{
NabuMoveIsLegal = false;
}
else
{
NabuMoveIsLegal = true;
}
}
}
}
if (WhoseTurn == 'W')
{
if ((Math.Abs(FinishFile - StartFile) <= 9) && (Math.Abs(FinishRank - StartRank) <= 9))
{
for (int i = 1; i > dFile; i--)
{
if (Board[(Math.Abs(StartFile + i)), (Math.Abs(StartRank + i))] != " ")
{
NabuMoveIsLegal = false;
}
else
{
NabuMoveIsLegal = true;
}
}
}
}
return NabuMoveIsLegal;
}
//Tom Short - UTC Reading
VB6.0 Solution
Answer:
Add a way to forfeit the game
[edit | edit source]Add an option to forfeit each turn (similar to the way you can knock over your king in chess).
VB.Net solution
Answer:
Sub Main()
' ...
Dim Resigned As Boolean
' ...
Do
' ...
Do
' ...
Do
' ...
If StartSquare = 0 Then
' Player resigned
If WhoseTurn = "W" Then
Console.WriteLine("White resigned!")
Else
Console.WriteLine("Black resigned!")
End If
Resigned = True
MoveIsLegal = True
GameOver = True
Else
StartRank = StartSquare Mod 10
StartFile = StartSquare \ 10
FinishRank = FinishSquare Mod 10
FinishFile = FinishSquare \ 10
MoveIsLegal = CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
If Not MoveIsLegal Then
Console.WriteLine("That is not a legal move - please try again")
End If
End If
Loop Until MoveIsLegal
If Not Resigned Then
GameOver = CheckIfGameWillBeWon(Board, FinishRank, FinishFile)
MakeMove(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
If GameOver Then
DisplayWinner(WhoseTurn)
End If
If WhoseTurn = "W" Then
WhoseTurn = "B"
Else
WhoseTurn = "W"
End If
End If
Loop Until GameOver
' ...
Loop Until PlayAgain <> "Y"
End Sub
Sub GetMove(ByRef StartSquare As Integer, ByRef FinishSquare As Integer)
Console.Write("Enter coordinates of square containing piece to move (file first): ")
StartSquare = Console.ReadLine
If StartSquare = 0 Then
FinishSquare = 0
Else
Console.Write("Enter coordinates of square to move piece to (file first): ")
FinishSquare = Console.ReadLine
End If
End Sub
Python Solution
Answer:
Edited regions will have comments by them.
if __name__ == "__main__":
Board = CreateBoard() #0th index not used
StartSquare = 0
FinishSquare = 0
PlayAgain = "Y"
while PlayAgain == "Y":
Forfeit=False # Resetting the Forfeit variable
WhoseTurn = "W"
GameOver = False
SampleGame = input("Do you want to play the sample game (enter Y for Yes)? ")
if ord(SampleGame) >= 97 and ord(SampleGame) <= 122:
SampleGame = chr(ord(SampleGame) - 32)
InitialiseBoard(Board, SampleGame)
while not(GameOver):
DisplayBoard(Board)
DisplayWhoseTurnItIs(WhoseTurn)
MoveIsLegal = False
while not(MoveIsLegal):
KeepPlaying= input("Would you like to make a move? (Y/N): ") # Depending on how you want a forfeit
if not KeepPlaying.upper() =='Y': # to be input. This will ask the user
Forfeit=True # whether they want to continue or not.
MoveIsLegal=True # Does not accept lower case y (can be amended if needed).
else: # This region will be indented so that it
Forfeit=False # does not run if a forfeit command is issued.
StartSquare, FinishSquare = GetMove(StartSquare, FinishSquare)
StartRank = StartSquare % 10
StartFile = StartSquare // 10
FinishRank = FinishSquare % 10
FinishFile = FinishSquare // 10
MoveIsLegal = CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
if not(MoveIsLegal):
print("That is not a legal move - please try again")
if Forfeit==True: # This version of ending
GameOver=True # the game will be run if
if WhoseTurn == "W": # a player forfeits. The
print("White has forfeit. Black wins!") # standard ending will run
else: # if no forfeit command is
print("Black has forfeit. White wins!") # issued.
else:
GameOver = CheckIfGameWillBeWon(Board, FinishRank, FinishFile)
MakeMove(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
if GameOver:
DisplayWinner(WhoseTurn)
if WhoseTurn == "W":
WhoseTurn = "B"
else:
WhoseTurn = "W"
PlayAgain = input("Do you want to play again (enter Y for Yes)? ")
if ord(PlayAgain) >= 97 and ord(PlayAgain) <= 122:
PlayAgain = chr(ord(PlayAgain) - 32)
Java Solution
Answer:
void getMove(Position startPosition, Position finishPosition, char whoseTurn) {
char forfeit = console.readChar("Would you like to forfeit? Enter Y to forfeit or N to carry on playing. ");
if((whoseTurn=='W' && (forfeit=='Y' ||forfeit=='y'))){
console.println("\nWhite has forfeited the game. Black wins.");
System.exit(0);
}
if((whoseTurn=='B' && (forfeit=='Y' ||forfeit=='y'))){
console.println("\nBlack has forfeited the game. White wins.");
System.exit(0);
}
else{
int coordinates = console.readInteger("Enter coordinates of square containing piece to move (file first):");
while(coordinates>=88 || coordinates<=11 || coordinates==20 || coordinates==30 || coordinates==40 || coordinates==50 || coordinates==60 || coordinates==70 || coordinates==80||
coordinates==19 || coordinates==29 || coordinates==39 || coordinates==49 || coordinates==59 || coordinates==69 || coordinates==79){
coordinates = console.readInteger("Incorrect coordinates.\nEnter coordinates of square containing piece to move (file first):");
}
startPosition.coordinates=coordinates;
coordinates = console.readInteger("Enter cooordinates of square to move piece to (file first):");
while(coordinates>=88 || coordinates<=11 || coordinates==20 || coordinates==30 || coordinates==40 || coordinates==50 || coordinates==60 || coordinates==70 || coordinates==80||
coordinates==19 || coordinates==29 || coordinates==39 || coordinates==49 || coordinates==59 || coordinates==69 || coordinates==79){
coordinates = console.readInteger("Incorrect coordinates.\nEnter coordinates of square containing piece to move (file first):");
}
finishPosition.coordinates = coordinates;
}
}
This code also includes another 2 possible questions which were 1.11 and 1.15. You would also need to add the argument near line 75
Pascal Solution
Answer:
//call to a new function within main program. If it returns true then game is over
if forfeitGame(Board,WhoseTurn)=True then
GameOver:=True
else //otherwise play game
begin
//new function
Function ForfeitGame(Board:TBoard; WhoseTurn:Char):Boolean;
//Function checks to see if player wants to end game early
var forfeit:char;
begin
writeln('Forfeit Game? Y for yes');
readln(forfeit);
if uppercase(forfeit)='Y' then
begin
//this is the procedure we wrote for updating the pices captured etc. It has been amended
//to pass the forfeit to. It used to pass only the board. If you are including
//this procedure then you will need to add forfeit:char into the interface for the
//procedure
updatePieces(Board,forfeit);
///decide the winner
if WhoseTurn='W' then writeln('White Wins')
else Writeln('Black wins');
ForfeitGame:=True;
end
else ForfeitGame:=False;
end;
C# Solution
Answer:
VB6.0 Solution
Answer:
Use GetTypeOfGame to ask the user what type of game they want to play
[edit | edit source]Currently the program does not use GetTypeOfGame when asking the user whether they want to play a sample game or not. Make the program use GetTypeOfGame to ask the user whether they want to play a sample game or not.
VB.Net solution
Answer:
Sub Main()
Dim Board(BoardDimension, BoardDimension) As String
Dim GameOver As Boolean
Dim StartSquare As Integer
Dim FinishSquare As Integer
Dim StartRank As Integer
Dim StartFile As Integer
Dim FinishRank As Integer
Dim FinishFile As Integer
Dim MoveIsLegal As Boolean
Dim PlayAgain As Char
Dim SampleGame As Char
Dim WhoseTurn As Char
PlayAgain = "Y"
Do
WhoseTurn = "W"
GameOver = False
SampleGame = GetTypeOfGame()
If Asc(SampleGame) >= 97 And Asc(SampleGame) <= 122 Then
SampleGame = Chr(Asc(SampleGame) - 32)
End If
InitialiseBoard(Board, SampleGame)
Do
DisplayBoard(Board)
DisplayWhoseTurnItIs(WhoseTurn)
MoveIsLegal = False
Do
GetMove(StartSquare, FinishSquare)
StartRank = StartSquare Mod 10
StartFile = StartSquare \ 10
FinishRank = FinishSquare Mod 10
FinishFile = FinishSquare \ 10
MoveIsLegal = CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
If Not MoveIsLegal Then
Console.WriteLine("That is not a legal move - please try again")
End If
Loop Until MoveIsLegal
GameOver = CheckIfGameWillBeWon(Board, FinishRank, FinishFile)
MakeMove(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
If GameOver Then
DisplayWinner(WhoseTurn)
End If
If WhoseTurn = "W" Then
WhoseTurn = "B"
Else
WhoseTurn = "W"
End If
Loop Until GameOver
Console.Write("Do you want to play again (enter Y for Yes)? ")
PlayAgain = Console.ReadLine
If Asc(PlayAgain) >= 97 And Asc(PlayAgain) <= 122 Then
PlayAgain = Chr(Asc(PlayAgain) - 32)
End If
Loop Until PlayAgain <> "Y"
End Sub
Python Solution
Answer:
def GetTypeOfGame():
SampleGame = "" #Assigns value of nothing for the variable SampleGame.
while SampleGame != "Y" and SampleGame != "N":
SampleGame = input("Do you want to play the sample game Y/N: ").upper()
return SampleGame
#Change TypeOfGame variables to SampleGame.
#'.upper()' Allows for both uppercase and lowercase characters to be entered.
if __name__ == "__main__":
Board = CreateBoard() #0th index not used
StartSquare = 0
FinishSquare = 0
PlayAgain = "Y"
while PlayAgain == "Y":
WhoseTurn = "W"
GameOver = False
SampleGame = GetTypeOfGame() #Makes SampleGame equal to the input returned from the function GetTypeOfGame
if ord(SampleGame) >= 97 and ord(SampleGame) <= 122:
SampleGame = chr(ord(SampleGame) - 32)
InitialiseBoard(Board, SampleGame)
while not(GameOver):
DisplayBoard(Board)
DisplayWhoseTurnItIs(WhoseTurn)
MoveIsLegal = False
while not(MoveIsLegal):
StartSquare, FinishSquare = GetMove(StartSquare, FinishSquare)
StartRank = StartSquare % 10
StartFile = StartSquare // 10
FinishRank = FinishSquare % 10
FinishFile = FinishSquare // 10
MoveIsLegal = CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
if not(MoveIsLegal):
print("That is not a legal move - please try again")
GameOver = CheckIfGameWillBeWon(Board, FinishRank, FinishFile)
MakeMove(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
if GameOver:
DisplayWinner(WhoseTurn)
if WhoseTurn == "W":
WhoseTurn = "B"
else:
WhoseTurn = "W"
PlayAgain = input("Do you want to play again (enter Y for Yes)? ")
if ord(PlayAgain) >= 97 and ord(PlayAgain) <= 122:
PlayAgain = chr(ord(PlayAgain) - 32)
Java Solution
Answer:
public Main() {
// ....
playAgain = 'Y';
do {
whoseTurn = 'W';
gameOver = false;
//console.print("Do you want to play the sample game (enter Y for Yes)? ");
sampleGame = gettypeOfGame(); //now calls function
if ((int)sampleGame >= 97 && (int)sampleGame <= 122) {
sampleGame = (char)((int)sampleGame - 32);
}
//...
}
^_^ Reading School
Pascal Solution
Answer:
Begin
PlayAgain := 'Y';
Repeat
WhoseTurn := 'W';
GameOver := False;
SampleGame:=GetTypeOfGame; //new code
C# Solution
Answer:
public static char GetTypeOfGame(char SampleGame)
{
do{
try
{
Console.WriteLine("Do you want to play the sample game" + Environment.NewLine + "(enter Y for Yes, Q for quit, or N for no)");
SampleGame = char.Parse(Console.ReadLine());
if ((int)SampleGame >= 97 && (int)SampleGame <= 122)
SampleGame = (char)((int)SampleGame - 32);
}
catch
{
Console.WriteLine("Please enter a valid answer");
GetTypeOfGame(SampleGame);
}
} while (SampleGame != 'Y' && SampleGame != 'Q' && SampleGame != 'N');
if (SampleGame == 'Q')
{
Environment.Exit(1);
}
return SampleGame;
}
// Answer kindly provided by UTC Reading #ShamelessPluggingAsRequestedByDan info@futureconnections.org.uk for more info
VB6.0 Solution
Answer:
Change the size of the board
[edit | edit source]The size of the two dimensional array that holds the board is defined by the constant BoardDimension. Change the size of the board to be bigger (for example: 10 by 10)
VB.Net solution
Answer:
' Note: I changed the size of the board to 9, kept the No. of ranks to 8 and added the Kaskshaptu piece to the 6th File.
Module CaptureTheSarrum
Const BoardDimension As Integer = 9 ' Changed from 8
Sub DisplayBoard(ByVal Board(,) As String)
Dim RankNo As Integer
Dim FileNo As Integer
Console.WriteLine()
For RankNo = 1 To BoardDimension - 1 ' This keeps the Number of ranks to 8.
Console.WriteLine(" _____________________________") ' Added 3 more underscores
Console.Write(RankNo & " ")
For FileNo = 1 To BoardDimension
Console.Write("|" & Board(RankNo, FileNo))
Next
Console.WriteLine("|")
Next
Console.WriteLine(" _____________________________") ' Added 3 more underscores
Console.WriteLine()
Console.WriteLine(" 1 2 3 4 5 6 7 8 9") ' Added a 9 here (for additional file)
Console.WriteLine()
Console.WriteLine()
End Sub
Sub InitialiseBoard(ByRef Board(,) As String, ByVal SampleGame As Char)
Dim Square, Count As Integer
Dim Piece, Colour As Char
Dim RankNo As Integer
Dim FileNo As Integer
If SampleGame = "Y" Then
' ... (Sample game setup)
Else
For RankNo = 1 To BoardDimension - 1 ' As seen above, this keeps the No. of ranks to 8/original number in this case.
For FileNo = 1 To BoardDimension
If RankNo = 2 Then
Board(RankNo, FileNo) = "BR"
ElseIf RankNo = 7 Then
Board(RankNo, FileNo) = "WR"
ElseIf RankNo = 1 Or RankNo = 8 Then
If RankNo = 1 Then Board(RankNo, FileNo) = "B"
If RankNo = 8 Then Board(RankNo, FileNo) = "W"
Select Case FileNo
Case 1, BoardDimension '9
Board(RankNo, FileNo) = Board(RankNo, FileNo) & "G"
Case 2, BoardDimension - 1 '8
Board(RankNo, FileNo) = Board(RankNo, FileNo) & "E"
Case 3, BoardDimension - 2 '7
Board(RankNo, FileNo) = Board(RankNo, FileNo) & "N"
Case 4
Board(RankNo, FileNo) = Board(RankNo, FileNo) & "M"
Case 5
Board(RankNo, FileNo) = Board(RankNo, FileNo) & "S"
Case 6
Board(RankNo, FileNo) = Board(RankNo, FileNo) & "K"
End Select
Else
Board(RankNo, FileNo) = " "
End If
Next
Next
End If
End Sub
' If you want to include the Kashshaptu:
' Edit the general move checker:
Function CheckMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer '...
Dim PieceType As Char
Dim PieceColour As Char
'...
Select Case PieceType
'...
Case "K"
Return CheckKashshaptuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile)
Case Else
Return False
End Select
End Function
' Add a Kashshaptu move checker: (Mine just lets the witch move wherever it wishes to go...kinda spooky huh?) edit this will let you immediately take the other players sarrum so fix it plz u newb
Function CheckKashshaptuMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer) As Boolean
If Abs(FinishFile - StartFile) < BoardDimension And Abs(FinishRank - StartRank) < BoardDimension Then ' Can move anywhere on the board.
Return True
End If
Return False
End Function
Python Solution
Answer:
BOARDDIMENSION = 9
#Change variable "BOARDDIMENSION" to match the length and width of the playing board.
def DisplayBoard(Board):
print()
for RankNo in range(1, BOARDDIMENSION + 1):
print(" _______________________")
print(RankNo, end=" ")
for FileNo in range(1, BOARDDIMENSION + 1):
print("|" + Board[RankNo][FileNo], end="")
print("|")
print(" __________________________")#Increase number of underscores.
print()
print(" 1 2 3 4 5 6 7 8 9")#Increase number of files to equal "BOARDDIMENSION".
print()
print()
def InitialiseBoard(Board, SampleGame):
if SampleGame == "Y":
for RankNo in range(1, BOARDDIMENSION + 1):
for FileNo in range(1, BOARDDIMENSION + 1):
Board[RankNo][FileNo] = " "
Board[1][2] = "BG"
Board[1][4] = "BS"
Board[1][8] = "WG"
Board[2][1] = "WR"
Board[3][1] = "WS"
Board[3][2] = "BE"
Board[3][8] = "BE"
Board[6][8] = "BR"
else:
for RankNo in range(1, BOARDDIMENSION + 1):
for FileNo in range(1, BOARDDIMENSION + 1):
if RankNo == 2:
Board[RankNo][FileNo] = "BR"
elif RankNo == 8: #Move the white redum pieces down one rank.
Board[RankNo][FileNo] = "WR"
elif RankNo == 1 or RankNo == 9:
if RankNo == 1:
Board[RankNo][FileNo] = "B"
if RankNo == 9:
Board[RankNo][FileNo] = "W"
if FileNo == 1 or FileNo == 8:
Board[RankNo][FileNo] = Board[RankNo][FileNo] + "G"
elif FileNo == 2 or FileNo == 7:
Board[RankNo][FileNo] = Board[RankNo][FileNo] + "E"
elif FileNo == 3 or FileNo == 6:
Board[RankNo][FileNo] = Board[RankNo][FileNo] + "N"
elif FileNo == 4:
Board[RankNo][FileNo] = Board[RankNo][FileNo] + "M"
elif FileNo == 5:
Board[RankNo][FileNo] = Board[RankNo][FileNo] + "S"
elif FileNo == 9: #Add a piece on the 9th file, in this case a 'K' so there is not a blank tile.
Board[RankNo][FileNo] = Board[RankNo][FileNo] + "K" #The 'K' piece can be exchanged for any other piece.
else:
Board[RankNo][FileNo] = " "
Java Solution
Answer:
void displayBoard(String[][] board) {
/*
*
* To make board bigger just modify BOARD_DIMENSION to the value you want.
* And add pieces to the initialised board so the format is not changed
*
*/
int rankNo;
int fileNo;
console.println();
for (rankNo = 1; rankNo <= BOARD_DIMENSION; rankNo++) {
// extend the "___________" divider
console.print(" ");
for (fileNo = 1; fileNo <= BOARD_DIMENSION; fileNo++) {
console.print("___");
}
console.println("");
//
//format for 2 digit numbers
if(rankNo < 10)console.print(rankNo + " ");
else console.print(rankNo + " ");
//
for (fileNo = 1; fileNo <= BOARD_DIMENSION; fileNo++) {
console.print("|" + board[rankNo][fileNo]);
}
console.println("|");
}
//repeating the add divider
console.print(" ");
for (fileNo = 1; fileNo <= BOARD_DIMENSION; fileNo++) {
console.print("___");
}
console.println();
//
// Add numbers to the end
console.print(" ");
for (fileNo = 1; fileNo <= BOARD_DIMENSION; fileNo++) {
console.print(fileNo + " ");
}
//
console.println();
console.println();
}
^_^ Reading School
Pascal Solution
Answer:
C# Solution
Answer:
Create two new constants:
public const int BoardFileDimension = x;
public const int BoardRankDimensions= x;
Change all the references from BoardDimension to the appropriate new constant, there are 8 in total in the following methods:
static void Main(string[] args)
public static void DisplayBoard(string[,] Board)
public static void InitialiseBoard(ref string[,] Board, char SampleGame)
Lastly, you need to add to the underscores in DisplayBoard and add the new rank and file numbers.
//UTC Reading
VB6.0 Solution
Answer:
Add a point scoring system
[edit | edit source]Give players a score based on how many pieces they have taken. Additionally give each piece taken its own unique score. Display the score on the players move and display both scores at the end of the game.
VB.Net solution
Answer:
Sub Main()
'...
Do
DisplayBoard(Board)
DisplayWhoseTurnItIs(WhoseTurn)
ScoreCount(Board, WhoseTurn)
MoveIsLegal = False
'...
'...
Loop Until GameOver
ScoreCount(Board, "B")
ScoreCount(Board, "W")
Console.Write("Do you want to play again (enter Y for Yes)? ")
PlayAgain = Console.ReadLine
'...
End Sub
Sub ScoreCount(ByRef Board(,) As String, ByRef WhoseTurn As Char)
Dim BScore, WScore As Integer
'1 point for Reddum's
'5 for Gisgigir
'7 for Etlu
'6 for Nabu
'8 for Marzaz Pani
'10 for Sarrum
BScore = 62
WScore = 62
If WhoseTurn = "B" Then
For RankNo = 1 To 8
For FileNo = 1 To 8
If Board(RankNo, FileNo) = "WR" Then
BScore = BScore - 1
ElseIf Board(RankNo, FileNo) = "WS" Then
BScore = BScore - 10
ElseIf Board(RankNo, FileNo) = "WM" Then
BScore = BScore - 8
ElseIf Board(RankNo, FileNo) = "WE" Then
BScore = BScore - 7
ElseIf Board(RankNo, FileNo) = "WG" Then
BScore = BScore - 5
ElseIf Board(RankNo, FileNo) = "WN" Then
BScore = BScore - 6
End If
Next
Next
Console.WriteLine("Black's Score: " & BScore)
ElseIf WhoseTurn = "W" Then
For RankNo = 1 To 8
For FileNo = 1 To 8
If Board(RankNo, FileNo) = "BR" Then
WScore = WScore - 1
ElseIf Board(RankNo, FileNo) = "BS" Then
WScore = WScore - 10
ElseIf Board(RankNo, FileNo) = "BM" Then
WScore = WScore - 8
ElseIf Board(RankNo, FileNo) = "BE" Then
WScore = WScore - 7
ElseIf Board(RankNo, FileNo) = "BG" Then
WScore = WScore - 5
ElseIf Board(RankNo, FileNo) = "BN" Then
WScore = WScore - 6
End If
Next
Next
Console.WriteLine("White's Score: " & WScore)
End If
End Sub
[By TheHarshKnight aka ThunderThighs x]
Python Solution
Answer:
def MakeMove(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn, WhitePoints, BlackPoints):
PieceList = ["R","E","G","N","M","S"]
#WhitePoints and BlackPoints are defined above CreateBoard in the main body
if WhoseTurn == "W" and Board[FinishRank][FinishFile][0] == "B":
for Count in range(len(PieceList)):
if Board[FinishRank][FinishFile][1] == PieceList[Count]:
WhitePoints += (Count+1)
print("White has taken",Board[FinishRank][FinishFile])
print("White has",WhitePoints,"points")
break
elif WhoseTurn == "B" and Board[FinishRank][FinishFile][0] == "W":
for Count in range(len(PieceList)):
if Board[FinishRank][FinishFile][1] == PieceList[Count]:
BlackPoints += (Count+1)
print("Black has taken",Board[FinishRank][FinishFile])
print("Black has",BlackPoints,"points")
break
if WhoseTurn == "W" and FinishRank == 1 and Board[StartRank][StartFile][1] == "R":
Board[FinishRank][FinishFile] = "WM"
Board[StartRank][StartFile] = " "
elif WhoseTurn == "B" and FinishRank == 8 and Board[StartRank][StartFile][1] == "R":
Board[FinishRank][FinishFile] = "BM"
Board[StartRank][StartFile] = " "
else:
Board[FinishRank][FinishFile] = Board[StartRank][StartFile]
Board[StartRank][StartFile] = " "
#Nathan Greenwood - Python 3.4
Java Solution
Answer:
//make move edit
int makeMove(String[][] board, int startRank, int startFile, int finishRank, int finishFile, char whoseTurn) {
int score = 0;
if ((whoseTurn == 'W') && (finishRank == 1) && (board[startRank][startFile].charAt(1) == 'R')) {
board[finishRank][finishFile] = "WM";
board[startRank][startFile] = " ";
} else {
if ((whoseTurn == 'B') && (finishRank == 8) && (board[startRank][startFile].charAt(1) == 'R')) {
board[finishRank][finishFile] = "BM";
board[startRank][startFile] = " ";
} else {
switch(board[finishRank][finishFile].charAt(1)){
case 'R': score = 1;
break;
case 'G': score = 2;
break;
case 'E': score = 3;
break;
case 'N': score = 4;
break;
case 'M': score = 5;
break;
default : score = 6;
}
board[finishRank][finishFile] = board[startRank][startFile];
board[startRank][startFile] = " ";
}
}
return score;
}
//main edit
String[][] board = new String[BOARD_DIMENSION + 1][BOARD_DIMENSION + 1];
boolean gameOver;
int startSquare = 0;
int finishSquare = 0;
int startRank = 0;
int startFile = 0;
int finishRank = 0;
int finishFile = 0;
boolean moveIsLegal;
char playAgain;
char sampleGame;
char whoseTurn;
Position startPosition = new Position();
Position finishPosition = new Position();
playAgain = 'Y';
do {
whoseTurn = 'W';
gameOver = false;
console.print("Do you want to play the sample game (enter Y for Yes)? ");
sampleGame = console.readChar();
if ((int)sampleGame >= 97 && (int)sampleGame <= 122) {
sampleGame = (char)((int)sampleGame - 32);
}
initialiseBoard(board, sampleGame);
do {
displayBoard(board);
displayWhoseTurnItIs(whoseTurn);
moveIsLegal = false;
do {
if (whoseTurn == 'W') {
console.print("Your Score is "+ whitescore);
} else {
console.print("Your Score is "+ blackscore);
}
getMove(startPosition, finishPosition);
startSquare = startPosition.coordinates;
finishSquare = finishPosition.coordinates;
startRank = startSquare % 10;
startFile = startSquare / 10;
finishRank = finishSquare % 10;
finishFile = finishSquare / 10;
moveIsLegal = checkMoveIsLegal(board, startRank, startFile, finishRank, finishFile, whoseTurn);
if (!moveIsLegal) {
console.println("That is not a legal move - please try again");
}
} while (!moveIsLegal);
gameOver = checkIfGameWillBeWon(board, finishRank, finishFile);
if (whoseTurn == 'W') {
whitescore += makeMove(board, startRank, startFile, finishRank, finishFile, whoseTurn);
} else {
blackscore += makeMove(board, startRank, startFile, finishRank, finishFile, whoseTurn);
}
if (gameOver) {
displayWinner(whoseTurn);
console.print("White score "+ whitescore);
console.print("Black score "+ blackscore);
}
if (whoseTurn == 'W') {
whoseTurn = 'B';
} else {
whoseTurn = 'W';
}
} while (!gameOver);
console.print("Do you want to play again (enter Y for Yes)? ");
playAgain = console.readChar();
if ((int)playAgain > 97 && (int)playAgain <= 122) {
playAgain = (char)((int)playAgain - 32);
}
} while (playAgain == 'Y');
}
// ^_^ Reading School
Pascal Solution
Answer:
//WhiteScore and BlackScore are both global integers.
Procedure ScoreCount(Board:TBoard;WhoseTurn:Char;FinishRank,FinishFile:Integer); //called in main program after a legal move is entered.
begin
If WhoseTurn='W'
then
begin
case Board[FinishRank,FinishFile][2] of
'G':WhiteScore:=WhiteScore+50;
'S':WhiteScore:=WhiteScore+100;
'R':WhiteScore:=WhiteScore+5;
'E':WhiteScore:=WhiteScore+15;
'M':WhiteScore:=WhiteScore+70;
'N':WhiteScore:=WhiteScore+20;
end;
end
else
begin
case Board[FinishRank,FinishFile][2] of
'G':BlackScore:=BlackScore+50;
'S':BlackScore:=BlackScore+100;
'R':BlackScore:=BlackScore+5;
'E':BlackScore:=BlackScore+15;
'M':BlackScore:=BlackScore+70;
'N':BlackScore:=BlackScore+20;
end;
end;
end;
Procedure DisplayWhoseTurnItIs(WhoseTurn : Char);
Begin
If WhoseTurn = 'W'
Then Writeln('It is White''s turn White has ',WhiteScore,' points')
Else Writeln('It is Black''s turn Black has ',BlackScore,' points');
End;
Procedure DisplayWinner(WhoseTurn : Char);
Begin
writeln;
If WhoseTurn = 'W'
Then
begin
Writeln('Black''s Sarrum has been captured. White wins with ',WhiteScore,' points!');
writeln('Black had ',BlackScore,' points');
end
Else
begin
Writeln('White''s Sarrum has been captured. Black wins with ',BlackScore,' points!');
writeln('White had ',WhiteScore,' points');
end;
Writeln;
End;
C# Solution
Answer:
VB6.0 Solution
Answer:
Allow the Redum to perform an 'en passant' move
[edit | edit source]En passant "is a special pawn capture, that can only occur immediately after a pawn moves two ranks forward from its starting position, and an enemy pawn could have captured it had the pawn moved only one square forward". The program code could be adapted to allow Redums to use such a move.
VB.Net solution
Answer:
Python Solution
Answer:
Java Solution
Answer:
Pascal Solution
Answer:
// enPassant is a global variable (integer)
Function CheckRedumMoveIsLegal(Var Board : TBoard; StartRank, StartFile, FinishRank, FinishFile : Integer;
ColourOfPiece : Char) : Boolean;
Begin
CheckRedumMoveIsLegal := False;
If ColourOfPiece = 'W'
Then
Begin
If FinishRank = StartRank - 1
Then
Begin
If (FinishFile = StartFile) And (Board[FinishRank, FinishFile] = ' ')
Then CheckRedumMoveIsLegal := True
Else
Begin
If (Abs(FinishFile - StartFile) = 1) And
(Board[FinishRank, FinishFile][1] = 'B')
Then CheckRedumMoveIsLegal := True;
{ New en Passant code - White }
If (Abs(FinishFile - StartFile) = 1) and ((enPassant div 10) = finishFile) and ((enpassant mod 10)= startRank)
Then
begin
CheckRedumMoveIsLegal := True;
board[enPassant mod 10,enPassant div 10] := ' ';
end;
End
End;
{ new double move code - white }
If (finishRank = startRank - 2) and (startRank = 7) and (board[finishRank, finishFile] = ' ')
Then
begin
CheckRedumMoveIsLegal := True;
enPassant := finishFile*10 + finishRank // saves the position of the piece that can be taken with en passant
end
else enPassant := 0; // blanks it if no pieces
End
Else
Begin
If FinishRank = StartRank + 1
Then
Begin
If (FinishFile = StartFile) And (Board[FinishRank, FinishFile] = ' ')
Then CheckRedumMoveIsLegal := True
Else
Begin
If (Abs(FinishFile - StartFile) = 1) And
(Board[FinishRank, FinishFile][1] = 'W')
Then
begin
CheckRedumMoveIsLegal := True;
end;
{ New en Passant code - black }
If (Abs(FinishFile - StartFile) = 1) and ((enPassant div 10) = finishFile) and ((enpassant mod 10)= startRank)
Then
begin
CheckRedumMoveIsLegal := True;
board[enPassant mod 10,enPassant div 10] := ' ';
end;
End
End;
{ new double move code - black }
If (finishRank = startRank + 2) and (startRank = 2) and (board[finishRank, finishFile] = ' ')
Then
begin
CheckRedumMoveIsLegal := True;
enPassant := finishFile*10 + finishRank // saves the position of the piece that can be taken with en passant
end
else enPassant := 0; // blanks it if no pieces
End;
End;
C# Solution
Answer:
//Leviathan
static void Main(string[] args)
{
//Seems long winded. Included the entire subroutine to show which ones were changed.
string[,] Board = new string[BoardDimension + 1, BoardDimension + 1];
Boolean GameOver;
int StartSquare = 0;
int FinishSquare = 0;
int StartRank = 0;
int StartFile = 0;
int FinishRank = 0;
int FinishFile = 0;
int LastMoveRank = 0;//
int LastMoveFile = 0;//here i have two variables to save the last move
Boolean MoveIsLegal;
char PlayAgain;
char SampleGame;
char WhoseTurn;
PlayAgain = 'Y';
do
{
WhoseTurn = 'W';
GameOver = false;
Console.Write("Do you want to play the sample game (enter Y for Yes)? ");
SampleGame = char.Parse(Console.ReadLine());
if ((int)SampleGame >= 97 && (int)SampleGame <= 122)
SampleGame = (char)((int)SampleGame - 32);
InitialiseBoard(ref Board, SampleGame);
do
{
DisplayBoard(Board);
DisplayWhoseTurnItIs(WhoseTurn);
MoveIsLegal = false;
do
{
GetMove(ref StartSquare, ref FinishSquare);
StartRank = StartSquare % 10;
StartFile = StartSquare / 10;
FinishRank = FinishSquare % 10;
FinishFile = FinishSquare / 10;
MoveIsLegal = CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn, LastMoveFile, LastMoveRank);//Sends LM Variables (Last Move) into MoveIsLegal
if (!MoveIsLegal)
Console.WriteLine("That is not a legal move - please try again");
} while (!MoveIsLegal);
GameOver = CheckIfGameWillBeWon(Board, FinishRank, FinishFile);
MakeMove(ref Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn);
if (GameOver)
DisplayWinner(WhoseTurn);
if (WhoseTurn == 'W')
WhoseTurn = 'B';
else
WhoseTurn = 'W';
LastMoveFile = FinishFile;//
LastMoveRank = FinishRank;//this sets the variables and puts them on the board using WriteLine. WriteLine is not needed, i just use it as a check
Console.WriteLine(LastMoveFile);//
Console.WriteLine(LastMoveRank);//
} while (!GameOver);
Console.Write("Do you want to play again (enter Y for Yes)? ");
PlayAgain = char.Parse(Console.ReadLine());
if ((int)PlayAgain > 97 && (int)PlayAgain <= 122)
PlayAgain = (char)((int)PlayAgain - 32);
} while (PlayAgain == 'Y');
}
-----------------------------------------------------------------
public static Boolean CheckRedumMoveIsLegal(string[,] Board, int StartRank, int StartFile, int FinishRank, int FinishFile, char ColourOfPiece, int LastMoveFile, int LastMoveRank)//Here
{
Boolean RedumMoveIsLegal = false;
if (ColourOfPiece == 'W')
{
if ((FinishFile == LastMoveFile)&&(FinishRank == LastMoveRank))
RedumMoveIsLegal = true;
else if ((FinishFile == LastMoveFile) && (FinishRank == LastMoveRank))
RedumMoveIsLegal = true;//Here is the white check
if (FinishRank == StartRank - 1)
if ((FinishFile == StartFile) && (Board[FinishRank, FinishFile] == " "))
RedumMoveIsLegal = true;
else
if ((Math.Abs(FinishFile - StartFile) == 1) && (Board[FinishRank, FinishFile][0] == 'B'))
RedumMoveIsLegal = true;
}
else
{
if ((FinishFile == LastMoveFile) && (FinishRank == LastMoveRank))
RedumMoveIsLegal = true;
else if ((FinishFile == LastMoveFile) && (FinishRank == LastMoveRank))
RedumMoveIsLegal = true;//Here is the Black check
if (FinishRank == StartRank + 1)
if ((FinishFile == StartFile) && (Board[FinishRank, FinishFile] == " "))
RedumMoveIsLegal = true;
else
if ((Math.Abs(FinishFile - StartFile) == 1) && (Board[FinishRank, FinishFile][0] == 'W'))
RedumMoveIsLegal = true;
}
return RedumMoveIsLegal;
}
-----------------------------------------------------------------
public static Boolean CheckMoveIsLegal(string[,] Board, int StartRank, int StartFile, int FinishRank, int FinishFile, char WhoseTurn, int LastMoveFile, int LastMoveRank)//Here
{
char PieceType;
char PieceColour;
Boolean MoveIsLegal = true;
if ((FinishFile == StartFile) && (FinishRank == StartRank))
MoveIsLegal = false;
PieceType = Board[StartRank, StartFile][1];
PieceColour = Board[StartRank, StartFile][0];
if (WhoseTurn == 'W')
{
if (PieceColour != 'W')
MoveIsLegal = false;
if (Board[FinishRank, FinishFile][0] == 'W')
MoveIsLegal = false;
}
else
{
if (PieceColour != 'B')
MoveIsLegal = false;
if (Board[FinishRank, FinishFile][0] == 'B')
MoveIsLegal = false;
}
if (MoveIsLegal)
switch (PieceType)
{
case 'R':
MoveIsLegal = CheckRedumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, PieceColour, LastMoveFile, LastMoveRank);//Here
break;
case 'S':
MoveIsLegal = CheckSarrumMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
case 'M':
MoveIsLegal = CheckMarzazPaniMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
case 'G':
MoveIsLegal = CheckGisgigirMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
case 'N':
MoveIsLegal = CheckNabuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
case 'E':
MoveIsLegal = CheckEtluMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile);
break;
default:
MoveIsLegal = false;
break;
}
return MoveIsLegal;
}
-----------------------------------------------------------------
VB6.0 Solution
Answer:
Only allow the user to enter one character when choosing the type of game
[edit | edit source]Currently, when the user is able to choose the type of game they are able to enter multiple characters, this should be limited to one character excluding numbers
VB.Net solution
Answer:
'This problem does not apply for VB.Net: The SampleGame variable is already assigned as a charater
Python Solution
Answer:
def GetTypeOfGame():
TypeOfGame = input("Do you want to play the sample game [y|n]? ")
while TypeOfGame.upper() not in ("Y","N"):
TypeOfGame = input("Do you want to play the sample game [y|n]? ")
return TypeOfGame
or
def GetTypeOfGame():
TypeOfGame = input("Do you want to play the sample game (enter Y for Yes or N for no)? ")
while TypeOfGame != "y" or "Y" or "N" or "n":
TypeOfGame = input("Do you want to play the sample game (enter Y for Yes or N for no)? ")
+
if __name__ == "__main__":
Board = CreateBoard() #0th index not used
StartSquare = 0
FinishSquare = 0
PlayAgain = "Y"
while PlayAgain == "Y":
WhoseTurn = "W"
GameOver = False
SampleGame = input("Do you want to play the sample game (enter Y for Yes or N for no)? ")
while SampleGame != "y" or "Y" or "n" or "N":
SampleGame = input("Do you want to play the sample game (enter Y for Yes or N for no)? ")
if ord(SampleGame) >= 97 and ord(SampleGame) <= 122:
SampleGame = chr(ord(SampleGame) - 32)
InitialiseBoard(Board, SampleGame)
while not(GameOver):
DisplayBoard(Board)
DisplayWhoseTurnItIs(WhoseTurn)
MoveIsLegal = False
while not(MoveIsLegal):
StartSquare, FinishSquare = GetMove(StartSquare, FinishSquare)
StartRank = StartSquare % 10
StartFile = StartSquare // 10
FinishRank = FinishSquare % 10
FinishFile = FinishSquare // 10
MoveIsLegal = CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
if not(MoveIsLegal):
print("That is not a legal move - please try again")
GameOver = CheckIfGameWillBeWon(Board, FinishRank, FinishFile)
MakeMove(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
if GameOver:
DisplayWinner(WhoseTurn)
if WhoseTurn == "W":
WhoseTurn = "B"
else:
WhoseTurn = "W"
PlayAgain = input("Do you want to play again (enter Y for Yes)? ")
if ord(PlayAgain) >= 97 and ord(PlayAgain) <= 122:
PlayAgain = chr(ord(PlayAgain) - 32)
Java Solution
Answer:
console.print("Do you want to play the sample game (enter Y for Yes or N for No )? ");
do {
sampleGame = console.readChar();
System.out.println((int)sampleGame);
if (sampleGame != 'N' && sampleGame != 'Y' && sampleGame != 'y' && sampleGame != 'n') {
console.println("That is not a valid choice please enter either Y or N");
}
} while (sampleGame != 'N' && sampleGame != 'Y' && sampleGame != 'y' && sampleGame != 'n');
if ((int) sampleGame >= 97 && (int) sampleGame <= 122) {
sampleGame = (char) ((int) sampleGame - 32);
Pascal Solution
Answer:
Function GetTypeOfGame : Char;
Var
TypeOfGame : Char;
Begin
repeat
Write('Do you want to play the sample game (enter Y for Yes)? ');
Readln(TypeOfGame);
until (UpperCase(TypeOfGame) = 'Y') OR (UpperCase(TypeOfGame) = 'N');
GetTypeOfGame := TypeOfGame;
End;
C# Solution
Answer:
VB6.0 Solution
Answer:
Allow the user to undo a move
[edit | edit source]Possibly save the game after every move and allow them to load a previous state of the board?
VB.Net solution
Answer:
Sub Main()
Dim Board(BoardDimension, BoardDimension) As String
Dim GameOver As Boolean
Dim StartSquare As Integer
Dim FinishSquare As Integer
Dim StartRank As Integer
Dim StartFile As Integer
Dim FinishRank As Integer
Dim FinishFile As Integer
Dim MoveIsLegal As Boolean
Dim PlayAgain As Char
Dim SampleGame As Char
Dim WhoseTurn As Char
'Dim Board saving arrays
Dim LastBoardLayout(BoardDimension, BoardDimension) As String
PlayAgain = "Y"
Do
WhoseTurn = "W"
GameOver = False
Console.Write("Do you want to play the sample game (enter Y for Yes)? ")
SampleGame = Console.ReadLine
If Asc(SampleGame) >= 97 And Asc(SampleGame) <= 122 Then
SampleGame = Chr(Asc(SampleGame) - 32)
End If
InitialiseBoard(Board, SampleGame)
Do
DisplayBoard(Board)
DisplayWhoseTurnItIs(WhoseTurn)
MoveIsLegal = False
Do
GetMove(StartSquare, FinishSquare)
StartRank = StartSquare Mod 10
StartFile = StartSquare \ 10
FinishRank = FinishSquare Mod 10
FinishFile = FinishSquare \ 10
MoveIsLegal = CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
If Not MoveIsLegal Then
Console.WriteLine("That is not a legal move - please try again")
End If
Loop Until MoveIsLegal
GameOver = CheckIfGameWillBeWon(Board, FinishRank, FinishFile)
'Assigning the current board variable to lastboardlayout.
SaveBoard(Board, LastBoardLayout)
MakeMove(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
'Redrawing the board so the previous move is visible.
DisplayBoard(Board)
If GameOver Then
DisplayWinner(WhoseTurn)
End If
'Asking the user if they want to undo their last move.
Console.WriteLine("Would you like to undo your last move?")
Dim shouldUndo As String = Console.ReadLine()
If shouldUndo = "y" Then
Board = LastBoardLayout
Else
If WhoseTurn = "W" Then
WhoseTurn = "B"
Else
WhoseTurn = "W"
End If
End If
Loop Until GameOver
Console.Write("Do you want to play again (enter Y for Yes)? ")
PlayAgain = Console.ReadLine
If Asc(PlayAgain) >= 97 And Asc(PlayAgain) <= 122 Then
PlayAgain = Chr(Asc(PlayAgain) - 32)
End If
Loop Until PlayAgain <> "Y"
End Sub
'Save Board Sub
Sub SaveBoard(ByVal Board(,) As String, ByRef LastBoardLayout(,) As String)
'.Clone stops the variable constantly equaling Board().
LastBoardLayout = Board.Clone
End Sub
'Dan Evans - AS Level
'edited Stephen Lunn
Python Solution
Answer:
Java Solution
Answer:
public Main() {
String[][] board = new String[BOARD_DIMENSION + 1][BOARD_DIMENSION + 1];
//Edit Variables
String[][] saved_board = new String[BOARD_DIMENSION + 1][BOARD_DIMENSION + 1];
char move;
//
boolean gameOver;
int startSquare = 0;
int finishSquare = 0;
int startRank = 0;
int startFile = 0;
int finishRank = 0;
int finishFile = 0;
boolean moveIsLegal;
char playAgain;
char sampleGame;
char whoseTurn;
Position startPosition = new Position();
Position finishPosition = new Position();
playAgain = 'Y';
do {
whoseTurn = 'W';
gameOver = false;
console.print("Do you want to play the sample game (enter Y for Yes)? ");
sampleGame = console.readChar();
if ((int)sampleGame >= 97 && (int)sampleGame <= 122) {
sampleGame = (char)((int)sampleGame - 32);
}
initialiseBoard(board, sampleGame);
do {
displayBoard(board);
displayWhoseTurnItIs(whoseTurn);
moveIsLegal = false;
do {
getMove(startPosition, finishPosition);
startSquare = startPosition.coordinates;
finishSquare = finishPosition.coordinates;
startRank = startSquare % 10;
startFile = startSquare / 10;
finishRank = finishSquare % 10;
finishFile = finishSquare / 10;
moveIsLegal = checkMoveIsLegal(board, startRank, startFile, finishRank, finishFile, whoseTurn);
if (!moveIsLegal) {
console.println("That is not a legal move - please try again");
}
} while (!moveIsLegal);
gameOver = checkIfGameWillBeWon(board, finishRank, finishFile);
for(int x = 0; x < BOARD_DIMENSION + 1;x++){
for(int y = 0; y < BOARD_DIMENSION + 1;y++){
saved_board[x][y] = board[x][y];
}
}
// Edit starts
makeMove(board, startRank, startFile, finishRank, finishFile, whoseTurn);
displayBoard(board);
console.println("Undomove? Y/N");
move = console.readChar();
if(move == 'Y'){
for(int x = 0; x < BOARD_DIMENSION + 1;x++){
for(int y = 0; y < BOARD_DIMENSION + 1;y++){
board[x][y] = saved_board[x][y];
}
}
if (whoseTurn == 'W') {
whoseTurn = 'B';
} else {
whoseTurn = 'W';
}
console.println("Move undid");
displayBoard(board);
}
//edit ends
if (gameOver) {
displayWinner(whoseTurn);
}
if (whoseTurn == 'W') {
whoseTurn = 'B';
} else {
whoseTurn = 'W';
}
} while (!gameOver);
console.print("Do you want to play again (enter Y for Yes)? ");
playAgain = console.readChar();
if ((int)playAgain > 97 && (int)playAgain <= 122) {
playAgain = (char)((int)playAgain - 32);
}
} while (playAgain == 'Y');
}
^_^ Reading_School
Pascal Solution
Answer:
Procedure UndoMove (Var Board:Tboard);
var
undo:char;
begin
Write('Do you want undo your move? (Enter Y for yes)');
Readln(undo);
If (Ord(undo) >= 97) and (Ord(undo) <= 122)
Then undo := Chr(Ord(undo) - 32);
if undo='Y' then
begin
Board[StartRank, StartFile]:=Board[FinishRank, FinishFile];
Board[FinishRank, FinishFile]:=temp;
end;
If WhoseTurn = 'W'
Then WhoseTurn := 'B'
Else WhoseTurn := 'W';
end;
//Call this procedure after the Whose turn change in the main code otherwise it won't work properly
//Daz u faget
//#420dankmemescantmeltstealbeams
C# Solution
Answer:
VB6.0 Solution
Answer:
Prevent the program from crashing when enter is pressed without any input
[edit | edit source]VB.Net solution
Answer:
Sub Getmove(ByRef StartSquare As String, ByRef finishSquare As String) ' Edited to stop blank entries
Do
Console.Write("Enter coordinates of square containing piece to move (file first): ")
StartSquare= Console.ReadLine
If StartSquare= "" Then
Console.WriteLine("Not a valid input, please try again.")
Else
StartSquare= CInt(StartSquare)
Exit Do
End If
Loop
Do
Console.Write("Enter coordinates of square to move piece to (file first): ")
FinishSquare = Console.ReadLine
If FinishSquare = "" Then
Console.WriteLine("Not a valid input, please try again.")
Else
FinishSquare = CInt(FinishSquare)
Exit Do
End If
Loop
End Sub
'-jC March '15
Python Solution
Answer:
def GetMove(StartSquare, FinishSquare):
while (True):
StartSquare = input("Enter coordinates of square containing piece to move (file first): ")
if (StartSquare == ""):
print ("Not a valid input, please try again.")
else:
StartSquare = int(StartSquare)
break
while (True):
FinishSquare = input("Enter coordinates of square to move piece to (file first): ")
if (FinishSquare == ""):
print ("Not a valid input, please try again.")
else:
FinishSquare = int(FinishSquare)
break
return StartSquare, FinishSquare
# Python by Graf, feel free to suggest any amendments.
# @Edit: And I mean suggest amendments, don't just delete my code because yours runs 0.0001s faster and has two less A/L signs. Ease of understanding >>> speed.
# For the menu:
if __name__ == "__main__":
Board = CreateBoard() #0th index not used
StartSquare = 0
FinishSquare = 0
PlayAgain = "Y"
while PlayAgain == "Y":
WhoseTurn = "W"
GameOver = False
SampleGame = input("Do you want to play the sample game Y/N? ")
while len(SampleGame) != 1: # checks the selection is not empty or too long
SampleGame = input("Do you want to play the sample game?\nEnter 'Y' for yes, 'N' for no: ") # asks again
if ord(SampleGame) >= 97 and ord(SampleGame) <= 122:
SampleGame = chr(ord(SampleGame) - 32)
InitialiseBoard(Board, SampleGame)
while not(GameOver):
DisplayBoard(Board)
DisplayWhoseTurnItIs(WhoseTurn)
MoveIsLegal = False
while not(MoveIsLegal):
StartSquare, FinishSquare = GetMove(StartSquare, FinishSquare)
StartRank = StartSquare % 10
StartFile = StartSquare // 10
FinishRank = FinishSquare % 10
FinishFile = FinishSquare // 10
MoveIsLegal = CheckMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
if not(MoveIsLegal):
print("That is not a legal move - please try again")
GameOver = CheckIfGameWillBeWon(Board, FinishRank, FinishFile)
MakeMove(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn)
if GameOver:
DisplayWinner(WhoseTurn)
if WhoseTurn == "W":
WhoseTurn = "B"
else:
WhoseTurn = "W"
PlayAgain = input("Do you want to play again (enter Y for Yes)? ")
if ord(PlayAgain) >= 97 and ord(PlayAgain) <= 122:
PlayAgain = chr(ord(PlayAgain) - 32)
# Python 3, by Xsanda
Java Solution
Answer:
void getMove(Position startPosition, Position finishPosition) {
int startLength = 0;
do{
startPosition.coordinates = console.readInteger("Enter cooordinates of square containing piece to move (file first): ");
startLength = (int)(Math.log10(startPosition.coordinates)+1);
}while(startLength<2);
int finishLength = 0;
do{
finishPosition.coordinates = console.readInteger("Enter cooordinates of square to move piece to (file first): ");
finishLength = (int)(Math.log10(finishPosition.coordinates)+1);
}while(finishLength<2);
}
By Sheikh Sonjeet Bin Paul + Emdadul + Grandad(who paid for my computer)
__________________________________________________________________________________________________________________________________________
void getMove(Position startPosition, Position finishPosition) {
do {
startPosition.coordinates = console.readInteger("\nEnter cooordinates of square containing piece to move (file first): ");
console.println("startPosition.coordinates: " + startPosition.coordinates);
//Console statement above was used to find out the 'value' which is passed through the
//program when user presses enter when prompted for coordinates
} while (startPosition.coordinates == -2147483648);
do {
finishPosition.coordinates = console.readInteger("\nEnter cooordinates of square to move piece to (file first): ");
} while (finishPosition.coordinates == -2147483648);
}
'Sanyan Rahman - SJC College
Pascal Solution
Answer:
This covers ensuring input is present for coordinates, that they are numbers and that each digit in the number is valid >0 and <=BoardDimension
Valid:=False;
Write('Enter coordinates of square containing piece to move (file first): ');
//Readln(StartSquare);
readln(Temp1);
Write('Enter coordinates of square to move piece to (file first): ');
//Readln(FinishSquare);
readln(Temp2);
//If two characters in each temp number are between 1 and the Board Dimension
if(temp1<>'') and (temp2<>'')
and(temp1[1]>'0') and (temp1[1]<=inttostr(BoardDimension))
and (temp1[2]>'0') and (temp1[2]<=inttostr(BoardDimension))
and (temp2[1]>'0') and (temp2[1]<=inttostr(BoardDimension))
and (temp2[2]>'0') and (temp2[2]<=inttostr(BoardDimension))then
begin
//then convert the temp numbers to integers
StartSquare:=strtoint(Temp1);
FinishSquare:=strToInt(Temp2);
//set valid to be true
Valid:=True;
end
else
writeln('Must enter something, cannot use characters and zeros are invalid coordinates');
until valid=true;
end;
C# Solution
Answer:
public static void GetMove(ref int StartSquare, ref int FinishSquare)
{
bool ok = true;
do
{
ok = true;
try
{
Console.Write("Enter cooordinates of square containing piece to move (file first): ");
StartSquare = int.Parse(Console.ReadLine());
Console.Write("Enter cooordinates of square to move piece to (file first): ");
FinishSquare = int.Parse(Console.ReadLine());
}
catch (Exception)
{
Console.WriteLine("you must only enter numbers");
ok = false;
}
} while (!ok);
}
VB6.0 Solution
Answer:
Change Colour of pieces
[edit | edit source]Currently the board is in Black and white text, This is difficult to read and understand. Add visible different colours to the pieces to make it easier to distinguish between the two sides.
VB.Net solution
Answer:
'Code courtesy of James Henderson
Sub DisplayBoard(ByVal Board(,) As String)
Dim RankNo As Integer
Dim FileNo As Integer
Console.WriteLine()
For RankNo = 1 To BoardDimension
Console.WriteLine(" _________________________")
Console.Write(RankNo & " ")
For FileNo = 1 To BoardDimension
'EDIT STARTS HERE
'Simple If statement determines ownership of pieces and writes in different colour
'This Example amkes White pieces light blue and black pieces red
Console.Write("|")
If Board(RankNo, FileNo)(0) = "W" Then
'Sets text colour to Cyan
Console.ForegroundColor = ConsoleColor.Cyan
Console.Write(Board(RankNo, FileNo))
'Sets text colour back to white
Console.ForegroundColor = ConsoleColor.White
ElseIf Board(RankNo, FileNo)(0) = "B" Then
'Sets text colour to red
Console.ForegroundColor = ConsoleColor.Red
Console.Write(Board(RankNo, FileNo))
'Sets text colour back to white
Console.ForegroundColor = ConsoleColor.White
'If this elseif is not included the spaces are skipped
ElseIf Board(RankNo, FileNo)(0) = " " Then
Console.Write(Board(RankNo, FileNo))
End If
'EDIT ENDS HERE
Next
Console.WriteLine("|")
Next
Console.WriteLine(" _________________________")
Console.WriteLine()
Console.WriteLine(" 1 2 3 4 5 6 7 8")
Console.WriteLine()
Console.WriteLine()
End Sub
'You can get it to have more chess-like colours by editing the background colour with better grid like lines (by Dominic)
'This goes in the display board part
Console.Clear()
Console.SetWindowSize(Console.WindowWidth, BoardDimension * 2 + 8)
Console.ForegroundColor = ConsoleColor.Black
Console.Write(" ┌")
For count = 0 To BoardDimension - 2
Console.Write("──┬")
Next
Console.Write("──┐")
For RankNo = 0 To BoardDimension - 1
Console.WriteLine()
Console.Write(" " & RankNo & " ")
For FileNo = 0 To BoardDimension - 1
Console.ForegroundColor = ConsoleColor.Black
Console.Write("│")
Console.ForegroundColor = ConsoleColor.Red
If Board(RankNo, FileNo) = "BG" Or Board(RankNo, FileNo) = "BK" Or Board(RankNo, FileNo) = "BR" Or Board(RankNo, FileNo) = "BM" Or Board(RankNo, FileNo) = "BN" Or Board(RankNo, FileNo) = "BE" Or Board(RankNo, FileNo) = "BS" Then
Console.ForegroundColor = ConsoleColor.Black
Console.BackgroundColor = ConsoleColor.Cyan
If (RankNo + FileNo) Mod 2 = 1 Then Console.BackgroundColor = ConsoleColor.Magenta
ElseIf Board(RankNo, FileNo) = "WG" Or Board(RankNo, FileNo) = "WK" Or Board(RankNo, FileNo) = "WR" Or Board(RankNo, FileNo) = "WM" Or Board(RankNo, FileNo) = "WN" Or Board(RankNo, FileNo) = "WE" Or Board(RankNo, FileNo) = "WS" Then
Console.ForegroundColor = ConsoleColor.White
Console.BackgroundColor = ConsoleColor.Blue
If (RankNo + FileNo) Mod 2 = 1 Then Console.BackgroundColor = ConsoleColor.Red
Else
Console.BackgroundColor = ConsoleColor.Black
If (RankNo + FileNo) Mod 2 = 1 Then Console.BackgroundColor = ConsoleColor.White
End If
Console.Write(Board(RankNo, FileNo))
Console.BackgroundColor = ConsoleColor.Gray
Console.ForegroundColor = ConsoleColor.Black
Next
Console.Write("│")
Console.WriteLine()
If RankNo < BoardDimension - 1 Then
Console.Write(" ├")
For count = 0 To BoardDimension - 2
Console.Write("──┼")
Next
Console.Write("──┤")
End If
Next
Console.Write(" └")
For count = 0 To BoardDimension - 2
Console.Write("──┴")
Next
Console.Write("──┘")
Console.WriteLine("")
Console.WriteLine("")
Console.Write(" ")
For counter = 0 To BoardDimension - 1
Console.Write(counter & " ")
Next
Console.WriteLine("")
Python solution
Answer:
#Code courtesy of Luke Kyriacou
###########################Add to top of code##########################
TD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE= -11
STD_ERROR_HANDLE = -12
FOREGROUND_BLUE = 0x01 # text color contains blue.
FOREGROUND_GREEN= 0x02 # text color contains green.
FOREGROUND_RED = 0x04 # text color contains red.
FOREGROUND_INTENSITY = 0x08 # text color is intensified.
BACKGROUND_BLUE = 0x10 # background color contains blue.
BACKGROUND_GREEN= 0x20 # background color contains green.
BACKGROUND_RED = 0x40 # background color contains red.
BACKGROUND_INTENSITY = 0x80 # background color is intensified.
import ctypes
std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
def set_color(color, handle=std_out_handle):
"""(color) -> BOOL
Example: set_color(FOREGROUND_GREEN | FOREGROUND_INTENSITY)
"""
bool = ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)
return bool
#######################################################################
def DisplayBoard(Board):
print
for RankNo in range(1,BOARDDIMENSION + 1):
print " _______________________"
print RankNo, " ",
for FileNo in range(1,BOARDDIMENSION + 1):
if Board[RankNo][FileNo][0] == "W": #Check if white
set_color(FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY) #Set white colour to cyan
elif Board[RankNo][FileNo][0] == "B": #Check if black
set_color(FOREGROUND_RED | FOREGROUND_INTENSITY) #Set black colour to red
print "|" + Board[RankNo][FileNo],
set_color(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY) #Reset colour
sys.stdout.softspace = 0
print "|"
print " _______________________"
print
print " 1 2 3 4 5 6 7 8"
print
print
Change the Etlu to behave like a knight in chess
[edit | edit source]VB.Net solution
Answer:
'Code courtesy of James Henderson
Function CheckEtluMoveIsLegal(ByVal Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer) As Boolean
If (Abs(FinishFile - StartFile) = 1 And Abs(FinishRank - StartRank) = 2) Or (Abs(FinishFile - StartFile) = 2 And Abs(FinishRank - StartRank) = 1) Then
Return True
End If
Return False
End Function
Python Solution
Answer:
def CheckEtluMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile):
CheckEtluMoveIsLegal = False
if (abs(FinishFile - StartFile) == 2 and abs(FinishRank - StartRank) == 1) or (abs(FinishFile - StartFile) == 1 and abs(FinishRank - StartRank) == 2):
CheckEtluMoveIsLegal = True
return CheckEtluMoveIsLegal
# Python 3, by Xsanda
Java Solution
Answer:
boolean checkEtluMoveIsLegal(String[][] board, int startRank, int startFile, int finishRank, int finishFile) {
boolean etluMoveIsLegal = false;
if ((abs(finishFile - startFile) == 2 && abs(finishRank - startRank) == 1) || (abs(finishFile - startFile) == 1 && abs(finishRank - startRank) == 2)) {
etluMoveIsLegal = true;
}
return etluMoveIsLegal;
}
^_^ Reading_School
Pascal Solution
Answer:
Function CheckEtluMoveIsLegal(Var Board : TBoard; StartRank, StartFile, FinishRank, FinishFile : Integer) : Boolean;
Begin
CheckEtluMoveIsLegal := False;
//change to 1 and 2 respectively
If (Abs(FinishFile - StartFile) = 1) And (Abs(FinishRank - StartRank) = 2)
//change to 2 and 1 respectively
Or (Abs(FinishFile - StartFile) = 2) And (Abs(FinishRank - StartRank) = 1)
Then CheckEtluMoveIsLegal := True;
End;
C# Solution
Answer:
public static Boolean CheckEtluMoveIsLegal(string[,] Board, int StartRank, int StartFile, int FinishRank, int FinishFile)
{
Boolean EtluMoveIsLegal = false;
if ((Math.Abs(FinishFile - StartFile) == 2) && (Math.Abs(FinishRank - StartRank) == 1)
|| (Math.Abs(FinishFile - StartFile) == 1) && (Math.Abs(FinishRank - StartRank) == 2))
EtluMoveIsLegal = true;
return EtluMoveIsLegal;
}
// Courtesy of ToxicVerbid
Perhaps add demonstration game to demonstrate a move eg Castling
[edit | edit source]VB.Net
Answer:
Tutorial.tutorial_doTutorialMenu(Board)
Module Tutorial
Public Sub tutorial_doTutorialMenu(ByRef Board(,) As String)
Console.WriteLine("")
Console.WriteLine("Tutorial Menu:")
Console.WriteLine("0. To go back to main menu.")
Console.WriteLine("1. To see castling.")
Console.WriteLine("")
Console.Write("What tutorial would you like: ")
tutorialSelected = Console.ReadLine
Select Case tutorialSelected
Case 0
Console.WriteLine(" ")
Main()
Case 1
Console.WriteLine("You are now viewing the Castling tutorial. Press enter to continue")
Console.ReadLine()
tutorial_castlingTutorial(Board)
Case Else
tutorial_doTutorialMenu(Board)
End Select
End Sub
Public Sub tutorial_DisplayEmptyBoard(ByRef Board(,) As String, ByVal tutorialStage As Single)
For RankNo = 1 To BoardDimension
For FileNo = 1 To BoardDimension
Board(RankNo, FileNo) = " "
Next
Next
Select Case tutorialSelected
Case 1 ' Castling tutorial
Select Case tutorialStage
Case 0 ' Stage 1
Board(8, 5) = "WS"
Board(8, 1) = "WG"
Board(8, 8) = "WG"
Case 1 ' Stage 2
Board(8, 3) = "WS"
Board(8, 4) = "WG"
Board(8, 8) = "WG"
End Select
End Select
DisplayBoard(Board)
End Sub
Public Sub tutorial_castlingTutorial(ByRef Board(,) As String)
tutorial_DisplayEmptyBoard(Board, 0)
Console.WriteLine("Castling involves moving the Sarrum with the Gisgigir towards each other and then swapping them over in one go")
Console.WriteLine("The Sarrum and the Gisgigir can not have moved from their original spaces")
Console.WriteLine("")
Console.WriteLine("In this case we decided to castle the Gisgigir in spot 8, 1 and the Sarrum.")
Console.WriteLine("Press enter to continue to the next stage")
Console.ReadLine()
Console.WriteLine(" ")
Console.WriteLine("Stage 2:")
Console.WriteLine("")
tutorial_DisplayEmptyBoard(Board, 1)
Console.WriteLine("The Sarrum and Gisgigir has now swapped places.")
Console.WriteLine("This move can not be done again.")
Console.WriteLine("")
Console.WriteLine("Press Enter to return back to the tutorial menu.")
Console.ReadLine()
tutorial_doTutorialMenu(Board)
End Sub
' By 12/Co1 at Riddlesdown Collegiate
End Module
Java Solution
Answer:
// Type in C for castling
void initialiseBoard(String[][] board, char sampleGame) {
int rankNo;
int fileNo;
if (sampleGame == 'Y') {
for (rankNo = 1; rankNo <= BOARD_DIMENSION; rankNo++) {
for (fileNo = 1; fileNo <= BOARD_DIMENSION; fileNo++) {
board[rankNo][fileNo] = " ";
}
}
board[1][2] = "BG";
board[1][4] = "BS";
board[1][8] = "WG";
board[2][1] = "WR";
board[3][1] = "WS";
board[3][2] = "BE";
board[3][8] = "BE";
board[6][8] = "BR";
}
else if( sampleGame == 'C' ){
for (rankNo = 1; rankNo <= BOARD_DIMENSION; rankNo++) {
for (fileNo = 1; fileNo <= BOARD_DIMENSION; fileNo++) {
board[rankNo][fileNo] = " ";
}
}
board[8][5] = "WS";
board[8][8] = "WG;
board[8][1] = "WG
board[1][5] = "BS";
}
else {
for (rankNo = 1; rankNo <= BOARD_DIMENSION; rankNo++) {
for (fileNo = 1; fileNo <= BOARD_DIMENSION; fileNo++) {
if (rankNo == 2) {
board[rankNo][fileNo] = "BR";
} else {
if (rankNo == 7) {
board[rankNo][fileNo] = "WR";
} else {
if ((rankNo == 1) || (rankNo == 8)) {
if (rankNo == 1) {
board[rankNo][fileNo] = "B";
}
if (rankNo == 8) {
board[rankNo][fileNo] = "W";
}
switch (fileNo) {
case 1:
case 8:
board[rankNo][fileNo] = board[rankNo][fileNo] + "G";
break;
case 2:
case 7:
board[rankNo][fileNo] = board[rankNo][fileNo] + "E";
break;
case 3:
case 6:
board[rankNo][fileNo] = board[rankNo][fileNo] + "N";
break;
case 4:
board[rankNo][fileNo] = board[rankNo][fileNo] + "M";
break;
case 5:
board[rankNo][fileNo] = board[rankNo][fileNo] + "S";
break;
}
} else {
board[rankNo][fileNo] = " ";
}
}
}
}
}
}
}
^_^ Reading School
Choose what piece the redum is promoted to when it reaches the end of the board
[edit | edit source]VB.Net
Answer:
'The Rayman'
Sub MakeMove(ByRef Board(,) As String, ByVal StartRank As Integer, ByVal StartFile As Integer, ByVal FinishRank As Integer, ByVal FinishFile As Integer, ByVal WhoseTurn As Char)
Dim PieceType As Char
Dim ValidPiece As Boolean = False
If WhoseTurn = "W" And FinishRank = 1 And Board(StartRank, StartFile)(1) = "R" Then
PieceType = " "
Do
Console.Write("Promote redum to piece type: ")
PieceType = Console.ReadLine().ToUpper
If PieceType = "E" Or PieceType = "M" Or PieceType = "N" Or PieceType = "G" Then
ValidPiece = True
Else
Console.WriteLine("That is not a valid piece. Try again")
End If
Loop Until ValidPiece = True
Board(FinishRank, FinishFile) = "W" & PieceType
Board(StartRank, StartFile) = " "
ElseIf WhoseTurn = "B" And FinishRank = 8 And Board(StartRank, StartFile)(1) = "R" Then
PieceType = " "
Do
Console.Write("Promote redum to piece type: ")
PieceType = Console.ReadLine().ToUpper
If PieceType = "E" Or PieceType = "M" Or PieceType = "N" Or PieceType = "G" Then
ValidPiece = True
Else
Console.WriteLine("That is not a valid piece. Try again")
End If
Loop Until ValidPiece = True
Board(FinishRank, FinishFile) = "B" & PieceType
Board(StartRank, StartFile) = " "
Else
Board(FinishRank, FinishFile) = Board(StartRank, StartFile)
Board(StartRank, StartFile) = " "
End If
End Sub
Python
Answer:
'Batman'
def MakeMove(Board, StartRank, StartFile, FinishRank, FinishFile, WhoseTurn):
if WhoseTurn == "W" and FinishRank == 1 and Board[StartRank][StartFile][1] == "R":
pieces = ["M","G","N","E"]
print("What piece would you like to promote the Redum to?")
print("Options - M G N or E")
piece=input()
while piece not in pieces:
print("Invalid change")
print("What piece would you like to promote the Redum to?")
print("Options - M G N or E")
piece=input()
Board[FinishRank][FinishFile] = "W"+piece
Board[StartRank][StartFile] = " "
elif WhoseTurn == "B" and FinishRank == 8 and Board[StartRank][StartFile][1] == "R":
pieces = ["M","G","N","E"]
print("What piece would you like to promote the Redum to?")
print("Options - M G N or E")
piece=input()
while piece not in pieces:
print("Invalid change")
print("What piece would you like to promote the Redum to?")
print("Options - M G N or E")
piece=input()
Board[FinishRank][FinishFile] = "B"+piece
Board[StartRank][StartFile] = " "
else:
Board[FinishRank][FinishFile] = Board[StartRank][StartFile]
Board[StartRank][StartFile] = " "
Make program exit upon a wrong input entered
[edit | edit source]VB.NET Solution
Answer:
Console.Write("To play a Sample Game (Enter S) To play a new game (Enter N) To Quit (Enter Q): ")
GameChoice = Console.ReadLine
If Asc(GameChoice) >= 97 And Asc(GameChoice) <= 122 Then
GameChoice = Chr(Asc(GameChoice) - 32)
End If
If GameChoice = "Q" Or (GameChoice <> "N" And GameChoice <> "S") Then
Environment.Exit(0)
Python Solution
Answer:
def InitialiseBoard(Board, SampleGame):
if SampleGame == "Y": #The sample game is set up if SampleGame equals Y.
for RankNo in range(1, BOARDDIMENSION + 1):
for FileNo in range(1, BOARDDIMENSION + 1):
Board[RankNo][FileNo] = " "
Board[1][2] = "BG"
Board[1][4] = "BS"
Board[1][8] = "WG"
Board[2][1] = "WR"
Board[3][1] = "WS"
Board[3][2] = "BE"
Board[3][8] = "BE"
Board[6][8] = "BR"
if SampleGame == "N": #The standard game is set up if SampleGame equals N.
for RankNo in range(1, BOARDDIMENSION + 1):
for FileNo in range(1, BOARDDIMENSION + 1):
if RankNo == 2:
Board[RankNo][FileNo] = "BR"
elif RankNo == 7:
Board[RankNo][FileNo] = "WR"
elif RankNo == 1 or RankNo == 8:
if RankNo == 1:
Board[RankNo][FileNo] = "B"
if RankNo == 8:
Board[RankNo][FileNo] = "W"
if FileNo == 1 or FileNo == 8:
Board[RankNo][FileNo] = Board[RankNo][FileNo] + "G"
elif FileNo == 2 or FileNo == 7:
Board[RankNo][FileNo] = Board[RankNo][FileNo] + "E"
elif FileNo == 3 or FileNo == 6:
Board[RankNo][FileNo] = Board[RankNo][FileNo] + "N"
elif FileNo == 4:
Board[RankNo][FileNo] = Board[RankNo][FileNo] + "M"
elif FileNo == 5:
Board[RankNo][FileNo] = Board[RankNo][FileNo] + "S"
else:
Board[RankNo][FileNo] = " "
else: #If sample game does not take the value of Y or N then the program will exit.
quit()
Modify the program such that you can play against the computer
[edit | edit source]'Advanced' Solution
Answer:
The code for this solution is too long to post here. It can be found at github with an explanation for the code at Hillsoft Blog. It is also able to win against everyone in my class.
Pascal Solution
Answer:
// Move type
Type
TBoard = Array[1..BoardDimension, 1..BoardDimension] Of String;
Move = Record
StartSquare : Integer;
FinishSquare : Integer;
End;
//
// FindMove() Procedure (Plays first approached aggressive move)
Procedure FindMove;
var sf, sr, ff, fr, moveCount, i, randomMove: integer; moves : Array[0..1000] of Move;
Begin
randomize;
moveCount := 0;
writeln('Black (CPU) is thinking...');
for i:=1 to CountPieces(Board, 'B') do begin
for sr :=1 to BoardDimension do begin
for sf :=1 to BoardDimension do begin
if (Board[sr, sf][1] = 'B') then begin
for fr:=1 to BoardDimension do begin
for ff:=1 to BoardDimension do begin
if CheckMoveIsLegal(Board, sr, sf, fr, ff, 'B') then begin
moves[moveCount].StartSquare := 10*sf+sr;
moves[moveCount].FinishSquare := 10*ff+fr;
moveCount:=moveCount+1
end;
end;
end;
end;
end;
end;
end;
for i:=1 to moveCount-1 do begin
fr := moves[i].FinishSquare Mod 10;
ff := moves[i].FinishSquare Div 10;
if Board[fr, ff][1] = 'W' then begin
StartSquare := moves[i].StartSquare;
FinishSquare := moves[i].FinishSquare;
Exit
end;
end;
randomMove := 1+random(moveCount);
StartSquare := moves[randomMove].StartSquare;
FinishSquare := moves[randomMove].FinishSquare;
End;
//
// Modification at main program body
if (WhoseTurn = 'B') then
FindMove()
else
GetMove(StartSquare, FinishSquare);
//
// You might also want have this is an option in the game menu if applied
// By Tochi, CHS
Java Solution
Answer:
//This is a very simple AI that will make a piece move when it is blacks turn.
//This fix is simple when you lay it out logicallyː when you are playing with another player you must both make a move -
//this is the only part that isn't automated in your program,
//So if you wanted to automate the game and play with the computer all you need to do is automate the coordinate picking process
//as shown below.
void computerGetMove(Position startPosition, Position finishPosition, String[][] board, char colourOfPiece, boolean moveIsLegal, char pieceType) {
Random rand = new Random();
boolean validPosition = true;
int startRank;
int startFile;
int finishRank;
int finishFile;
do {
validPosition = true;
startPosition.coordinates = rand.nextInt(88) + 1;// This creates a random integer between the values of 1 and 88
startRank = startPosition.coordinates % 10;// Modulus is used to find the first number in the two digit value and gets put into startRank
startFile = startPosition.coordinates / 10;// The second digit is then found and put into startFile
if (startRank < 1 || startRank > 8 || startFile < 1 || startFile > 8) {//This if statement checks if the newly initialised startRank
//and startFile are within the board dimensons. If not validPosition is set to false which will make the do-while loop run again.
validPosition = false;
}
} while (validPosition == false);
do {
validPosition = true;
finishPosition.coordinates = rand.nextInt(88) + 1;
finishRank = finishPosition.coordinates % 10;
finishFile = finishPosition.coordinates / 10;
if (finishRank < 1 || finishRank > 8 || finishFile > 8 || finishFile < 1) {
validPosition = false;
}
} while (validPosition == false);// The loop will run while validPosition is false ( This is the case whenever the randomly generated coordinates are
//out of the board dimensions
}
Brad - Halesowen College
{{PAGENAME}}
===Stating which piece has just been captured===
Currently, there is nothing implemented to let the players know which piece has been captured, other than the piece's initials.
VB .NET Solution
{{CPTAnswerTab}}
<syntaxhighlight lang="vbnet">
Java Solution
Answer:
Python Solution
Answer:
Promote Redum to Kashshaptu when it reaches home rank
[edit | edit source]Add the rule that the Redum (Soldier) pieces is promoted to a Kashshaptu (Witch) piece if it reaches the other side of the board from where it stated. The Kashshaptu will then move like the Queen in chess.
Python Solution
Answer:
def CheckKashshaptuMoveIsLegal(Board, StartRank, StartFile, FinishRank, FinishFile): KashshaptuMoveIsLegal = False RankDifference = FinishRank - StartRank FileDifference = FinishFile - StartFile if abs(RankDifference) == abs(FileDifference): KashshaptuMoveIsLegal = True for Count in range(1, FileDifference): if Board[StartRank + Count][StartFile + Count] != " ": KashshaptuMoveIsLegal = False elif FileDifference <= -1: KashshaptuMoveIsLegal = True for Count in range(-1, FileDifference, -1): if Board[StartRank + Count][StartFile + Count] != " ": KashshaptuMoveIsLegal = False elif RankDifference == 0: if FileDifference >= 1: KashshaptuMoveIsLegal = True for Count in range(1, FileDifference): if Board[StartRank][StartFile + Count] != " ": KashshaptuMoveIsLegal = False elif FileDifference <= -1: KashshaptuMoveIsLegal = True for Count in range(-1, FileDifference, -1): if Board[StartRank][StartFile + Count] != " ": KashshaptuMoveIsLegal = False elif FileDifference == 0: if RankDifference >= 1: KashshaptuMoveIsLegal = True for Count in range(1, RankDifference): if Board[StartRank + Count][StartFile] != " ": KashshaptuMoveIsLegal = False elif RankDifference <= -1: KashshaptuMoveIsLegal = True for Count in range(-1, RankDifference, -1): if Board[StartRank + Count][StartFile] != " ": KashshaptuMoveIsLegal = False return KashshaptuMoveIsLegal