A-level Computing/AQA/Problem Solving, Programming, Data Representation and Practical Exercise/Skeleton code/2016 Exam Resit
2016 Old Spec Comp 1: AQA REVERSE ANSWERS!Edit
Please put the question number followed by what your answer was, thanks for contributing. I would also like to thank everyone who, along with me, created this page, very good and had most of the solutions on what came up in the exam.
- Binary number was:
- .
- .
- Hexadecimal number was B4
- .
2016 Old Spec Comp 1: AQA REVERSEEdit
The Skeleton Program accompanying this Preliminary Material is for the board game AQA REVERSE.
AQA REVERSE is a board game in which a human plays against the computer. Each player takes it in turn to make a move by specifying coordinates of where they would like to place one of their pieces – the human player uses pieces labelled "H" and the computer uses pieces labelled "C". A piece can only be put in an empty square on the board.
After a player has put a piece on the board any of the opponent’s pieces that are now trapped, either horizontally or vertically, between the piece just placed and one of the player’s other pieces are flipped – this means that they now change their label (if they were an "H" they become a "C" and vice versa). There must be no empty spaces or other pieces belonging to the player between the two trapping pieces.
The game finishes when every square on the board contains a piece. The winner is the player who has the most pieces on the board at the end of the game. The human player always moves first.
The default board consists of a 6x6 grid of squares.
If you want to communicate I will be able to help:
Contacts:
Answer:
I am one of the contributors to the coding solution, I am a python coder and I can help with any solution.
I can talk about my the solution as pseudo or plain English if it isn't python and a python solution.
My contact is: rad-wane@hotmail.co.uk
Please go to the discussion page at the top of the page to talk.
Note be-careful and aware of the contact you put here
Please contribute to this website as you can see in this link: https://en.wikibooks.org/wiki/A-level_Computing_2009/AQA/Problem_Solving,_Programming,_Data_Representation_and_Practical_Exercise/Skeleton_code/2015_Exam/Section_D
Similar Games:
- Chinese Go is very similar to this game
- The real board game version (called Othello) has these other rules:
- Diagonal capture is allowed (along with horizontal and vertical)
- Pieces can only be placed where flips will occur
- If no flips are possible, the player's turn is skipped.
Potential questions could include:Edit
- A loop for invalid co-ordinates
- To accept both upper case and lower case inputs for Selection Menu
- Saving and Loading (Board layout and whose turn)
- Two player mode
- A tally of scores after match is over
- Ability to change player's initials from H and C
- Starting position of pieces changed
- Computer move may be asked to be modified
- Entering your name before the game starts
- Flip Diagonally
- Only allowing a player to place a piece if it captures opponent piece
- Skip Turn
- (More to follow)
If adding to this list, please provide tangible and measurable changes.
"Changing capture rules" is not a workable idea unless possible changes are also stated.
This is the skeleton program: (Please add to this and make sure it is the full code, mistakes could be costly)Edit
Visual Basic Code:
Answer:
'Skeleton Program code for the AQA COMP1 Summer 2016 examination <br />
'this code should be used in conjunction with the Preliminary Material <br />
'written by the AQA COMP1 Programmer Team <br />
'developed in the Visual Studio 2008 programming environment
Module Module1
Sub Main()
Dim Choice As Char
Dim PlayerName As String
Dim BoardSize As Integer
Randomize()
BoardSize = 6
PlayerName = ""
Do
DisplayMenu()
Choice = GetMenuChoice(PlayerName)
Select Case Choice
Case "p"
PlayGame(PlayerName, BoardSize)
Case "e"
PlayerName = GetPlayersName()
Case "c"
BoardSize = ChangeBoardSize()
End Select
Loop Until Choice = "q"
End Sub
Sub SetUpGameBoard(ByVal Board(,) As Char, ByVal BoardSize As Integer)
Dim Row As Integer
Dim Column As Integer
For Row = 1 To BoardSize
For Column = 1 To BoardSize
If Row = (BoardSize + 1) \ 2 And Column = (BoardSize + 1) \ 2 + 1 Or Column = (BoardSize + 1) \ 2 And Row = (BoardSize + 1) \ 2 + 1 Then
Board(Row, Column) = "C"
ElseIf Row = (BoardSize + 1) \ 2 + 1 And Column = (BoardSize + 1) \ 2 + 1 Or Column = (BoardSize + 1) \ 2 And Row = (BoardSize + 1) \ 2 Then
Board(Row, Column) = "H"
Else
Board(Row, Column) = " "
End If
Next
Next
End Sub
Function ChangeBoardSize() As Integer
Dim BoardSize As Integer
Do
Console.Write("Enter a board size (between 4 and 9): ")
BoardSize = Console.ReadLine
Loop Until BoardSize >= 4 And BoardSize <= 9
Return BoardSize
End Function
Function GetHumanPlayerMove(ByVal PlayerName As String) As Integer
Dim Coordinates As Integer
Console.Write(PlayerName & " enter the coordinates of the square where you want to place your piece: ")
Coordinates = Console.ReadLine
Return Coordinates
End Function
Function GetComputerPlayerMove(ByVal BoardSize As Integer) As Integer
Return (Int(Rnd() * BoardSize) + 1) * 10 + Int(Rnd() * BoardSize) + 1
End Function
Function GameOver(ByVal Board(,) As Char, ByVal BoardSize As Integer) As Boolean
Dim Row As Integer
Dim Column As Integer
For Row = 1 To BoardSize
For Column = 1 To BoardSize
If Board(Row, Column) = " " Then
Return False
End If
Next
Next
Return True
End Function
Function GetPlayersName() As String
Dim PlayerName As String
Console.Write("What is your name? ")
PlayerName = Console.ReadLine
Return PlayerName
End Function
Function CheckIfMoveIsValid(ByVal Board(,) As Char, ByVal Move As Integer) As Boolean
Dim Row As Integer
Dim Column As Integer
Dim MoveIsValid As Boolean
Row = Move Mod 10
Column = Move \ 10
MoveIsValid = False
If Board(Row, Column) = " " Then
MoveIsValid = True
End If
Return MoveIsValid
End Function
Function GetPlayerScore(ByVal Board(,) As Char, ByVal BoardSize As Integer, ByVal Piece As Char) As Integer
Dim Score As Integer
Dim Row As Integer
Dim Column As Integer
Score = 0
For Row = 1 To BoardSize
For Column = 1 To BoardSize
If Board(Row, Column) = Piece Then
Score = Score + 1
End If
Next
Next
Return Score
End Function
Function CheckIfThereArePiecesToFlip(ByVal Board(,) As Char, ByVal BoardSize As Integer, ByVal StartRow As Integer, ByVal StartColumn As Integer, ByVal RowDirection As Integer, ByVal ColumnDirection As Integer) As Boolean
Dim RowCount As Integer
Dim ColumnCount As Integer
Dim FlipStillPossible As Boolean
Dim FlipFound As Boolean
Dim OpponentPieceFound As Boolean
RowCount = StartRow + RowDirection
ColumnCount = StartColumn + ColumnDirection
FlipStillPossible = True
FlipFound = False
OpponentPieceFound = False
While RowCount <= BoardSize And RowCount >= 1 And ColumnCount >= 1 And ColumnCount <= BoardSize And FlipStillPossible And Not FlipFound
If Board(RowCount, ColumnCount) = " " Then
FlipStillPossible = False
ElseIf Board(RowCount, ColumnCount) <> Board(StartRow, StartColumn) Then
OpponentPieceFound = True
ElseIf Board(RowCount, ColumnCount) = Board(StartRow, StartColumn) And Not OpponentPieceFound Then
FlipStillPossible = False
Else
FlipFound = True
End If
RowCount = RowCount + RowDirection
ColumnCount = ColumnCount + ColumnDirection
End While
Return FlipFound
End Function
Sub FlipOpponentPiecesInOneDirection(ByVal Board(,) As Char, ByVal BoardSize As Integer, ByVal StartRow As Integer, ByVal StartColumn As Integer, ByVal RowDirection As Integer, ByVal ColumnDirection As Integer)
Dim RowCount As Integer
Dim ColumnCount As Integer
Dim FlipFound As Boolean
FlipFound = CheckIfThereArePiecesToFlip(Board, BoardSize, StartRow, StartColumn, RowDirection, ColumnDirection)
If FlipFound Then
RowCount = StartRow + RowDirection
ColumnCount = StartColumn + ColumnDirection
While Board(RowCount, ColumnCount) <> " " And Board(RowCount, ColumnCount) <> Board(StartRow, StartColumn)
If Board(RowCount, ColumnCount) = "H" Then
Board(RowCount, ColumnCount) = "C"
Else
Board(RowCount, ColumnCount) = "H"
End If
RowCount = RowCount + RowDirection
ColumnCount = ColumnCount + ColumnDirection
End While
End If
End Sub
Sub MakeMove(ByVal Board(,) As Char, ByVal BoardSize As Integer, ByVal Move As Integer, ByVal HumanPlayersTurn As Boolean)
Dim Row As Integer
Dim Column As Integer
Row = Move Mod 10
Column = Move \ 10
If HumanPlayersTurn Then
Board(Row, Column) = "H"
Else
Board(Row, Column) = "C"
End If
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 1, 0)
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, -1, 0)
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, 1)
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, -1)
End Sub
Sub PrintLine(ByVal BoardSize As Integer)
Dim Count As Integer
Console.Write(" ")
For Count = 1 To BoardSize * 2 - 1
Console.Write("_")
Next
Console.WriteLine()
End Sub
Sub DisplayGameBoard(ByVal Board(,) As Char, ByVal BoardSize As Integer)
Dim Row As Integer
Dim Column As Integer
Console.WriteLine()
Console.Write(" ")
For Column = 1 To BoardSize
Console.Write(" ")
Console.Write(Column)
Next
Console.WriteLine()
PrintLine(BoardSize)
For Row = 1 To BoardSize
Console.Write(Row)
Console.Write(" ")
For Column = 1 To BoardSize
Console.Write("|")
Console.Write(Board(Row, Column))
Next
Console.WriteLine("|")
PrintLine(BoardSize)
Console.WriteLine()
Next
End Sub
Sub DisplayMenu()
Console.WriteLine("(p)lay game")
Console.WriteLine("(e)nter name")
Console.WriteLine("(c)hange board size")
Console.WriteLine("(q)uit")
Console.WriteLine()
End Sub
Function GetMenuChoice(ByVal PlayerName As String) As Char
Dim Choice As Char
Console.Write(PlayerName & " enter the letter of your chosen option: ")
Choice = Console.ReadLine
Return Choice
End Function
Sub PlayGame(ByVal PlayerName As String, ByVal BoardSize As Integer)
Dim Board(BoardSize, BoardSize) As Char
Dim HumanPlayersTurn As Boolean
Dim Move As Integer
Dim HumanPlayerScore As Integer
Dim ComputerPlayerScore As Integer
Dim MoveIsValid As Boolean
SetUpGameBoard(Board, BoardSize)
HumanPlayersTurn = False
Do
HumanPlayersTurn = Not HumanPlayersTurn
DisplayGameBoard(Board, BoardSize)
MoveIsValid = False
Do
If HumanPlayersTurn Then
Move = GetHumanPlayerMove(PlayerName)
Else
Move = GetComputerPlayerMove(BoardSize)
End If
MoveIsValid = CheckIfMoveIsValid(Board, Move)
Loop Until MoveIsValid
If Not HumanPlayersTurn Then
Console.WriteLine("Press the Enter key and the computer will make its move")
Console.ReadLine()
End If
MakeMove(Board, BoardSize, Move, HumanPlayersTurn)
Loop Until GameOver(Board, BoardSize)
DisplayGameBoard(Board, BoardSize)
HumanPlayerScore = GetPlayerScore(Board, BoardSize, "H")
ComputerPlayerScore = GetPlayerScore(Board, BoardSize, "C")
If HumanPlayerScore > ComputerPlayerScore Then
Console.WriteLine("Well done, " & PlayerName & ", you have won the game!")
ElseIf HumanPlayerScore = ComputerPlayerScore Then
Console.WriteLine("That was a draw!")
Else
Console.WriteLine("The computer has won the game!")
End If
Console.WriteLine()
End Sub
End Module
Python Code:
Answer:
#Skeleton Program for the AQA COMP1 Summer 2016 examination
#this code should be used in conjunction with the Preliminary Material
#written by the AQA COMP1 Programmer Team
#developed in a Python 3.4 programming environment
import random
def SetUpGameBoard(Board, Boardsize):
for Row in range(1, BoardSize + 1):
for Column in range(1, BoardSize + 1):
if (Row == (BoardSize + 1) // 2 and Column == (BoardSize + 1) // 2 + 1) or (Column == (BoardSize + 1) // 2 and Row == (BoardSize + 1) // 2 + 1):
Board[Row][Column] = "C"
elif (Row == (BoardSize + 1) // 2 + 1 and Column == (BoardSize + 1) // 2 + 1) or (Column == (BoardSize + 1) // 2 and Row == (BoardSize + 1) // 2):
Board[Row][Column] = "H"
else:
Board[Row][Column] = " "
def ChangeBoardSize():
BoardSize = int(input("Enter a board size (between 4 and 9): "))
while not(BoardSize >= 4 and BoardSize <= 9):
BoardSize = int(input("Enter a board size (between 4 and 9): "))
return BoardSize
def GetHumanPlayerMove(PlayerName):
print(PlayerName, "enter the coodinates of the square where you want to place your piece: ", end="")
Coordinates = int(input())
return Coordinates
def GetComputerPlayerMove(BoardSize):
return random.randint(1, BoardSize) * 10 + random.randint(1, BoardSize)
def GameOver(Board, BoardSize):
for Row in range(1 , BoardSize + 1):
for Column in range(1, BoardSize + 1):
if Board[Row][Column] == " ":
return False
return True
def GetPlayersName():
PlayerName = input("What is your name? ")
return PlayerName
def CheckIfMoveIsValid(Board, Move):
Row = Move % 10
Column = Move // 10
MoveIsValid = False
if Board[Row][Column] == " ":
MoveIsValid = True
return MoveIsValid
def GetPlayerScore(Board, BoardSize, Piece):
Score = 0
for Row in range(1, BoardSize + 1):
for Column in range(1, BoardSize + 1):
if Board[Row][Column] == Piece:
Score = Score + 1
return Score
def CheckIfThereArePiecesToFlip(Board, BoardSize, StartRow, StartColumn, RowDirection, ColumnDirection):
RowCount = StartRow + RowDirection
ColumnCount = StartColumn + ColumnDirection
FlipStillPossible = True
FlipFound = False
OpponentPieceFound = False
while RowCount <= BoardSize and RowCount >= 1 and ColumnCount >= 1 and ColumnCount <= BoardSize and FlipStillPossible and not FlipFound:
if Board[RowCount][ColumnCount] == " ":
FlipStillPossible = False
elif Board[RowCount][ColumnCount] != Board[StartRow][StartColumn]:
OpponentPieceFound = True
elif Board[RowCount][ColumnCount] == Board[StartRow][StartColumn] and not OpponentPieceFound:
FlipStillPossible = False
else:
FlipFound = True
RowCount = RowCount + RowDirection
ColumnCount = ColumnCount + ColumnDirection
return FlipFound
def FlipOpponentPiecesInOneDirection(Board, BoardSize, StartRow, StartColumn, RowDirection, ColumnDirection):
FlipFound = CheckIfThereArePiecesToFlip(Board, BoardSize, StartRow, StartColumn, RowDirection, ColumnDirection)
if FlipFound:
RowCount = StartRow + RowDirection
ColumnCount = StartColumn + ColumnDirection
while Board[RowCount][ColumnCount] != " " and Board[RowCount][ColumnCount] != Board[StartRow][StartColumn]:
if Board[RowCount][ColumnCount] == "H":
Board[RowCount][ColumnCount] = "C"
else:
Board[RowCount][ColumnCount] = "H"
RowCount = RowCount + RowDirection
ColumnCount = ColumnCount + ColumnDirection
def MakeMove(Board, BoardSize, Move, HumanPlayersTurn):
Row = Move % 10
Column = Move // 10
if HumanPlayersTurn:
Board[Row][Column] = "H"
else:
Board[Row][Column] = "C"
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 1, 0)
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, -1, 0)
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, 1)
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, -1)
def PrintLine(BoardSize):
print(" ", end="")
for Count in range(1, BoardSize * 2):
print("_", end="")
print()
def DisplayGameBoard(Board, BoardSize):
print()
print(" ", end="")
for Column in range(1, BoardSize + 1):
print(" ", end="")
print(Column, end="")
print()
PrintLine(BoardSize)
for Row in range(1, BoardSize + 1):
print(Row, end="")
print(" ", end="")
for Column in range(1, BoardSize + 1):
print("|", end="")
print(Board[Row][Column], end="")
print("|")
PrintLine(BoardSize)
print()
def DisplayMenu():
print("(p)lay game")
print("(e)nter name")
print("(c)hange board size")
print("(q)uit")
print()
def GetMenuChoice(PlayerName):
print(PlayerName, "enter the letter of your chosen option: ", end="")
Choice = input()
return Choice
def CreateBoard():
Board = []
for Count in range(BoardSize + 1):
Board.append([])
for Count2 in range(BoardSize + 1):
Board[Count].append("")
return Board
def PlayGame(PlayerName, BoardSize):
Board = CreateBoard()
SetUpGameBoard(Board, BoardSize)
HumanPlayersTurn = False
while not GameOver(Board, BoardSize):
HumanPlayersTurn = not HumanPlayersTurn
DisplayGameBoard(Board, BoardSize)
MoveIsValid = False
while not MoveIsValid:
if HumanPlayersTurn:
Move = GetHumanPlayerMove(PlayerName)
else:
Move = GetComputerPlayerMove(BoardSize)
MoveIsValid = CheckIfMoveIsValid(Board, Move)
if not HumanPlayersTurn:
print("Press the Enter key and the computer will make its move")
input()
MakeMove(Board, BoardSize, Move, HumanPlayersTurn)
DisplayGameBoard(Board, BoardSize)
HumanPlayerScore = GetPlayerScore(Board, BoardSize, "H")
ComputerPlayerScore = GetPlayerScore(Board, BoardSize, "C")
if HumanPlayerScore > ComputerPlayerScore:
print("Well done", PlayerName, ", you have won the game!")
elif HumanPlayerScore == ComputerPlayerScore:
print("That was a draw!")
else:
print("The computer has won the game!")
print()
random.seed()
BoardSize = 6
PlayerName = ""
Choice = ""
while Choice != "q":
DisplayMenu()
Choice = GetMenuChoice(PlayerName)
if Choice == "p":
PlayGame(PlayerName, BoardSize)
elif Choice == "e":
PlayerName = GetPlayersName()
elif Choice == "c":
BoardSize = ChangeBoardSize()
C# Code:
Answer:
// Skeleton Program code for the AQA COMP1 Summer 2016 examination
// this code whould be used in conjunction with the Preliminary Material
// written by the AQA COMP1 Programmer Team
// developed in the Visual Studio 2012 programming environment
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Comp_1_Resit
{
class Program
{
static void Main(string[] args)
{
char Choice;
string PlayerName;
int BoardSize;
BoardSize = 6;
PlayerName = "";
do
{
DisplayMenu();
Choice = GetMenuChoice(PlayerName);
switch (Choice)
{
case 'p':
PlayGame(PlayerName, BoardSize);
break;
case 'e':
PlayerName = GetPlayersName();
break;
case 'c':
BoardSize = ChangeBoardSize();
break;
}
} while (Choice != 'q');
}
static void SetUpGameBoard(char[,] Board, int BoardSize)
{
for (int Row = 1; Row <= BoardSize ; Row++)
{
for (int Column = 1; Column <= BoardSize ; Column++)
{
if (Row == (BoardSize + 1) / 2 && Column == (BoardSize + 1) / 2 + 1 || Column == (BoardSize + 1) / 2 && Row == (BoardSize + 1) / 2 + 1)
{
Board[Row, Column] = 'C';
}
else if (Row == (BoardSize + 1) / 2 + 1 && Column == (BoardSize + 1) / 2 + 1 || Column == (BoardSize + 1) / 2 && Row == (BoardSize + 1) / 2)
{
Board[Row, Column] = 'H';
}
else
{
Board[Row, Column] = ' ';
}
}
}
}
static int ChangeBoardSize()
{
int BoardSize;
do
{
Console.Write("Enter a board size (between 4 and 9): ");
BoardSize = Convert.ToInt32(Console.ReadLine());
} while (BoardSize < 4 || BoardSize > 9);
return BoardSize;
}
static int GetHumanPlayerMove(string PlayerName)
{
int Coordinates;
Console.Write(PlayerName + " enter the coordinates of the square where you want to place your piece: ");
Coordinates = Convert.ToInt32(Console.ReadLine());
return Coordinates;
}
static int GetComputerPlayerMove(int BoardSize)
{
Random RandomNo = new Random();
return RandomNo.Next(1, BoardSize + 1) * 10 + RandomNo.Next(1, BoardSize + 1);
}
static bool GameOver(char[,] Board, int BoardSize)
{
for (int Row = 1; Row <= BoardSize; Row++)
{
for (int Column = 1; Column <= BoardSize; Column++)
{
if (Board[Row,Column] == ' ')
{
return false;
}
}
}
return true;
}
static string GetPlayersName()
{
string PlayerName;
Console.Write("What is your name? ");
PlayerName = Console.ReadLine();
return PlayerName;
}
static bool CheckIfMoveIsValid(char[,] Board, int Move)
{
int Row;
int Column;
bool MoveIsValid;
Row = Move % 10;
Column = Move / 10;
MoveIsValid = false;
if (Board[Row, Column] == ' ')
{
MoveIsValid = true;
}
return MoveIsValid;
}
static int GetPlayerScore(char[,] Board, int BoardSize, char Piece)
{
int Score;
Score = 0;
for (int Row = 1; Row <= BoardSize; Row++)
{
for (int Column = 1; Column <= BoardSize; Column++)
{
if (Board[Row, Column] == Piece)
{
Score = Score + 1;
}
}
}
return Score;
}
static bool CheckIfThereArePiecesToFlip(char[,] Board, int BoardSize, int StartRow, int StartColumn, int RowDirection, int ColumnDirection)
{
int RowCount;
int ColumnCount;
bool FlipStillPossible;
bool FlipFound;
bool OpponentPieceFound;
RowCount = StartRow + RowDirection;
ColumnCount = StartColumn + ColumnDirection;
FlipStillPossible = true;
FlipFound = false;
OpponentPieceFound = false;
while (RowCount <= BoardSize && RowCount >= 1 && ColumnCount >= 1 && ColumnCount <= BoardSize && FlipStillPossible && !FlipFound)
{
if (Board[RowCount,ColumnCount] == ' ' )
{
FlipStillPossible = false;
}
else if (Board[RowCount,ColumnCount] != Board[StartRow, StartColumn])
{
OpponentPieceFound = true;
}
else if (Board[RowCount,ColumnCount] == Board[StartRow, StartColumn] && !OpponentPieceFound)
{
FlipStillPossible = false;
}
else
{
FlipFound = true;
}
RowCount = RowCount + RowDirection;
ColumnCount = ColumnCount + ColumnDirection;
}
return FlipFound;
}
static void FlipOpponentPiecesInOneDirection(char[,] Board, int BoardSize, int StartRow, int StartColumn, int RowDirection, int ColumnDirection)
{
int RowCount;
int ColumnCount;
bool FlipFound;
FlipFound = CheckIfThereArePiecesToFlip(Board, BoardSize, StartRow, StartColumn, RowDirection, ColumnDirection);
if (FlipFound)
{
RowCount = StartRow + RowDirection;
ColumnCount = StartColumn + ColumnDirection;
while (Board[RowCount, ColumnCount] != ' ' && Board[RowCount, ColumnCount] != Board[StartRow, StartColumn])
{
if (Board[RowCount, ColumnCount] == 'H')
{
Board[RowCount, ColumnCount] = 'C';
}
else
{
Board[RowCount, ColumnCount] = 'H';
}
RowCount = RowCount + RowDirection;
ColumnCount = ColumnCount + ColumnDirection;
}
}
}
static void MakeMove(char[,] Board, int BoardSize, int Move, bool HumanPlayersTurn)
{
int Row;
int Column;
Row = Move % 10;
Column = Move / 10;
if (HumanPlayersTurn)
{
Board[Row, Column] = 'H';
}
else
{
Board[Row, Column] = 'C';
}
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 1, 0);
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, -1, 0);
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, 1);
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, -1);
}
static void PrintLine(int BoardSize)
{
Console.Write(" ");
for (int Count = 1; Count <= BoardSize * 2 - 1; Count++)
{
Console.Write("_");
}
Console.WriteLine();
}
static void DisplayGameBoard(char[,] Board, int BoardSize)
{
Console.WriteLine();
Console.Write(" ");
for (int Column = 1; Column <= BoardSize; Column++)
{
Console.Write(" ");
Console.Write(Column);
}
Console.WriteLine();
PrintLine(BoardSize);
for (int Row = 1; Row <= BoardSize; Row++)
{
Console.Write(Row);
Console.Write(" ");
for (int Column = 1; Column <= BoardSize; Column++)
{
Console.Write("|");
Console.Write(Board[Row, Column]);
}
Console.WriteLine("|");
PrintLine(BoardSize);
Console.WriteLine();
}
}
static void DisplayMenu()
{
Console.WriteLine("(p)lay game");
Console.WriteLine("(e)nter name");
Console.WriteLine("(c)hange board size");
Console.WriteLine("(q)uit");
Console.WriteLine();
}
static char GetMenuChoice(string PlayerName)
{
char Choice;
Console.Write(PlayerName + " enter the letter of your chosen option: ");
Choice = Convert.ToChar(Console.ReadLine());
return Choice;
}
static void PlayGame(string PlayerName, int BoardSize)
{
char[,] Board = new char[BoardSize + 1, BoardSize + 1];
bool HumanPlayersTurn;
int Move = 0;
int HumanPlayerScore;
int ComputerPlayerScore;
bool MoveIsValid;
SetUpGameBoard(Board, BoardSize);
HumanPlayersTurn = false;
do
{
HumanPlayersTurn = !HumanPlayersTurn;
DisplayGameBoard(Board, BoardSize);
MoveIsValid = false;
do
{
if (HumanPlayersTurn)
{
Move = GetHumanPlayerMove(PlayerName);
}
else
{
Move = GetComputerPlayerMove(BoardSize);
}
MoveIsValid = CheckIfMoveIsValid(Board, Move);
} while (!MoveIsValid);
if (!HumanPlayersTurn)
{
Console.WriteLine("Press the Enter key and the computer will make its move");
Console.ReadLine();
}
MakeMove(Board, BoardSize, Move, HumanPlayersTurn);
} while (!GameOver(Board, BoardSize));
DisplayGameBoard(Board, BoardSize);
HumanPlayerScore = GetPlayerScore(Board, BoardSize, 'H');
ComputerPlayerScore = GetPlayerScore(Board, BoardSize, 'C');
if (HumanPlayerScore > ComputerPlayerScore )
{
Console.WriteLine("Well done, " + PlayerName + ", you have won the game!");
}
else if (HumanPlayerScore == ComputerPlayerScore )
{
Console.WriteLine("That was a draw!");
}
else
{
Console.WriteLine("The computer has won the game!");
}
Console.WriteLine();
}
}
}
A loop for invalid co-ordinates Edit
Java:
Answer:
boolean checkIfMoveIsValid(char[][] board, int move, int boardSize) { //add in the boardSize reference
int row;
int column;
boolean moveIsValid;
row = move % 10;
column = move / 10;
moveIsValid = false;
if (row <= boardSize && column <= boardSize && column > 0 && row > 0 ){ //add in this if statement
if (board[row][column] == ' ') {
moveIsValid = true;
}
} //closing the new if statement
return moveIsValid;
}
VB.Net:
Answer:
Function CheckIfMoveIsValid(ByVal Board(,) As Char, ByVal Move As Integer) As Boolean
Dim Row As Integer
Dim Column As Integer
Dim MoveIsValid As Boolean
Row = Move Mod 10
Column = Move \ 10
MoveIsValid = False
Try
If Board(Row, Column) = " " Then
MoveIsValid = True
End If
Catch ex As Exception 'Allows the user to enter invalid coordinates without crashing the program.
Console.WriteLine("Error!")
Console.WriteLine("Try enter the coordinates again.")
End Try
Return MoveIsValid
End Function
Python:
Answer:
# Edits made here is so that the program only accepts numbers #
def GetHumanPlayerMove(PlayerName):
MoveValid = False
while MoveValid == False:
print(PlayerName, "enter the coodinates of the square where you want to place your piece: ", end="")
Coordinates = input() # No longer int(input)
if Coordinates.isdigit():
MoveValid = True
return int(Coordinates) # Value is now changed into integer
# Edits made here to check if the co-ordinates are valid, on the board
def CheckIfMoveIsValid(Board, Move):
Row = Move % 10
Column = Move // 10
MoveIsValid = False
if Row <= BoardSize and Column <= BoardSize and Column > 0 and Row > 0: # Validate the co-ordinates
if Board[Row][Column] == " ":
MoveIsValid = True
return MoveIsValid
C#:
Answer:
static bool CheckIfMoveIsValid(char[,] Board, int Move, int BoardSize) //add reference BoardSize
{
int Row;
int Column;
bool MoveIsValid;
Row = Move % 10;
Column = Move / 10;
MoveIsValid = false;
if (Row <= BoardSize && Column <= BoardSize && Column > 0 && Row > 0 ) //add line
{
if (Board[Row, Column] == ' ')
{
MoveIsValid = true;
}
}
return MoveIsValid;
}
OR
Answer:
try
{
if (Board[Row, Column] == ' ')
{
MoveIsValid = true;
}
//Allows the user to enter invalid coordinates without crashing the program.
}
catch
{
Console.WriteLine("Invalid Coordinates. Please reenter.");
}
To accept both upper-case and lower-case inputs for Selection MenuEdit
Python:
Answer:
random.seed()
BoardSize = 6
PlayerName = ""
Choice = ""
while Choice.lower() != "q":
DisplayMenu()
Choice = GetMenuChoice(PlayerName)
if Choice.lower() == "p":
PlayGame(PlayerName, BoardSize)
elif Choice.lower() == "e":
PlayerName = GetPlayersName()
elif Choice.lower() == "c":
BoardSize = ChangeBoardSize()
or
def GetMenuChoice(PlayerName):
print(PlayerName, "enter the letter of your chosen option: ", end="")
Choice = input()
return Choice.lower()
or
random.seed()
BoardSize = 6
PlayerName = ""
Choice = ""
while Choice != "q" or Choice != "Q":
DisplayMenu()
Choice = GetMenuChoice(PlayerName)
if Choice in ("p", "P"):
PlayGame(PlayerName, BoardSize)
elif Choice in ("e", "E"):
PlayerName = GetPlayersName()
elif Choice in ("c", "C"):
BoardSize = ChangeBoardSize()
C#:
Answer:
static char GetMenuChoice(string PlayerName)
{
char Choice;
Console.Write(PlayerName + " enter the letter of your chosen option: ");
Choice = Convert.ToChar(Console.ReadLine().ToLower());
return Choice;
}
Skipping a turn Edit
Answer:
def PlayGame(PlayerName, BoardSize):
Board = CreateBoard()
SetUpGameBoard(Board, BoardSize)
HumanPlayersTurn = False
while not GameOver(Board, BoardSize):
HumanPlayersTurn = not HumanPlayersTurn
MoveIsValid = False
while not MoveIsValid:
if HumanPlayersTurn:
Skip = str(input("Would you like to skip the game? N for no, Y for yes, Q to quit."))
if Skip == "N":
Move = GetHumanPlayerMove(PlayerName)
MakeMove(Board, BoardSize, Move, HumanPlayersTurn)
DisplayGameBoard(Board, BoardSize)
HumanPlayersTurn = False
elif Skip == "Y":
HumanPlayersTurn = False
elif Skip == "Q":
DisplayMenu()
Choice = GetMenuChoice(PlayerName)
else:
Move = GetComputerPlayerMove(BoardSize)
MoveIsValid = CheckIfMoveIsValid(Board, Move)
if not HumanPlayersTurn:
print("Press the Enter key and the computer will make its move")
input()
MakeMove(Board, BoardSize, Move, HumanPlayersTurn)
DisplayGameBoard(Board, BoardSize)
DisplayGameBoard(Board, BoardSize)
HumanPlayerScore = GetPlayerScore(Board, BoardSize, "H")
ComputerPlayerScore = GetPlayerScore(Board, BoardSize, "C")
if HumanPlayerScore > ComputerPlayerScore:
print("Well done", PlayerName, ", you have won the game!")
elif HumanPlayerScore == ComputerPlayerScore:
print("That was a draw!")
else:
print("The computer has won the game!")
print()
Only letting a player place a piece if it captures the opponent's piece Edit
In the original Reversi game you are only allowed to place a piece if it captures the opponent's piece.
Python :
Answer:
def CheckIfMoveIsValid(Board, BoardSize, Move, HumanPlayersTurn):
Row = Move % 10
Column = Move // 10
MoveIsValid = False
if Board[Row][Column] == " ":
if HumanPlayersTurn == True:
Board[Row][Column] = "H"
else:
Board[Row][Column] = "C"
if ((CheckIfThereArePiecesToFlip(Board, BoardSize, Row, Column, 1, 0) == True) or
(CheckIfThereArePiecesToFlip(Board, BoardSize, Row, Column, -1, 0) == True) or
(CheckIfThereArePiecesToFlip(Board, BoardSize, Row, Column, 0, 1) == True) or
(CheckIfThereArePiecesToFlip(Board, BoardSize, Row, Column, 0, -1) == True) or
(CheckIfThereArePiecesToFlip(Board, BoardSize, Row, Column, 1, 1) == True) or
(CheckIfThereArePiecesToFlip(Board, BoardSize, Row, Column, -1, 1) == True) or
(CheckIfThereArePiecesToFlip(Board, BoardSize, Row, Column, -1, -1) == True) or
(CheckIfThereArePiecesToFlip(Board, BoardSize, Row, Column, 1, -1) == True)):
MoveIsValid = True
else:
MoveIsValid = False
Board[Row][Column] = " "
return MoveIsValid
#You must also make it so that when you call upon the CheckIfMoveIsValid function in PlayGame you
#add the HumanPlayersTurn parameter
Saving and Loading (Board layout and whose turn)Edit
I haven't made it load yet, but it does save in a text file called test. If anyone has other ideas on how to do this I'll code other possible solutions. This current one, saves the board every turn and whose turn, true means its human turn, false computer.
Vb.Net - Using last year's as an example this is what I came up with, I could definitely be improved but is a starting point.
To save the game i put in a If statement when the human move was fetched so when the input move = 6666 the save sub was run
To make the Load game sub work, I put another case statement into the menu that set a variable Gameload = true and ran the play sub passing it through. Then in the play sub an if statement that when true runs the load game sub, while also making sure to stopped the SetupGameBoard sub overwriting the save.
Answer:
Sub Savegame(ByVal Board(,) As Char, ByVal HumanPlayersTurn As Boolean, ByVal Boardsize As Integer)
'Passed into the sub all values that need to be saved. Current board, whose turn it is and the board size. 'To access a .txt file you need to import System.Io 'Declare a variable as a tool to write with Dim SaveFileWriter As StreamWriter Dim TurnFileWriter As StreamWriter
'Declare where the text file is, I have two files one for Turn and board size. One for the actual board layout Dim BoardSave As String = "c:\users\at\documents\visual studio 2010\Projects\Exam code\Save.txt" Dim TurnSizeSave As String = "C:\Users\at\Documents\Visual Studio 2010\Projects\Exam code/TurnSizeSave.txt"
'This variable converts the whose move boolean into a character string you can store Dim whosemove As String
'This declares whos turn it is in string form If HumanPlayersTurn = True Then whosemove = "Human" Else whosemove = "Computer" End If
'Recording all the boord positions cycles through all column/row combinations and written then one line per coordinate SaveFileWriter = New StreamWriter(BoardSave, False) For Rowno = 1 To Boardsize For ColumnNo = 1 To Boardsize SaveFileWriter.WriteLine(Board(Rowno, ColumnNo)) Next Next SaveFileWriter.Close()
'This section records whos turn it was on the first line and board size on the second TurnFileWriter = New StreamWriter(TurnSizeSave, False) TurnFileWriter.WriteLine(whosemove) TurnFileWriter.WriteLine(Boardsize) TurnFileWriter.Close() Console.WriteLine("The game has been saved") End Sub
Loading the game:
Sub loadgame(ByRef BoardSize As Integer, ByRef HumanPlayersTurn As Boolean, ByRef Board(,) As Char) 'Declare one reader for the save file and one for the turn/boardsize file Dim SaveFileReader As StreamReader Dim TurnFileReader As StreamReader Dim whosturn As String
'The two locations of the save files Dim Save As String = "C:\Users\at\Documents\Visual Studio 2010\Projects\Exam code\Save.txt" Dim TurnSize As String = "C:\Users\at\Documents\Visual Studio 2010\Projects\Exam code\TurnSizeSave.txt"
'Reads in the first line of the Turn/Board size save and converts it back to the boolean TurnFileReader = New StreamReader(TurnSize) whosturn = TurnFileReader.ReadLine()
'NOTE MUST BE OPOSITE TO WHOS TURN IT WAS AS THE PLAY SUB USES WHATEVER THE BOOLEAN IS NOT If whosturn = "Human" Then HumanPlayersTurn = False ElseIf whosturn = "Computer" Then HumanPlayersTurn = True Else Console.WriteLine("Error loading turn") HumanPlayersTurn = True End If
'Fetchs boardsize BoardSize = TurnFileReader.ReadLine() TurnFileReader.Close()
'Cycles though all the coordinates for the board size and loads what was saved in the Save.txt file SaveFileReader = New StreamReader(Save) For Row = 1 To BoardSize For Column = 1 To BoardSize Board(Row, Column) = SaveFileReader.ReadLine() Next Next End Sub
Adapting the program to load the save:
In Sub Main - Case "l"
GameLoaded = True PlayGame(PlayerName, BoardSize, GameLoaded)
In Setup Board - Enclose all code with If Gameloaded = False Then ..... End If
In PlayGame -
If Gameloaded = True Then loadgame(BoardSize, HumanPlayersTurn, Board)End If
Python (Method 1):
Answer:
def DisplayGameBoard(Board, BoardSize):
print()
print(" ", end="")
for Column in range(1, BoardSize + 1):
print(" ", end="")
print(Column, end="")
print()
PrintLine(BoardSize)
for Row in range(1, BoardSize + 1):
print(Row, end="")
print(" ", end="")
for Column in range(1, BoardSize + 1):
print("|", end="")
print(Board[Row][Column], end="")
print("|")
PrintLine(BoardSize)
print()
return Board
#RorySlatter:
def SaveGame(Board,HumanPlayersTurn):
f = open("GameData.txt","w")
for Row in range(1,BoardSize+1):
for Column in range(1,BoardSize+1):
f.write(str(Board[Row][Column])) #Prints each square of the board next to each other - this will make it easier when loading the game.
f.write(str(HumanPlayersTurn))
f.close()
def PlayGame(PlayerName, BoardSize):
Board = CreateBoard()
SetUpGameBoard(Board, BoardSize)
HumanPlayersTurn = False
while not GameOver(Board, BoardSize):
HumanPlayersTurn = not HumanPlayersTurn
DisplayGameBoard(Board, BoardSize)
MoveIsValid = False
while not MoveIsValid:
if HumanPlayersTurn:
Move = GetHumanPlayerMove(PlayerName)
else:
Move = GetComputerPlayerMove(BoardSize)
MoveIsValid = CheckIfMoveIsValid(Board, Move)
if not HumanPlayersTurn:
print("Press the Enter key and the computer will make its move")
input()
MakeMove(Board, BoardSize, Move, HumanPlayersTurn)
SaveGame(Board,HumanPlayersTurn) # Saves the game after each move
DisplayGameBoard(Board, BoardSize)
HumanPlayerScore = GetPlayerScore(Board, BoardSize, "H")
ComputerPlayerScore = GetPlayerScore(Board, BoardSize, "C")
if HumanPlayerScore > ComputerPlayerScore:
print("Well done", PlayerName, ", you have won the game!")
elif HumanPlayerScore == ComputerPlayerScore:
print("That was a draw!")
else:
print("The computer has won the game!")
print()
Python (Method 2):
Another Way of Saving (Nested FOR Loops to separate data from board lines)
Answer:
# SWood - Ossett Sixth
#-----------------------------------------------------------------
def SaveGame(Board,HumanPlayersTurn):
with open("MySave.txt", "w") as SaveFile: # Open file securely
for Row in range(1 , BoardSize + 1): # For each Row do this...
for Column in range(1, BoardSize + 1): # For each Column in each Row...
SaveFile.writelines(str(Board[Row][Column])) # Write only the contents of each cell, no borders etc.
SaveFile.writelines(" " + "\n") # Write new line after each Row.
SaveFile.writelines(str(HumanPlayersTurn)) # Write PlayerTurn after the Board.
#-----------------------------------------------------------------
def LoadGame(Board):
with open("MySave.txt", "r") as SavedFile:
for Row in range(1 , BoardSize + 1): # For each Row, readline of text file
Line = SavedFile.readline()
for Column in range(1 , BoardSize + 1):
Board[Row][Column] = Line[Column - 1] # For each Column in Row, put the data in that cell position.
WhoseTurn = SavedFile.readline() # Set this based on what is read in as text.
if WhoseTurn == "True":
HumanPlayersTurn = True
elif WhoseTurn == "False":
HumanPlayersTurn = False
print("Human Turn:", HumanPlayersTurn)
return Board, HumanPlayersTurn # Return the variables to use.
#------------- ADD This bit to PlayGame...
def PlayGame(PlayerName, BoardSize):
print("Do you want to play a SAVED Game?")
myGame = str(input("Enter choice (y/n): ")).lower()
if myGame == "n":
Board = CreateBoard() # original section of code, if choose not to load a game.
SetUpGameBoard(Board, BoardSize)
HumanPlayersTurn = False
elif myGame == "y":
Board = CreateBoard()
Board, HumanPlayersTurn = LoadGame(Board) # If loading a game, get the info from LoadGame() instead of SetUpBoard().
#-------- Below here is normal ---------------
SaveGame(Board, HumanPlayersTurn) # Need to call SaveGame in PlayGame loop. Put it after MakeMove().
#---------------------------------------------------------------------------------------------------------------------------------------------------
C#:
Answer:
Two player modeEdit
Python:
Firstly I have added another choice on the main menu called (m)ultiplayer game, where user will enter 'm' to play against each other, this will straightly ask them to enter their names, I stored the first player's players name in the variable PlayerName and the second in another variable I made called PlayerTwoName. I then call the play game function passing on three parameters PlayerName, PlayerTwoName, BoardSize. Because I added another parameter that it takes I had to pass another parameter when the computer plays with human so I added none leaving the other two so like (PlayerName,None, BoardSize). In the PlayGame function just before the computer gets it's move, I made a check to see if it's two players against a computer or a human, this was simply done by that variable/parameter I have passed on, if Player2Name does not equal none, then we know it is another human player as we passed his/her name. Under that I did Move = GetHumanPlayerMove(Player2Name), this is calling the function GetHumanPlayerMove but passing a different parameter than the computer. Otherwise/else it is a computer so we keep the existing line Move = GetComputerPlayerMove(BoardSize) but under the if statement as else. I then just added some extra bits so instead of "Press the Enter key and the computer will make its move" I did a check to see if it is against human player and then added anther message saying press enter so 'player2name' will make their move, for example. Also a message saying player 2 won instead of computer won.
Answer:
def DisplayMenu():
print("(p)lay game - against computer")
print("(m)ultiplayer game")
print("(e)nter name - Single Player")
print("(c)hange board size")
print("(q)uit")
print()
def PlayGame(PlayerName,Player2Name, BoardSize):
Board = CreateBoard()
SetUpGameBoard(Board, BoardSize)
HumanPlayersTurn = False
while not GameOver(Board, BoardSize):
HumanPlayersTurn = not HumanPlayersTurn
DisplayGameBoard(Board, BoardSize)
MoveIsValid = False
while not MoveIsValid:
if HumanPlayersTurn:
Move = GetHumanPlayerMove(PlayerName)
else:
if Player2Name != None:
Move = GetHumanPlayerMove(Player2Name)
else:
Move = GetComputerPlayerMove(BoardSize)
MoveIsValid = CheckIfMoveIsValid(Board, Move)
if not HumanPlayersTurn:
if Player2Name != None:
print("Press the Enter key and the",Player2Name," will make their move")
input()
else:
print("Press the Enter key and the computer will make its move")
input()
MakeMove(Board, BoardSize, Move, HumanPlayersTurn)
DisplayGameBoard(Board, BoardSize)
HumanPlayerScore = GetPlayerScore(Board, BoardSize, "H")
ComputerPlayerScore = GetPlayerScore(Board, BoardSize, "C")
if HumanPlayerScore > ComputerPlayerScore:
print("Well done", PlayerName, ", you have won the game!")
elif HumanPlayerScore == ComputerPlayerScore:
print("That was a draw!")
else:
if Player2Name != None:
print("The computer has won the game!")
else:
print("Well done", PlayerTwoName, ", you have won the game!")
print()
random.seed()
BoardSize = 6
PlayerName = ""
Choice = ""
while Choice.lower() != "q":
DisplayMenu()
Choice = GetMenuChoice(PlayerName)
if Choice.lower() == "p":
PlayGame(PlayerName,None, BoardSize)
elif Choice.lower() == "e":
PlayerName = GetPlayersName()
elif Choice.lower() == "c":
BoardSize = ChangeBoardSize()
elif Choice.lower() == "m":
PlayerName = input ("Player one's name: ")
PlayerTwoName = input ("Player two's name: ")
PlayGame(PlayerName, PlayerTwoName, BoardSize)
C#:
Answer:
static void Main(string[] args)
{
char Choice;
string PlayerName;
int BoardSize;
string PlayerTwoName; //add player 2 variable for name
BoardSize = 6;
PlayerName = "H";
do
{
DisplayMenu();
Choice = GetMenuChoice(PlayerName);
switch (Choice)
{
case 'p':
PlayerName = GetPlayersName();
PlayGame(PlayerName, null, BoardSize); //add the parameter for player two but set to null as the computer will be taking the role
break;
case 'e':
PlayerName = GetPlayersName();
break;
case 'c':
BoardSize = ChangeBoardSize();
break;
case 'm':
Console.WriteLine("Player one enter name:");
PlayerName = Console.ReadLine(); //store player one's name
Console.WriteLine("Player two enter name:");
PlayerTwoName = Console.ReadLine(); //store player two's name
PlayGame(PlayerName, PlayerTwoName, BoardSize); //call play game with player one and two
break;
}
} while (Choice != 'q');
}
static void SetUpGameBoard(char[,] Board, int BoardSize, string PlayerName, string PlayerTwoName) //add player two name as parameter
{
for (int Row = 1; Row <= BoardSize; Row++)
{
for (int Column = 1; Column <= BoardSize; Column++)
{
if (Row == (BoardSize + 1) / 2 && Column == (BoardSize + 1) / 2 + 1 || Column == (BoardSize + 1) / 2 && Row == (BoardSize + 1) / 2 + 1)
{
if (PlayerTwoName != null) //if player two parameter is NOT empty
{
Board[Row, Column] = Convert.ToChar(PlayerTwoName.Substring(0, 1)); //use first letter of player one name
}
else
{
Board[Row, Column] = 'C'; //if player two name empty use default C
}
}
else if (Row == (BoardSize + 1) / 2 + 1 && Column == (BoardSize + 1) / 2 + 1 || Column == (BoardSize + 1) / 2 && Row == (BoardSize + 1) / 2)
{
Board[Row, Column] = Convert.ToChar(PlayerName.Substring(0, 1)); //gets first letter of playername
}
else
{
Board[Row, Column] = ' ';
}
}
}
}
static void FlipOpponentPiecesInOneDirection(char[,] Board, int BoardSize, int StartRow, int StartColumn, int RowDirection, int ColumnDirection, string PlayerName, string PlayerTwoName) //add player two parameter
{
int RowCount;
int ColumnCount;
bool FlipFound;
FlipFound = CheckIfThereArePiecesToFlip(Board, BoardSize, StartRow, StartColumn, RowDirection, ColumnDirection);
if (FlipFound)
{
RowCount = StartRow + RowDirection;
ColumnCount = StartColumn + ColumnDirection;
while (Board[RowCount, ColumnCount] != ' ' && Board[RowCount, ColumnCount] != Board[StartRow, StartColumn])
{
if (Board[RowCount, ColumnCount] == Convert.ToChar(PlayerName.Substring(0, 1))) //change all instances of H to playername.substring and convert to char
{
if (PlayerTwoName != "") //if player two name is NOT empty use first letter as counter
{
Board[RowCount, ColumnCount] = Convert.ToChar(PlayerTwoName.Substring(0, 1));
}
else
{
Board[RowCount, ColumnCount] = 'C'; //use default C when player two name is empty
}
}
else
{
Board[RowCount, ColumnCount] = Convert.ToChar(PlayerName.Substring(0, 1)); //change all instances of H to playername.substring and convert to char
}
RowCount = RowCount + RowDirection;
ColumnCount = ColumnCount + ColumnDirection;
}
}
}
static void MakeMove(char[,] Board, int BoardSize, int Move, bool HumanPlayersTurn, string PlayerName, string PlayerTwoName) //add parameter
{
int Row;
int Column;
Row = Move % 10;
Column = Move / 10;
if (HumanPlayersTurn)
{
Board[Row, Column] = Convert.ToChar(PlayerName.Substring(0, 1));
}
else
{
if (PlayerTwoName != null) //if player two name is NOT null then allow move for player two
{
Board[Row, Column] = Convert.ToChar(PlayerTwoName.Substring(0, 1));
}
else
{
Board[Row, Column] = 'C';
}
}
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 1, 0, PlayerName.Substring(0, 1), ""); //change all instances of H to playername.substring and convert to char
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, -1, 0, PlayerName.Substring(0, 1), "");
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, 1, PlayerName.Substring(0, 1), "");
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, -1, PlayerName.Substring(0, 1), "");
//flip diagonals
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 1, 1, PlayerName.Substring(0, 1), "");
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, -1, 1, PlayerName.Substring(0, 1), "");
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 1, -1, PlayerName.Substring(0, 1), "");
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, -1, -1, PlayerName.Substring(0, 1), "");
}
static void PlayGame(string PlayerName, string PlayerTwoName, int BoardSize) //add player two parameter
{
char[,] Board = new char[BoardSize + 1, BoardSize + 1];
bool HumanPlayersTurn;
int Move = 0;
int HumanPlayerScore;
int ComputerPlayerScore;
bool MoveIsValid;
SetUpGameBoard(Board, BoardSize, PlayerName, PlayerTwoName); //add player two
HumanPlayersTurn = false;
do
{
HumanPlayersTurn = !HumanPlayersTurn;
DisplayGameBoard(Board, BoardSize);
MoveIsValid = false;
do
{
if (HumanPlayersTurn)
{
Move = GetHumanPlayerMove(PlayerName);
}
else if (PlayerTwoName != null)
{
Move = GetHumanPlayerMove(PlayerTwoName); //recall function but for player two
}
else
{
Move = GetComputerPlayerMove(BoardSize);
}
MoveIsValid = CheckIfMoveIsValid(Board, Move, BoardSize);
} while (!MoveIsValid);
if (!HumanPlayersTurn)
{
if (PlayerTwoName != null) //allow player two to move
{
}
else
{
Console.WriteLine("Press the Enter key and the computer will make its move");
Console.ReadLine();
}
}
MakeMove(Board, BoardSize, Move, HumanPlayersTurn, PlayerName, PlayerTwoName); //call make move function with player two parameter added
} while (!GameOver(Board, BoardSize));
DisplayGameBoard(Board, BoardSize);
HumanPlayerScore = GetPlayerScore(Board, BoardSize, Convert.ToChar(PlayerName.Substring(0, 1))); //convert playername.substring to char
if (PlayerTwoName != null)
{
ComputerPlayerScore = GetPlayerScore(Board, BoardSize, Convert.ToChar(PlayerTwoName.Substring(0, 1))); //computer score will now store player two's score (reusing preexisting code but searches for pieces with the initial from player two's name)
}
else
{
ComputerPlayerScore = GetPlayerScore(Board, BoardSize, 'C');
}
if (HumanPlayerScore > ComputerPlayerScore)
{
if (PlayerTwoName != null) //calculates who won but checks for player two
{
Console.WriteLine("Well done, " + PlayerName + ", you have won the game!");
Console.WriteLine("Your Pieces: " + HumanPlayerScore); //show human score
Console.WriteLine(PlayerTwoName + " Pieces: " + ComputerPlayerScore); //show computer score
}
else
{
Console.WriteLine("Well done, " + PlayerName + ", you have won the game!");
Console.WriteLine("Your Pieces: " + HumanPlayerScore); //show human score
Console.WriteLine("Computer Pieces: " + ComputerPlayerScore); //show computer score
}
}
else if (HumanPlayerScore == ComputerPlayerScore)
{
Console.WriteLine("That was a draw!");
}
else
{
if (PlayerTwoName != null)
{
Console.WriteLine("Well done, " + PlayerTwoName + ", you have won the game!");
Console.WriteLine("Your Pieces: " + ComputerPlayerScore); //show human score
Console.WriteLine(PlayerName + " Pieces: " + HumanPlayerScore); //show computer score
}
else
{
Console.WriteLine("The computer has won the game!");
Console.WriteLine("Your Pieces: " + HumanPlayerScore); //show human score
Console.WriteLine("Computer Pieces: " + ComputerPlayerScore); //show computer score
}
}
Console.WriteLine();
}
}
Vb.net
Answer:
'Skeleton Program code for the AQA COMP1 Summer 2016 examination <br />
'this code should be used in conjunction with the Preliminary Material <br />
'written by the AQA COMP1 Programmer Team <br />
'developed in the Visual Studio 2008 programming environment
Module Module1
Sub Main()
Dim Choice As Char
Dim PlayerName As String
Dim player2name As String
Dim BoardSize As Integer
Randomize()
BoardSize = 4
PlayerName = ""
player2name = ""
Do
DisplayMenu()
Choice = GetMenuChoice(PlayerName)
Select Case Choice
Case "p"
PlayGame(PlayerName, BoardSize, player2name)
Case "e"
PlayerName = GetPlayersName()
Case "c"
BoardSize = ChangeBoardSize()
Case "m"
PlayerName = GetPlayersName()
player2Name = GetPlayer2Name()
PlayMultiGame(PlayerName, BoardSize, player2name)
End Select
Loop Until Choice = "q"
End Sub
Sub SetUpGameBoard(ByVal Board(,) As Char, ByVal BoardSize As Integer, ByVal playername As String)
Dim Row As Integer
Dim Column As Integer
For Row = 1 To BoardSize
For Column = 1 To BoardSize
If playername = "" Then
If Row = (BoardSize + 1) \ 2 And Column = (BoardSize + 1) \ 2 + 1 Or Column = (BoardSize + 1) \ 2 And Row = (BoardSize + 1) \ 2 + 1 Then
Board(Row, Column) = "C"
ElseIf Row = (BoardSize + 1) \ 2 + 1 And Column = (BoardSize + 1) \ 2 + 1 Or Column = (BoardSize + 1) \ 2 And Row = (BoardSize + 1) \ 2 Then
Board(Row, Column) = "H"
Else
Board(Row, Column) = " "
End If
Else
If Row = (BoardSize + 1) \ 2 And Column = (BoardSize + 1) \ 2 + 1 Or Column = (BoardSize + 1) \ 2 And Row = (BoardSize + 1) \ 2 + 1 Then
Board(Row, Column) = "C"
ElseIf Row = (BoardSize + 1) \ 2 + 1 And Column = (BoardSize + 1) \ 2 + 1 Or Column = (BoardSize + 1) \ 2 And Row = (BoardSize + 1) \ 2 Then
Board(Row, Column) = GetPlayersInitials(playername)
Else
Board(Row, Column) = " "
End If
End If
Next
Next
End Sub
Function ChangeBoardSize() As Integer
Dim BoardSize As Integer
Do
Console.Write("Enter a board size (between 4 and 9): ")
BoardSize = Console.ReadLine
Loop Until BoardSize >= 4 And BoardSize <= 9
Return BoardSize
End Function
Function GetHumanPlayerMove(ByVal PlayerName As String) As Integer
Dim Coordinates As Integer
Dim choice As String
Console.WriteLine(PlayerName & " enter the coordinates of the square where you want to place your piece: ")
Console.WriteLine(" Or Enter q to quit")
choice = Console.ReadLine
Do
Select Case choice
Case "q"
End
End Select
Loop Until IsNumeric(choice)
Coordinates = choice
Return Coordinates
End Function
Function GetHumanPlayer2Move(ByVal Player2Name As String) As Integer
Dim Coordinates As Integer
Dim choice As String
Console.WriteLine(Player2Name & " enter the coordinates of the square where you want to place your piece: ")
Console.WriteLine(" Or Enter q to quit")
choice = Console.ReadLine
Do
Select Case choice
Case "q"
End
End Select
Loop Until IsNumeric(choice)
Coordinates = choice
Return Coordinates
End Function
Function GetComputerPlayerMove(ByVal BoardSize As Integer) As Integer
Return (Int(Rnd() * BoardSize) + 1) * 10 + Int(Rnd() * BoardSize) + 1
End Function
Function GameOver(ByVal Board(,) As Char, ByVal BoardSize As Integer) As Boolean
Dim Row As Integer
Dim Column As Integer
For Row = 1 To BoardSize
For Column = 1 To BoardSize
If Board(Row, Column) = " " Then
Return False
End If
Next
Next
Return True
End Function
Function GetPlayersName() As String
Dim PlayerName As String
Console.Write("What is your name Player1? ")
PlayerName = Console.ReadLine
Return PlayerName
End Function
Function GetPlayersInitials(ByVal playername As String)
Dim initial As String
initial = playername(0)
UCase(initial)
Return initial
End Function
Function GetPlayer2Name() As String
Dim Player2Name As String
Console.Write("What is your name player2? ")
Player2Name = Console.ReadLine
Return Player2Name
End Function
Function GetPlayer2Initials(ByVal player2name As String)
Dim initial2 As String
initial2 = player2name(0)
UCase(initial2)
Return initial2
End Function
Function CheckIfMoveIsValid(ByVal Board(,) As Char, ByVal Move As Integer) As Boolean
Dim Row As Integer
Dim Column As Integer
Dim MoveIsValid As Boolean
Row = Move Mod 10
Column = Move \ 10
MoveIsValid = False
If Board(Row, Column) = " " Then
MoveIsValid = True
End If
Return MoveIsValid
End Function
Function GetPlayerScore(ByVal Board(,) As Char, ByVal BoardSize As Integer, ByVal Piece As Char) As Integer
Dim Score As Integer
Dim Row As Integer
Dim Column As Integer
Score = 0
For Row = 1 To BoardSize
For Column = 1 To BoardSize
If Board(Row, Column) = Piece Then
Score = Score + 1
End If
Next
Next
Return Score
End Function
Function CheckIfThereArePiecesToFlip(ByVal Board(,) As Char, ByVal BoardSize As Integer, ByVal StartRow As Integer, ByVal StartColumn As Integer, ByVal RowDirection As Integer, ByVal ColumnDirection As Integer) As Boolean
Dim RowCount As Integer
Dim ColumnCount As Integer
Dim FlipStillPossible As Boolean
Dim FlipFound As Boolean
Dim OpponentPieceFound As Boolean
RowCount = StartRow + RowDirection
ColumnCount = StartColumn + ColumnDirection
FlipStillPossible = True
FlipFound = False
OpponentPieceFound = False
While RowCount <= BoardSize And RowCount >= 1 And ColumnCount >= 1 And ColumnCount <= BoardSize And FlipStillPossible And Not FlipFound
If Board(RowCount, ColumnCount) = " " Then
FlipStillPossible = False
ElseIf Board(RowCount, ColumnCount) <> Board(StartRow, StartColumn) Then
OpponentPieceFound = True
ElseIf Board(RowCount, ColumnCount) = Board(StartRow, StartColumn) And Not OpponentPieceFound Then
FlipStillPossible = False
Else
FlipFound = True
End If
RowCount = RowCount + RowDirection
ColumnCount = ColumnCount + ColumnDirection
End While
Return FlipFound
End Function
Sub FlipOpponentPiecesInOneDirection(ByVal Board(,) As Char, ByVal BoardSize As Integer, ByVal StartRow As Integer, ByVal StartColumn As Integer, ByVal RowDirection As Integer, ByVal ColumnDirection As Integer, ByVal playername As String, ByVal player2name As String)
Dim RowCount As Integer
Dim ColumnCount As Integer
Dim FlipFound As Boolean
If playername = "" Then
FlipFound = CheckIfThereArePiecesToFlip(Board, BoardSize, StartRow, StartColumn, RowDirection, ColumnDirection)
If FlipFound Then
RowCount = StartRow + RowDirection
ColumnCount = StartColumn + ColumnDirection
While Board(RowCount, ColumnCount) <> " " And Board(RowCount, ColumnCount) <> Board(StartRow, StartColumn)
If Board(RowCount, ColumnCount) = "H" Then
Board(RowCount, ColumnCount) = "C"
Else
Board(RowCount, ColumnCount) = "H"
End If
RowCount = RowCount + RowDirection
ColumnCount = ColumnCount + ColumnDirection
End While
End If
ElseIf player2name <> "" Then
FlipFound = CheckIfThereArePiecesToFlip(Board, BoardSize, StartRow, StartColumn, RowDirection, ColumnDirection)
If FlipFound Then
RowCount = StartRow + RowDirection
ColumnCount = StartColumn + ColumnDirection
While Board(RowCount, ColumnCount) <> " " And Board(RowCount, ColumnCount) <> Board(StartRow, StartColumn)
If Board(RowCount, ColumnCount) = GetPlayersInitials(playername) Then
Board(RowCount, ColumnCount) = GetPlayer2Initials(player2name)
Else
Board(RowCount, ColumnCount) = GetPlayersInitials(playername)
End If
RowCount = RowCount + RowDirection
ColumnCount = ColumnCount + ColumnDirection
End While
End If
ElseIf playername <> "" Then
FlipFound = CheckIfThereArePiecesToFlip(Board, BoardSize, StartRow, StartColumn, RowDirection, ColumnDirection)
If FlipFound Then
RowCount = StartRow + RowDirection
ColumnCount = StartColumn + ColumnDirection
While Board(RowCount, ColumnCount) <> " " And Board(RowCount, ColumnCount) <> Board(StartRow, StartColumn)
If Board(RowCount, ColumnCount) = GetPlayersInitials(playername) Then
Board(RowCount, ColumnCount) = "C"
Else
Board(RowCount, ColumnCount) = GetPlayersInitials(playername)
End If
RowCount = RowCount + RowDirection
ColumnCount = ColumnCount + ColumnDirection
End While
End If
End If
End Sub
Sub MakeMove(ByVal Board(,) As Char, ByVal BoardSize As Integer, ByVal Move As Integer, ByVal HumanPlayersTurn As Boolean, ByVal playername As String, ByVal player2name As String)
Dim Row As Integer
Dim Column As Integer
Row = Move Mod 10
Column = Move \ 10
If playername = "" Then
If HumanPlayersTurn Then
Board(Row, Column) = "H"
Else
Board(Row, Column) = "C"
End If
ElseIf player2name <> "" Then
If HumanPlayersTurn Then
Board(Row, Column) = GetPlayersInitials(playername)
Else
Board(Row, Column) = GetPlayer2Initials(player2name)
End If
Else
If HumanPlayersTurn Then
Board(Row, Column) = GetPlayersInitials(playername)
Else
Board(Row, Column) = "C"
End If
End If
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 1, 0, playername, player2name)
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, -1, 0, playername, player2name)
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, 1, playername, player2name)
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, -1, playername, player2name)
End Sub
Sub PrintLine(ByVal BoardSize As Integer)
Dim Count As Integer
Console.Write(" ")
For Count = 1 To BoardSize * 2 - 1
Console.Write("_")
Next
Console.WriteLine()
End Sub
Sub DisplayGameBoard(ByVal Board(,) As Char, ByVal BoardSize As Integer)
Dim Row As Integer
Dim Column As Integer
Console.WriteLine()
Console.Write(" ")
For Column = 1 To BoardSize
Console.Write(" ")
Console.Write(Column)
Next
Console.WriteLine()
PrintLine(BoardSize)
For Row = 1 To BoardSize
Console.Write(Row)
Console.Write(" ")
For Column = 1 To BoardSize
Console.Write("|")
Console.Write(Board(Row, Column))
Next
Console.WriteLine("|")
PrintLine(BoardSize)
Console.WriteLine()
Next
End Sub
Sub DisplayMenu()
Console.WriteLine("(p)lay game")
Console.WriteLine("(e)nter name")
Console.WriteLine("(c)hange board size")
Console.WriteLine("(m)ultiplayer")
Console.WriteLine("(q)uit")
Console.WriteLine()
End Sub
Function GetMenuChoice(ByVal PlayerName As String) As Char
Dim Choice As Char
Console.Write(PlayerName & " enter the letter of your chosen option: ")
Choice = Console.ReadLine
Return Choice
End Function
Sub PlayGame(ByVal PlayerName As String, ByVal BoardSize As Integer, ByVal player2name As String)
Dim Board(BoardSize, BoardSize) As Char
Dim HumanPlayersTurn As Boolean
Dim Move As Integer
Dim HumanPlayerScore As Integer
Dim ComputerPlayerScore As Integer
Dim MoveIsValid As Boolean
SetUpGameBoard(Board, BoardSize, PlayerName)
HumanPlayersTurn = False
Do
HumanPlayersTurn = Not HumanPlayersTurn
DisplayGameBoard(Board, BoardSize)
MoveIsValid = False
Do
If HumanPlayersTurn Then
Move = GetHumanPlayerMove(PlayerName)
Else
Move = GetComputerPlayerMove(BoardSize)
End If
MoveIsValid = CheckIfMoveIsValid(Board, Move)
Loop Until MoveIsValid
If Not HumanPlayersTurn Then
Console.WriteLine("Press the Enter key and the computer will make its move")
Console.ReadLine()
End If
MakeMove(Board, BoardSize, Move, HumanPlayersTurn, PlayerName, player2name)
Loop Until GameOver(Board, BoardSize)
DisplayGameBoard(Board, BoardSize)
If PlayerName = "" Then
HumanPlayerScore = GetPlayerScore(Board, BoardSize, "H")
Else
HumanPlayerScore = GetPlayerScore(Board, BoardSize, GetPlayersInitials(PlayerName))
End If
ComputerPlayerScore = GetPlayerScore(Board, BoardSize, "C")
If HumanPlayerScore > ComputerPlayerScore Then
Console.WriteLine("Well done, " & PlayerName & ", you have won the game!")
ElseIf HumanPlayerScore = ComputerPlayerScore Then
Console.WriteLine("That was a draw!")
Else
Console.WriteLine("The computer has won the game!")
End If
Console.WriteLine()
End Sub
Sub PlayMultiGame(ByVal PlayerName As String, ByVal BoardSize As Integer, ByVal player2name As String)
Dim Board(BoardSize, BoardSize) As Char
Dim HumanPlayersTurn As Boolean
Dim Move As Integer
Dim Player1Score As Integer
Dim Player2Score As Integer
Dim MoveIsValid As Boolean
SetUpMultiGameBoard(Board, BoardSize, PlayerName, player2name)
HumanPlayersTurn = False
Do
HumanPlayersTurn = Not HumanPlayersTurn
DisplayGameBoard(Board, BoardSize)
MoveIsValid = False
Do
If HumanPlayersTurn Then
Move = GetHumanPlayerMove(PlayerName)
Else
Move = GetHumanPlayer2Move(player2name)
End If
MoveIsValid = CheckIfMoveIsValid(Board, Move)
Loop Until MoveIsValid
MakeMove(Board, BoardSize, Move, HumanPlayersTurn, PlayerName, player2name)
Loop Until GameOver(Board, BoardSize)
DisplayGameBoard(Board, BoardSize)
Player1Score = GetPlayerScore(Board, BoardSize, GetPlayersInitials(PlayerName))
Player2Score = GetPlayerScore(Board, BoardSize, GetPlayer2Initials(PlayerName))
If Player1Score > Player2Score Then
Console.WriteLine("Well done, " & PlayerName & ", you have won the game!")
ElseIf Player1Score = Player2Score Then
Console.WriteLine("That was a draw!")
Else
Console.WriteLine("Well done, " & player2name & ", you have won the game!")
End If
Console.WriteLine()
End Sub
Sub SetUpMultiGameBoard(ByVal Board(,) As Char, ByVal BoardSize As Integer, ByVal playername As String, ByVal player2name As String)
Dim Row As Integer
Dim Column As Integer
For Row = 1 To BoardSize
For Column = 1 To BoardSize
If Row = (BoardSize + 1) \ 2 And Column = (BoardSize + 1) \ 2 + 1 Or Column = (BoardSize + 1) \ 2 And Row = (BoardSize + 1) \ 2 + 1 Then
Board(Row, Column) = GetPlayer2Initials(player2name)
ElseIf Row = (BoardSize + 1) \ 2 + 1 And Column = (BoardSize + 1) \ 2 + 1 Or Column = (BoardSize + 1) \ 2 And Row = (BoardSize + 1) \ 2 Then
Board(Row, Column) = GetPlayersInitials(playername)
Else
Board(Row, Column) = " "
End If
Next
Next
End Sub
End Module
Ability to change player's initials from H and C Edit
Python:
Answer:
def SetUpGameBoard(Board, Boardsize, PlayerInitials, ComputerInitials):
for Row in range(1, BoardSize + 1):
for Column in range(1, BoardSize + 1):
if (Row == (BoardSize + 1) // 2 and Column == (BoardSize + 1) // 2 + 1) or (Column == (BoardSize + 1) // 2 and Row == (BoardSize + 1) // 2 + 1):
Board[Row][Column] = ComputerInitials # Changes the initial "C" piece into ComputerInitial variable value
elif (Row == (BoardSize + 1) // 2 + 1 and Column == (BoardSize + 1) // 2 + 1) or (Column == (BoardSize + 1) // 2 and Row == (BoardSize + 1) // 2):
Board[Row][Column] = PlayerInitials # Changes the initial "H" peice into PlayerInitial variable value
else:
Board[Row][Column] = " "
def ChangeInitials(PlayerName):
print("Enter the initials for", PlayerName, "'s peice")
PlayerInitials = input()
PlayerInitials = PlayerInitials.upper() # converts player's initials into upper case
print("Enter the initials for the computer's peice")
ComputerInitials = input()
ComputerInitials = ComputerInitials.upper() # converts computer's initials into upper case
return ComputerInitials, PlayerInitials
def DisplayMenu():
print("(p)lay game")
print("(e)nter name")
print("(c)hange board size")
print("(i)nitials change")# adds initial change option to menu
print("(q)uit")
print()
def PlayGame(PlayerName, BoardSize, PlayerInitials, ComputerInitials):#
Board = CreateBoard()
SetUpGameBoard(Board, BoardSize, PlayerInitials, ComputerInitials)#
HumanPlayersTurn = False
while not GameOver(Board, BoardSize):
HumanPlayersTurn = not HumanPlayersTurn
DisplayGameBoard(Board, BoardSize)
MoveIsValid = False
while not MoveIsValid:
if HumanPlayersTurn:
Move = GetHumanPlayerMove(PlayerName)
else:
Move = GetComputerPlayerMove(BoardSize)
MoveIsValid = CheckIfMoveIsValid(Board, Move)
if not HumanPlayersTurn:
print("Press the Enter key and the computer will make its move")
input()
MakeMove(Board, BoardSize, Move, HumanPlayersTurn)
DisplayGameBoard(Board, BoardSize)
HumanPlayerScore = GetPlayerScore(Board, BoardSize, "H")
ComputerPlayerScore = GetPlayerScore(Board, BoardSize, "C")
if HumanPlayerScore > ComputerPlayerScore:
print("Well done", PlayerName, ", you have won the game!")
elif HumanPlayerScore == ComputerPlayerScore:
print("That was a draw!")
else:
print("The computer has won the game!")
print()
random.seed()
BoardSize = 6
PlayerName = ""
Choice = ""
PlayerInitials = "H"# Sets the default Player initial to H
ComputerInitials = "C"# Sets the default Computer initial to C
while Choice != "q":
DisplayMenu()
Choice = GetMenuChoice(PlayerName)
if Choice == "p":
PlayGame(PlayerName, BoardSize, PlayerInitials, ComputerInitials)#
elif Choice == "e":
PlayerName = GetPlayersName()
elif Choice == "c":
BoardSize = ChangeBoardSize()
elif Choice == "i": #
ComputerInitials, PlayerInitials = ChangeInitials(PlayerName)
C#:
The solution here changes the default H to the first letter of the player's name when entered through the menu.
Answer:
static void SetUpGameBoard(char[,] Board, int BoardSize, string PlayerName)
{
for (int Row = 1; Row <= BoardSize; Row++)
{
for (int Column = 1; Column <= BoardSize; Column++)
{
if (Row == (BoardSize + 1) / 2 && Column == (BoardSize + 1) / 2 + 1 || Column == (BoardSize + 1) / 2 && Row == (BoardSize + 1) / 2 + 1)
{
Board[Row, Column] = 'C';
}
else if (Row == (BoardSize + 1) / 2 + 1 && Column == (BoardSize + 1) / 2 + 1 || Column == (BoardSize + 1) / 2 && Row == (BoardSize + 1) / 2)
{
Board[Row, Column] = Convert.ToChar(PlayerName.Substring(0,1)); //gets first letter of playername
}
else
{
Board[Row, Column] = ' ';
}
}
}
}
static void FlipOpponentPiecesInOneDirection(char[,] Board, int BoardSize, int StartRow, int StartColumn, int RowDirection, int ColumnDirection, string PlayerName)
{
int RowCount;
int ColumnCount;
bool FlipFound;
FlipFound = CheckIfThereArePiecesToFlip(Board, BoardSize, StartRow, StartColumn, RowDirection, ColumnDirection);
if (FlipFound)
{
RowCount = StartRow + RowDirection;
ColumnCount = StartColumn + ColumnDirection;
while (Board[RowCount, ColumnCount] != ' ' && Board[RowCount, ColumnCount] != Board[StartRow, StartColumn])
{
if (Board[RowCount, ColumnCount] == Convert.ToChar(PlayerName.Substring(0, 1))) //change all instances of H to playername.substring and convert to char
{
Board[RowCount, ColumnCount] = 'C';
}
else
{
Board[RowCount, ColumnCount] = Convert.ToChar(PlayerName.Substring(0, 1)); //change all instances of H to playername.substring and convert to char
}
RowCount = RowCount + RowDirection;
ColumnCount = ColumnCount + ColumnDirection;
}
}
}
static void MakeMove(char[,] Board, int BoardSize, int Move, bool HumanPlayersTurn, string PlayerName) //add parameter
{
int Row;
int Column;
Row = Move % 10;
Column = Move / 10;
if (HumanPlayersTurn)
{
Board[Row, Column] = Convert.ToChar(PlayerName.Substring(0, 1));
}
else
{
Board[Row, Column] = 'C';
}
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 1, 0, PlayerName.Substring(0, 1)); //change all instances of H to playername.substring and convert to char
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, -1, 0, PlayerName.Substring(0, 1));
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, 1, PlayerName.Substring(0, 1));
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, -1, PlayerName.Substring(0, 1));
//flip diagonals
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 1, 1, PlayerName.Substring(0, 1));
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, -1, 1, PlayerName.Substring(0, 1));
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 1, -1, PlayerName.Substring(0, 1));
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, -1, -1, PlayerName.Substring(0, 1));
}
static void PlayGame(string PlayerName, int BoardSize)
{
char[,] Board = new char[BoardSize + 1, BoardSize + 1];
bool HumanPlayersTurn;
int Move = 0;
int HumanPlayerScore;
int ComputerPlayerScore;
bool MoveIsValid;
SetUpGameBoard(Board, BoardSize, PlayerName);
HumanPlayersTurn = false;
do
{
HumanPlayersTurn = !HumanPlayersTurn;
DisplayGameBoard(Board, BoardSize);
MoveIsValid = false;
do
{
if (HumanPlayersTurn)
{
Move = GetHumanPlayerMove(PlayerName);
}
else
{
Move = GetComputerPlayerMove(BoardSize);
}
MoveIsValid = CheckIfMoveIsValid(Board, Move, BoardSize);
} while (!MoveIsValid);
if (!HumanPlayersTurn)
{
Console.WriteLine("Press the Enter key and the computer will make its move");
Console.ReadLine();
}
MakeMove(Board, BoardSize, Move, HumanPlayersTurn, PlayerName);
} while (!GameOver(Board, BoardSize));
DisplayGameBoard(Board, BoardSize);
HumanPlayerScore = GetPlayerScore(Board, BoardSize, Convert.ToChar(PlayerName.Substring(0, 1))); //convert playername.substring to char
ComputerPlayerScore = GetPlayerScore(Board, BoardSize, 'C');
if (HumanPlayerScore > ComputerPlayerScore)
{
Console.WriteLine("Well done, " + PlayerName + ", you have won the game!");
}
else if (HumanPlayerScore == ComputerPlayerScore)
{
Console.WriteLine("That was a draw!");
}
else
{
Console.WriteLine("The computer has won the game!");
}
Console.WriteLine();
}
Edit
Python:
Answer:
random.seed()
BoardSize = 6
PlayerName = ""
Choice = ""
while Choice != "q":
DisplayMenu()
Choice = GetMenuChoice(PlayerName)
if Choice == "p":
PlayerName = GetPlayersName() #Runs the GetPlayerName function before the PlayGame function
PlayGame(PlayerName, BoardSize)
elif Choice == "e":
PlayerName = GetPlayersName()
elif Choice == "c":
BoardSize = ChangeBoardSize()
C#:
Answer:
static void Main(string[] args)
{
char Choice;
string PlayerName;
int BoardSize;
BoardSize = 6;
PlayerName = "H";
do
{
DisplayMenu();
Choice = GetMenuChoice(PlayerName);
switch (Choice)
{
case 'p':
PlayerName = GetPlayersName();
PlayGame(PlayerName, BoardSize);
break;
case 'e':
PlayerName = GetPlayersName();
break;
case 'c':
BoardSize = ChangeBoardSize();
break;
}
} while (Choice != 'q');
}
Flip Diagonally Edit
Python:
Answer:
def MakeMove(Board, BoardSize, Move, HumanPlayersTurn):
Row = Move % 10
Column = Move // 10
if HumanPlayersTurn:
Board[Row][Column] = "H"
else:
Board[Row][Column] = "C"
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 1, 0, playerInitial)
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, -1, 0, playerInitial)
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, 1, playerInitial)
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, -1, playerInitial)
#------------------------------------------------------ Flip Diagonally
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 1, 1, playerInitial)
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, -1, 1, playerInitial)
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 1, -1, playerInitial)
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, -1, -1, playerInitial)
#OR do all 8 directions Using a nested loop:
def MakeMove(Board, BoardSize, Move, HumanPlayersTurn):
Row = Move % 10
Column = Move // 10
if HumanPlayersTurn:
Board[Row][Column] = "H"
else:
Board[Row][Column] = "C"
for r in range(-1,2):
for c in range(-1,2):
if not (r == 0 and c == 0):
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, r, c)
C#:
Answer:
static void MakeMove(char[,] Board, int BoardSize, int Move, bool HumanPlayersTurn)
{
int Row;
int Column;
Row = Move % 10;
Column = Move / 10;
if (HumanPlayersTurn)
{
Board[Row, Column] = 'H';
}
else
{
Board[Row, Column] = 'C';
}
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 1, 0);
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, -1, 0);
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, 1);
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 0, -1);
//flip diagonals
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 1, 1);
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, -1, 1);
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, 1, -1);
FlipOpponentPiecesInOneDirection(Board, BoardSize, Row, Column, -1, -1);
}
Showing the User's score after a Game is finished. Edit
I have quite simply added ONE line of code in to the original section which calculated when the game was over.
It now just tells you your score against how many spaces were on the board originally.
Python:
Answer:
def PlayGame(PlayerName, BoardSize):
##------- Original code is still here. ------------
#------------------------------ Amended section ----------------------------------
HumanPlayerScore = GetPlayerScore(Board, BoardSize, "H")
ComputerPlayerScore = GetPlayerScore(Board, BoardSize, "C")
if HumanPlayerScore > ComputerPlayerScore:
print("Well done", PlayerName, ", you have won the game!")
#--------------------------------- Prints the players score total below, when the game has ended.
print("You captured", HumanPlayerScore, "Pieces. Out of", BoardSize * BoardSize)
elif HumanPlayerScore == ComputerPlayerScore:
print("That was a draw!")
else:
print("The computer has won the game!")
print()
C#:
Answer:
static void PlayGame(string PlayerName, int BoardSize)
{
char[,] Board = new char[BoardSize + 1, BoardSize + 1];
bool HumanPlayersTurn;
int Move = 0;
int HumanPlayerScore;
int ComputerPlayerScore;
bool MoveIsValid;
SetUpGameBoard(Board, BoardSize, PlayerName);
HumanPlayersTurn = false;
do
{
HumanPlayersTurn = !HumanPlayersTurn;
DisplayGameBoard(Board, BoardSize);
MoveIsValid = false;
do
{
if (HumanPlayersTurn)
{
Move = GetHumanPlayerMove(PlayerName);
}
else
{
Move = GetComputerPlayerMove(BoardSize);
}
MoveIsValid = CheckIfMoveIsValid(Board, Move, BoardSize);
} while (!MoveIsValid);
if (!HumanPlayersTurn)
{
Console.WriteLine("Press the Enter key and the computer will make its move");
Console.ReadLine();
}
MakeMove(Board, BoardSize, Move, HumanPlayersTurn, PlayerName);
} while (!GameOver(Board, BoardSize));
DisplayGameBoard(Board, BoardSize);
HumanPlayerScore = GetPlayerScore(Board, BoardSize, Convert.ToChar(PlayerName.Substring(0, 1))); //convert playername.substring to char
ComputerPlayerScore = GetPlayerScore(Board, BoardSize, 'C');
if (HumanPlayerScore > ComputerPlayerScore)
{
Console.WriteLine("Well done, " + PlayerName + ", you have won the game!");
Console.WriteLine("Your Pieces: " + HumanPlayerScore); //show human score
Console.WriteLine("Computer Pieces: " + ComputerPlayerScore); //show computer score
}
else if (HumanPlayerScore == ComputerPlayerScore)
{
Console.WriteLine("That was a draw!");
}
else
{
Console.WriteLine("The computer has won the game!");
Console.WriteLine("Your Pieces: " + HumanPlayerScore); //show human score
Console.WriteLine("Computer Pieces: " + ComputerPlayerScore); //show computer score
}
Console.WriteLine();
}
Section A Questions:Edit
Section A usually doesn't relate to the skeleton program. The type of question that will be asked is:Correct any mistakes I make here, please.
POINT TO NOTE, AS YOU ARE NOT ALLOWED A CALCULATOR YOU CAN USE THE COMPUTER AND YOUR PROGRAMMING LANGUAGE TO CALCULATE THINGS, worth learning it though.
- Representing denary values to binary, e.g. in last year's paper it was represent 55 using 8 bit unsigned binary.r
The way to go about this is, you will firstly know that 8 bits means there will be 8 numbers. The answer will be: 00110111 Learn how to convert from binary to denary and vice versa
- Two's compliment, this is basically a negative binary value, the 1 at the end (to your left) will usually tell you if it is negative, this is when it says it is signed.
Look at Two's compliment
- DON'T FORGET denary numbers which have a decimal e.g. 5.625. This is simply 1/2^n, where n is the next column to your right, so it goes 0.5, 0.25, 0.125, 0.0625. It halves each time.
- You will need to know the range of denary numbers that can be represented by a certain bit value. This is easily worked out, if it is positive 2^n, where n is the amount of bits, meaning if I was using 8 bits, I could represent 2^8 values which is 256 bits.
Don't forget to know the range of the negative bits too
- Look at Hexadecimal that is 0-9 A-F, usually represented in 4 bits.
- Understand why, for example hexadecimal is used instead of binary. This can be so it is faster to write, easier to read, takes less space to display on the screen...
- The amount of characters 7-bit ASCII and 8-Bit ASCII can represent. 7 bit can do 128 character and 8 bit is 256 characters same as doing 2^n.
- You need to know what an algorithm is, my definition is a set of instructions to solve a given problem independent of any programming language
- Know your what parity bits are, odd and even parity. It is validation usually used in communication to check if the message has been received without any errors.
- Know Hamming code - Hamming code uses multiple parity bits and understand how it works.
- Find errors given parity bits or hamming code, so by looking at if the value is odd or even depending on type of parity/hamming code.
- Know how to follow/read and understand an algorithm.
- FSM - finite state machines, read,follow and understand them.
- Transition tables
- Bit Maps, Vector graphics, resolutions, colour depth...
Advantages and disadvantages so mostly talk about the quality of image, the size the file is...
- Know what floor division is //, know what '%' is know what mod does, mod finds the remainder from dividing one number with another. 12 mod 10 (12% 10 in Python) would be 2.
- Structured Charts!
THESE ARE JUST SOME OF THE THINGS YOU'LL NEED TO KNOW. DON'T JUST RELY ON THIS AS I MAY HAVE MISSED SOME THINGS.
Section C - Potential Questions:Edit
State a User Defined Subroutine with only one parameter: 1)GetHumanPlayerMove 2)GetComputerPlayerMove 3)PrintLine 4)GetMenuChoice
'''State a User-defined subroutine whose only action is to produce output to the screen:''' 1)DisplayGameBoard 2)PrintLine 3)DisplayMenu
State a Local variable: 1)BoardSize 2)PlayerName 3)Choice
State a Global variable: 1)BoardSize 2)PlayerName 3)Choice
Variable that has a stepper role: 1)Row 2)Column
Variable that has a Gatherer role: 1) Score
Array variable: 1)Board
Describe the circumstances under which this structure in the Skeleton Program will stop repeating: When the int value of the Global Variable of BoardSize has been reached, or when the game has been won by a player.
Why has a For loop been chosen for the repetition structure : The program is fed the specified number of times it has to repeat ( e.g. BoardSize parameters ), therefore a for loop has been used as it allows the user/player to pick a specific range, and execute it the specified amount of times.
#State two reasons why subroutines should, ideally, not use global variables : 1)Easier re-use of routines in other programs; 2)Routine can be included in a library; 3)Helps to make the program code more understandable; 4)Ensures that the routine is self-contained // routine is independent of the rest of the program; 5)(Global variables use memory while a program is running) but local variables use memory for only part of the time a program is running; 6)reduces the possibility of undesirable side effects; 7) Using global variables makes a program harder to debug;
Name a variable used to store whole numbers : 1)Coordinates 2)BoardSize
State a User-defined subroutine that has exactly two parameters : (Arguments are values assigned to the parameter that is passed through) (Paramters are the names passed through the function or subroutine) 1)SetUpGameBoard(Board, Boardsize) 2)GameOver(Board, BoardSize) 3)CheckIfMoveIsValid(Board, Move): 4)DisplayGameBoard(Board, BoardSize) 5)PlayGame(PlayerName, BoardSize)
What does random.seed() do? 1) Makes it more random
Why has MOD 10 been used? 1) To get the second digit of a two digit number
State a Built-in function with exactly one parameter that returns an integer value: 1)GetHumanPlayerMove(PlayerName) ====> (gets the integer value of coordinates)
Explain what is meant by a boundary value 1)Boundary values are those just inside, on and just outside the range of allowed values
Built-in function that converts a string into a different data type : 1)int
Variable Types
Fixed
Value |
A variable that is given a value that then does not change for a duration of a loop |
---|---|
BoardSize | Is set to 6 towards the end of the code, but it could be most recent holder because it can be changed once the program has started |
Stepper | A variable used to move through an array or other data structure, often heading towards a fixed value and stepping through elements in an array |
Row | Is used to iterate through the board to give a total amount of rows |
Column | Is used to iterate through the board to give a total amount of columns |
Count | It iterates through the board adding the correct number of elements to create sufficient spaces |
Count2 | Will again iterate through the board which will adding "" to represent a blank space |
Most Recent Holder | A variable used to record the last thing inserted by a user or a the latest value being read from an array |
Playername | Will use the latest name entered throughout the program |
Choice | Will take the latest value inputted and compare against the available options and enter that menu. |
Move | It is assigned a value and it is used later in the program. |
Gatherer | A variable that accumulates or tallies up set of data and inputs. It is very useful for calculating totals or totals that will be used to calculate averages. |
Score | Tallies up total number of pieces of human/computer which gives the total score |
Most Wanted Holder | A variable that keeps track of the lowest or highest value in a set of inputs |
Not Sure | Please add if you think there is |
Follower | Used to keep check of a previous value of a variable, so that a new value can be compared |
Not Sure | There is None |
Temporary | A variable used for storing something for a very short period of time |
Coordinates | The program will only hold the coordinates for one turn, before holding the computer's and back around to the human's coordinates again |
Transformation | Used to store the result of a calculation involving more than one variable |
RowCount | stores result of adding the variables StartRow and RowDirection |
ColumnCount | stores result of adding the variables StartColumn and ColumnDirection |