411 REFERENCE · Wikibooks
A-level Computing/AQA/Paper 1/Skeleton program/2026
Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.
Ant Simulation This is for the 2026 AQA A-level Computer Science Specification (7517).
This is where suggestions can be made about what some of the questions might be and how we can solve them.
Please be respectful and do not vandalise the page, as this may affect students' preparation for exams!
Section C Mark distribution comparison
Mark distribution for this year:
The 2026 paper 1 will contain five questions worth 3, 5, 2, 2 and 1 mark(s) (12 total).
The 2025 paper contained 4 questions worth 2 marks each (8 total).
The 2024 paper contained 3 questions worth 11 marks in total (3+2+6=11).
The 2023 paper contained 6 questions worth 13 marks
The 2022 paper contained 5 questions worth 17 marks.
The 2021 paper contained 4 questions worth 13 marks.
Section C Predictions
Predictions:
Basically, Logically, technically, finally,
a) What is Encapsulation? b) What is a specific purpose of encapsulation being used in this program?
What is Inheritance? And give an example of polymorphism in the code?
Describe the 3 possibilities for what a worker ant can do in one stage.
Explain the difference between private and protected methods.
Note: at least for the Python skeleton code, there is no exception handling. In past papers which have had exception handling in the code, there were 1 to 2 mark questions asked about it in this section. Should exception handling come up, it would have to be in section D.
Section D Mark distribution comparison
Mark distribution for this year:
The 2026 paper 1 contains 4 questions: a 5 mark, an 8 mark and two 12 mark questions.
These marks include the screen capture(s), so the marks for the coding will be 1-2 marks lower.
The 2025 paper 1 contained 4 questions: a 5 mark, a 6 mark and two 14 mark questions.
The 2024 paper 1 contained 4 questions: a 5 mark, a 6 mark and two 14 mark questions.
The 2023 paper 1 contained 4 questions: a 5 mark, a 9 mark, a 10 mark and one 13 mark question.
The 2022 paper 1 contained 4 questions: a 5 mark, a 9 mark, a 11 mark and one 13 mark question.
The 2021 paper 1 contained 4 questions: a 6 mark, an 8 mark, a 9 mark and one 14 mark question.
The 2020 paper 1 contained 4 questions: a 6 mark, an 8 mark, a 11 mark and one 12 mark question.
The 2019 paper 1 contained 4 questions: a 5 mark, an 8 mark, a 9 mark and one 13 mark question.
The 2018 paper 1 contained 5 questions: a 2 mark, a 5 mark, two 9 mark and one 12 mark question.
The 2017 paper 1 contained 5 questions: a 5 mark, three 6 mark and one 12 mark question.
Section D Predictions
Current questions are speculation by contributors to this page
Section D actual contents;
Q1 Add an option in the menu to add food to a cell.
Q2 Edit the show area subroutine to display the area in the form of a grid.
Q3 Add an attribute to the cell class to make an obstacle in the cell that the ants cannot move into, and make simulation 2 have the 3rd column as obstacles.
Q4 Add a Soldier Ant class that moves randomly within 2 cells of its nest and when in the same cell as enemy ants, has a 90% chance of killing them. When there are more than 1 nest have 2 Soldier Ants spawn per nest.
Simulation 1
When inspecting a cell, ensure that the cell reference they have entered is within the bounds of the simulation, asking them to input a cell again again if not
C#
Coombe Wood School - South Croydon
Around line 60:
case "3":
int Row = 0, Column = 0;
//START OF CHANGE: loop until valid cell is entered
do
{
GetCellReference(ref Row, ref Column);
if (Row < 1 || Row > ThisSimulation.NumberOfRows || Column < 1 || Column > ThisSimulation.NumberOfColumns)
{
Console.WriteLine($"Invalid cell! Please enter a row between 1-{ThisSimulation.NumberOfRows} and a column between 1-{ThisSimulation.NumberOfColumns}.");
}
else
{
break;
}
} while (true);
//END OF CHANGE
//End of Change
//Note Before: This requires some amending as non integer values such as strings can still cause errors :P (Non-Coombe Wood School Student)
//Ok, it's been a week and it still hasn't been changed, it really needs to be fixed cause it still causes errors for non integer values :/ (Non-Coombe Wood School Student)
Around line 130:
//START OF CHANGE
public int NumberOfRows, NumberOfColumns;
protected int StartingFoodInNest, StartingNumberOfFoodCells, StartingNumberOfNests;
//END OF CHANGE
Java
Harington School
//add Simulation parameter, which must be included as an argument whenever getCellReference is called
static void getCellReference(IntWrapper row, IntWrapper column, Simulation thisSim) {
System.out.println();
do {
System.out.print("Enter row number: ");
row.value = Integer.parseInt(scanner.nextLine());
} while (row.value > thisSim.numberOfRows || row.value < 1);
do {
System.out.print("Enter column number: ");
column.value = Integer.parseInt(scanner.nextLine());
} while (column.value > thisSim.numberOfColumns || column.value < 1);
System.out.println();
}
Python
Salty Springs - credit to salty springs, hop off pls dont do trickss on itt :/
#part of the simulation class
def CheckCellExists(self, Row, Column):
if Row <= self._NumberOfRows and Row >= 1 and Column <= self._NumberOfColumns and Column >= 1:
return True
return False
#in Main()
elif Choice == "3":
Row = 0
Column = 0
Row, Column = GetCellReference() #get specific cell *howls*
while not ThisSimulation.CheckCellExists(Row,Column):
print("Invalid cell")
Row, Column = GetCellReference() #get specific cell
Add an error message when a blank grid space is entered and ask the user to retry
C#
Coombe Wood School - South Croydon
//START OF CHANGE "Add an error message when a blank grid space is entered"
Console.WriteLine();
while (true)
{
Console.Write("Enter row number: ");
string rowInput = Console.ReadLine();
if (string.IsNullOrWhiteSpace(rowInput) || !int.TryParse(rowInput, out Row) || Row <= 0)
{
Console.WriteLine("Invalid row input. Please enter a valid positive number.");
continue;
}
Console.Write("Enter column number: ");
string colInput = Console.ReadLine();
if (string.IsNullOrWhiteSpace(colInput) || !int.TryParse(colInput, out Column) || Column <= 0)
{
Console.WriteLine("Invalid column input. Please enter a valid positive number.");
continue;
}
// If both inputs are valid
break;
}
Console.WriteLine();
}
//END OF CHANGE "Add an error message when a blank grid space is entered"
</syntaxhighlight>
Java
King Olie of Harington School
static void getCellReference(IntWrapper row, IntWrapper column, int maxRow, int maxColumn) {
System.out.println();
System.out.print("Enter row number: ");
row.value = Integer.parseInt(scanner.nextLine());
while (row.value < 0 || row.value > maxRow) {
System.out.println();
System.out.println("That was invalid you little punk. Try Again.");
System.out.print("Enter row number: ");
row.value = Integer.parseInt(scanner.nextLine());
}
System.out.print("Enter column number: ");
column.value = Integer.parseInt(scanner.nextLine());
while (column.value < 0 || column.value > maxColumn) {
System.out.println();
System.out.println("That was invalid you little punk. Try Again.");
System.out.print("Enter row number: ");
row.value = Integer.parseInt(scanner.nextLine());
}
System.out.println();
}
Java
Harington School DM
//line 101
static void getCellReference(IntWrapper row, IntWrapper column) {
System.out.println();
System.out.print("Enter row number: ");
String inputRow = scanner.nextLine();
while(inputRow == "" || inputRow == " ") {
System.out.print("Invalid input, please try again\n");
inputRow = scanner.nextLine();
}
row.value = Integer.parseInt(inputRow);
System.out.print("Enter column number: ");
String inputCol = scanner.nextLine();
while(inputCol == "" || inputCol == " ") {
System.out.print("Invalid input. please try again\n");
inputCol = scanner.nextLine();
}
column.value = Integer.parseInt(inputCol);
System.out.println();
}
Python
13D - VC - Guildford County School
# replace GetCellReference() with this, around line 65, it adds a check to see if the selected spot is valid
def GetCellReference():
print()
while True:
row_input = input("Enter row number: ").strip()
if not row_input or not row_input.isdigit() or int(row_input) <= 0:
print("Invalid row input. Please enter a valid positive number.")
continue
col_input = input("Enter column number: ").strip()
if not col_input or not col_input.isdigit() or int(col_input) <= 0:
print("Invalid column input. Please enter a valid positive number.")
continue
# If both inputs are valid
Row = int(row_input)
Column = int(col_input)
break
print()
return Row, Column
Fix the error that occurs when trying to inspect a cell not in the range of the grid
C#
Coombe Wood School - South Croydon
public string GetCellDetails(int Row, int Column)
{
//START OF CHANGE
if (Row < 1 || Row > NumberOfRows || Column < 1 || Column > NumberOfColumns)
{
return $"Cell ({Row}, {Column}) is out of range.";
}
// END OF CHANGE
Add this to the start of the GetCellDetails
Python
13D - JK - Guildford County School
# replace GetCellDetails with this in the simulation class (around line 220), it adds a try/except for if the index is out of range
def GetCellDetails(self, Row, Column):
try:
CurrentCell = self._Grid[self.__GetIndex(Row, Column)]
Details = CurrentCell.GetDetails()
N = self.GetNestInCell(CurrentCell)
if N is not None:
Details += f"Nest present ({N.GetFoodLevel()} food)" + "\n\n"
if self.GetNumberOfAntsInCell(CurrentCell) > 0:
Details += "ANTS\n"
for A in self._Ants:
if A.InSameLocation(CurrentCell):
Details += A.GetDetails() + "\n"
Details += "\n\n"
if self.GetNumberOfPheromonesInCell(CurrentCell) > 0:
Details += "PHEROMONES\n"
for P in self._Pheromones:
if P.InSameLocation(CurrentCell):
Details += f"Ant {P.GetBelongsTo()} with strength of {P.GetStrength()}" + "\n\n"
Details += "\n\n"
return Details
except:
print("Cell was out of range\n")
Python
City of Norwich School
This fixes the issue where an IndexError is thrown when inspecting a cell outside of the bounds of the map. One unique case this fix catches is inspecting a cell at position (0,0). Row and column indexing starts at 1, so there should be no cell at (0, 0) and an IndexError should be thrown when trying to obtain it. However, this does not happen and cell details are still returned.
When inspecting a cell, the cell's position is converted to a grid list index using the __GetIndex(self, Row, Column) method. Cell instances are stored in a 1D list (_Grid), so a cell's position has to be converted to its index within the grid list. Grid list indices are calculated using the formula:
When the row is 0 and the column is 0, this equation evaluates to a negative value regardless of which simulation is used. For example, this evaluates to -6 when using simulation 1 as it has a map with 5 rows and 5 columns. Negative indices are still valid in Python, but unlike positive indices, they go from right to left and indexing starts at -1. As a result, a cell instance is still obtained and an IndexError is not thrown.
The following fix catches all erroneous cases except for empty strings, non-numeric characters and decimals. The fix begins at line 38 in the program in the Main() subroutine. while Choice != "9":
DisplayMenu()
Choice = GetChoice()
if Choice == "1":
print(ThisSimulation.GetDetails())
elif Choice == "2":
StartRow = 0
StartColumn = 0
EndRow = 0
EndColumn = 0
StartRow, StartColumn = GetCellReference()
EndRow, EndColumn = GetCellReference()
print(ThisSimulation.GetAreaDetails(StartRow, StartColumn, EndRow, EndColumn))
elif Choice == "3":
Row = 0
Column = 0
# Change start
valid_cell = False
while not valid_cell:
Row, Column = GetCellReference()
if (Row > 0
and Column > 0
and Row <= SimulationParameters[1]
and Column <= SimulationParameters[2]):
valid_cell = True
else:
print("Invalid cell position!")
# Change end
print(ThisSimulation.GetCellDetails(Row, Column))
elif Choice == "4":
ThisSimulation.AdvanceStage(1)
print("Simulation moved on one stage\n")
elif Choice == "5":
NumberOfStages = int(input("Enter number of stages to advance by: "))
ThisSimulation.AdvanceStage(NumberOfStages)
print(f"Simulation moved on {NumberOfStages} stages" + "\n")
Simulation 2
Fix the error of the cell still increasing pheromones after it is empty
C#
AL- Coombe Wood School - South Croydon
public void AdvanceStage(int NumberOfStages)
{
for (int Count = 1; Count <= NumberOfStages; Count++)
{
List<Pheromone> PheromonesToDelete = new List<Pheromone>();
foreach (Pheromone P in Pheromones)
{
P.AdvanceStage(Nests, Ants, Pheromones);
if (P.GetStrength() == 0)
{
PheromonesToDelete.Add(P);
}
}
foreach (Pheromone P in PheromonesToDelete)
{
Pheromones.Remove(P);
}
foreach (Ant A in Ant)
{
A.AdvanceStage(Nests, Ants, Pheromones);
Cell CurrentCell = Grid[GetIndex(A.GetRow(), A.GetColumn())];
if (A.GetFoodCarried() > 0 && A.IsAtOwnNest())
{
AddFoodToNest(A.GetFoodCarried(), A.GetRow(), A.GetColumn());
A.UpdateFoodCarried(-A.GetFoodCarried());
}
else if (CurrentCell.GetAmountOfFood() > 0 && A.GetFoodCarried() == 0)
{
int FoodObtained;
do
{
FoodObtained = RGen.Next(1, A.GetFoodCapacity() + 1);
} while (FoodObtained > CurrentCell.GetAmountOfFood() || (A.GetFoodCarried() + FoodObtained) > A.GetFoodCapacity());
CurrentCell.UpdateFoodInCell(-FoodObtained);
A.UpdateFoodCarried(FoodObtained);
//start of change
//removes pheromones from empty cells
if (CurrentCell.GetAmountOfFood() == 0)
{
Pheromones.RemoveAll(P => P.InSameLocation(CurrentCell));
}
//end of change
}
else
{
if (A.GetFoodCarried() > 0)
{
UpdateAntsPheromoneInCell(A);
}
A.ChooseCellToMoveTo(GetIndicesOfNeighbours(A.GetRow(), A.GetColumn()),
GetIndexOfNeighbourWithStrongestPheromone(A.GetRow(), A.GetColumn()));
}
}
foreach (Nest N in Nests)
{
N.AdvanceStage(Nests, Ants, Pheromones);
}
}
When selecting the option 'Display area details', selecting an area by using a point further from the top-left than the second point results in nothing being displayed. Fix this error such that, when this is input, it displays the same result if the points were input in the other order
C#
DA- Coombe Wood School - South Croydon
public string GetAreaDetails(int StartRow, int StartColumn, int EndRow, int EndColumn)
{
//start of changes
if (StartRow > EndRow)
{
int temp = StartRow;
StartRow = EndRow;
EndRow = temp;
}
if (StartColumn > EndColumn)
{
int temp = StartColumn;
StartColumn = EndColumn; EndColumn = temp;
}
//end of changes
string Details = "";
for (int Row = StartRow; Row <= EndRow; Row++)
{
for (int Column = StartColumn; Column <= EndColumn; Column++)
{
Details += $"{Row}, {Column}: ";
Cell TempCell = Grid[GetIndex(Row, Column)];
if (GetNestInCell(TempCell) != null)
{
Details += "| Nest | ";
}
int NumberOfAnts = GetNumberOfAntsInCell(TempCell);
if (NumberOfAnts > 0)
{
Details += $"| Ants: {NumberOfAnts} | ";
}
int NumberOfPheromones = GetNumberOfPheromonesInCell(TempCell);
if (NumberOfPheromones > 0)
{
Details += $"| Pheromones: {NumberOfPheromones} | ";
}
int AmountOfFood = TempCell.GetAmountOfFood();
if (AmountOfFood > 0)
{
Details += $"| {AmountOfFood} food | ";
}
Details += Environment.NewLine;
}
}
return Details;
}
Python
LMW- Caistor Grammar School - Caistor
elif Choice == "2":
StartRow = 0
StartColumn = 0
EndRow = 0
EndColumn = 0
StartRow, StartColumn = GetCellReference()
EndRow, EndColumn = GetCellReference()
StartRow,EndRow=min(StartRow,EndRow),max(StartRow,EndRow)
StartColumn,EndColumn=min(StartColumn,EndColumn),max(StartColumn,EndColumn)
print(ThisSimulation.GetAreaDetails(StartRow, StartColumn, EndRow, EndColumn))
Fix the error where the game ends without a message when there are no more ants remaining
C#
KO- Coombe Wood School - South Croydon
public void AdvanceStage(int NumberOfStages)
{
for (int Count = 1; Count <= NumberOfStages; Count++)
{
List<Pheromone> PheromonesToDelete = new List<Pheromone>();
foreach (Pheromone P in Pheromones)
{
P.AdvanceStage(Nests, Ants, Pheromones);
if (P.GetStrength() == 0)
{
PheromonesToDelete.Add(P);
}
}
foreach (Pheromone P in PheromonesToDelete)
{
Pheromones.Remove(P);
}
foreach (Ant A in Ants)
{
A.AdvanceStage(Nests, Ants, Pheromones);
Cell CurrentCell = Grid[GetIndex(A.GetRow(), A.GetColumn())];
if (A.GetFoodCarried() > 0 && A.IsAtOwnNest())
{
AddFoodToNest(A.GetFoodCarried(), A.GetRow(), A.GetColumn());
A.UpdateFoodCarried(-A.GetFoodCarried());
}
else if (CurrentCell.GetAmountOfFood() > 0 && A.GetFoodCarried() == 0)
{
int FoodObtained;
do
{
FoodObtained = RGen.Next(1, A.GetFoodCapacity() + 1);
} while (FoodObtained > CurrentCell.GetAmountOfFood() || (A.GetFoodCarried() + FoodObtained) > A.GetFoodCapacity());
CurrentCell.UpdateFoodInCell(-FoodObtained);
A.UpdateFoodCarried(FoodObtained);
}
else
{
if (A.GetFoodCarried() > 0)
{
UpdateAntsPheromoneInCell(A);
}
A.ChooseCellToMoveTo(GetIndicesOfNeighbours(A.GetRow(), A.GetColumn()),
GetIndexOfNeighbourWithStrongestPheromone(A.GetRow(), A.GetColumn()));
}
}
foreach (Nest N in Nests)
{
N.AdvanceStage(Nests, Ants, Pheromones);
} // start of change
if (Ants.Count == 0)
{
Console.WriteLine("game over");
Console.ReadKey();
Environment.Exit(0);
} // end of change
}
}
Python
AE - Guildford County Sixth
At the end of the simulation.advancestage() method
if len(self._Ants) == 0:
print("Simulation is ending at",self._Stage," because no more Ants remain")
self.Running = False
break
Limit skippable stages so the user can't skip straight to when the ants die (adds more playability)
C#
AS- Coombe Wood School - South Croydon
Simulation ThisSimulation = new Simulation(SimulationParameters);
string Choice;
Do
Case 5 replace the code with this code:
case "5":
//start of change
Console.Write("Enter number of stages to advance by (max 5): ");
int NumberOfStages = Convert.ToInt32(Console.ReadLine());
if (NumberOfStages > 5)
{
Console.WriteLine("You can't advance more then 5 stages");
NumberOfStages = 5;
}
else if (NumberOfStages < 1)
{
Console.WriteLine("You have to atleast advance 1 stage.");
NumberOfStages = 1;
}
ThisSimulation.AdvanceStage(NumberOfStages);
Console.WriteLine($"Simulation moved on {NumberOfStages} stages{Environment.NewLine}");//end of change
break;
Python
13C - NC - Guildford County School#import copy module
import copy
#start of change
elif Choice == "5":
backupsimulation=copy.deepcopy(ThisSimulation)
print(backupsimulation.GetDetails())
NumberOfStages = int(input("Enter number of stages to advance by: "))
ThisSimulation.AdvanceStage(NumberOfStages)
if ThisSimulation._Ants==[]:
print('you have advanced too many stages (all ants dead)')
ThisSimulation=backupsimulation
print(f"Simulation moved on {NumberOfStages} stages" + "\n")
#end of change
Simulation 3
Simulation 4
Prevent nests from culling ants from other nests
Python
NG - Lancaster Royal Grammar School - Lancaster
## START OF CHANGE ~line 421
def AdvanceStage(self, Nests, Ants, Pheromones):
if Ants is None:
return
AntsToCull = 0
Count = 0
for A in Ants:
if self.IsAntInNest(A):
if A.GetTypeOfAnt() == "queen":
Count += 10
else:
Count += 2
self.ChangeFood(-int(Count))
NestAnts = [A for A in Ants if self.IsAntInNest(A)]
if self._FoodLevel == 0 and len(NestAnts) > 0:
AntsToCull += 1
if self._FoodLevel < len(NestAnts):
AntsToCull += 1
if self._FoodLevel < len(NestAnts) * 5:
AntsToCull += 1
if AntsToCull > len(NestAnts):
AntsToCull = len(NestAnts)
random.shuffle(Ants)
Pos = 0
while AntsToCull > 0 and len(Ants) > Pos:
if self.IsAntInNest(Ants[Pos]):
if Ants[Pos].GetTypeOfAnt() == "queen":
self._NumberOfQueens -= 1
Ants.pop(Pos)
AntsToCull -= 1
else:
Pos += 1
else:
for A in range(1, self._NumberOfQueens + 1):
RNo1 = random.randint(0, 99)
if RNo1 < 50:
RNo2 = random.randint(0, 99)
if RNo2 < 2:
Ants.append(QueenAnt(self._Row, self._Column, self._Row, self._Column))
else:
Ants.append(WorkerAnt(self._Row, self._Column, self._Row, self._Column))
return Nests, Ants, Pheromones
def IsAntInNest(self, Ant):
return (Ant.GetNestRow() == self._Row and Ant.GetNestColumn() == self._Column)
## END OF CHANGE
General Questions
Have the program exit when the user decides to quit
C#
DO - Coombe Wood School - South Croydon
Line 71 - After the get choice
//start of change
if (Choice == "9")
{
Environment.Exit(0);
}
Console.ReadLine();
//End of Change
Python
13D - JK - Guildford County School
#Line 45 - after the processing for the other inputs
#start of change
if Choice == "9":
quit()
#End of Change
Fix the error in selecting the simulation when a value between 1 and 4 is not entered
C#
RT - Coombe Wood School - South Croydon
static void Main()
{
List<int> SimulationParameters = new List<int>();
Console.Write("Enter simulation number: ");
string SimNo = Console.ReadLine();
switch (SimNo)
{
case "1":
SimulationParameters = new List<int> { 1, 5, 5, 500, 3, 5, 1000, 50 };
break;
case "2":
SimulationParameters = new List<int> { 1, 5, 5, 500, 3, 5, 1000, 100 };
break;
case "3":
SimulationParameters = new List<int> { 1, 10, 10, 500, 3, 9, 1000, 25 };
break;
case "4":
SimulationParameters = new List<int> { 2, 10, 10, 500, 3, 6, 1000, 25 };
break;
//start of change
default:
Console.WriteLine("Enter a number between 1-4");
Main();
break;
}
;
//End of Change
Java
LT - Harington Schoolpublic static void main(String[] args) throws Exception
{
ArrayList<Integer> simulationParameters = new ArrayList<Integer>();
while(simulationParameters.isEmpty())
{
System.out.print("Enter simulation number: ");
String simNo = scanner.nextLine();
switch (simNo)
{
case "1":
simulationParameters = new ArrayList<Integer>(Arrays.asList(1, 5, 5, 500, 3, 5, 1000, 50));
break;
case "2":
simulationParameters = new ArrayList<Integer>(Arrays.asList(1, 5, 5, 500, 3, 5, 1000, 100));
break;
case "3":
simulationParameters = new ArrayList<Integer>(Arrays.asList(1, 10, 10, 500, 3, 9, 1000, 25));
break;
case "4":
simulationParameters = new ArrayList<Integer>(Arrays.asList(2, 10, 10, 500, 3, 6, 1000, 25));
break;
default:
System.out.println("\nInvalid Input!");
break;
}
System.out.println();
}
Python
13C - ZH - Guildford County School def Main():
SimulationParameters = []
SimNo = input("Enter simulation number (1-4): ")
while SimNo not in ["1","2","3","4"]:
SimNo = input("Enter simulation number (1-4): ")
Add an option to create a new nest. This should be allowed to be done only once per simulation. You do not need to check whether there is a nest already at that location
Java
Harington School - LC
//Start around line 70 after case 5
//Create new local boolean variable nestCreated
//Start of change
case "6":
if (nestCreated == true) {
System.out.println("New nest already created, you can only create 1");
}
else {
IntWrapper nestRow = new IntWrapper(0), nestColumn = new IntWrapper(0);
getCellReference(nestRow, nestColumn);
thisSimulation.setUpANestAt(nestRow.value, nestColumn.value);
nestCreated = true;
}
break;
//End of change
Java
King Olie of Harington School
//Start around line 70 after case 5
//Create new static boolean variable doneAddedNess set to false
case "6":
if(!doneAddedNess) {
System.out.println("Adding a ness ");
System.out.println("x: ");
int x = scanner.nextInt();
System.out.println("y: ");
int y = scanner.nextInt();
thisSimulation.setUpANestAt(x,y);
doneAddedNess = true;
}
else {
System.out.println("you have already added a nest this game silly.");
}
break;
// in displayMenu
System.out.println("6. Add a ness (once per game)");
Python
JD - John Port Spencer Academy
CHANGE ~ line 54
elif Choice == "6":
if nestCreated != True:
print("Add a nest")
x = int(input("X coord: "))
y = int(input("Y coord: "))
ThisSimulation.SetUpANestAt(x, y)
nestCreated = True
else:
print("Already added a nest")
END CHANGE
elif Choice == "9":
quit()
def DisplayMenu():
print()
print("1. Display overall details")
print("2. Display area details")
print("3. Inspect cell")
print("4. Advance one stage")
print("5. Advance X stages")
CHANGE FOR OPTION 6 ADDED
print("6. Add a nest (1 per game)")
ENDCHANGE
Add an end to the simulation when there are 0 ants
C#
Coombe Wood School - South Croydon
Around line 60:
//start of change
// Add to end of Advance stage:
if (Ants.Count == 0)
{
Console.WriteLine("All ants are dead. Game Over!");
Console.ReadKey();
Environment.Exit(0);
}
//END OF CHANGE
Java
King Olie of Harington School
public void advanceStage(int numberOfStages) {
boolean anyAntsLeft = false;
for (int count = 1; count <= numberOfStages; count++) {
anyAntsLeft = false;
ArrayList<Pheromone> pheromonesToDelete = new ArrayList<Pheromone>();
for (Pheromone p : pheromones) {
p.advanceStage(nests, ants, pheromones);
if (p.getStrength() == 0) {
pheromonesToDelete.add(p);
}
}
for (Pheromone p : pheromonesToDelete) {
pheromones.remove(p);
}
for (Ant a : ants) {
a.advanceStage(nests, ants, pheromones);
anyAntsLeft = true;
Cell currentCell = grid.get(getIndex(a.getRow(), a.getColumn()));
if ((a.getFoodCarried() > 0) && a.isAtOwnNest()) {
addFoodToNest(a.getFoodCarried(), a.getRow(), a.getColumn());
a.updateFoodCarried(-a.getFoodCarried());
} else if ((currentCell.getAmountOfFood() > 0) && (a.getFoodCarried() == 0) && (a.getFoodCapacity() > 0)) {
int foodObtained;
do {
foodObtained = rGen.nextInt(a.getFoodCapacity()) + 1;
} while (!(foodObtained <= currentCell.getAmountOfFood()
&& (a.getFoodCarried() + foodObtained) <= a.getFoodCapacity()));
currentCell.updateFoodInCell(-foodObtained);
a.updateFoodCarried(foodObtained);
} else {
if (a.getFoodCarried() > 0) {
updateAntsPheromoneInCell(a);
}
a.chooseCellToMoveTo(getIndicesOfNeighbours(a.getRow(), a.getColumn()), getIndexOfNeighbourWithStrongestPheromone(a.getRow(), a.getColumn()));
}
}
for (Nest n : nests) {
n.advanceStage(nests, ants, pheromones);
}
}
if(!anyAntsLeft) {
System.out.println("No ants detected ending sim");
System.exit(0);
// i know this is a bad habit. But i dont know other ways of stopping it easily without changing code in diffrent areas... laziness wins.
}
}
Python
13D - JS - Guildford County School
# Around line 20, just before DisplayMenu() and just after Choice = ""
# start of change
if len(ThisSimulation._Ants) == 0:
print("No more ants, you lost!")
quit()
# End of Change
Python
LMW - Caistor Grammar School - Caistor
def GetDetails(self):
Details = ""
for Row in range(1, self._NumberOfRows + 1):
for Column in range(1, self._NumberOfColumns + 1):
Details += f"{Row}, {Column}: "
TempCell = self._Grid[self.__GetIndex(Row, Column)]
if self.GetNestInCell(TempCell) is not None:
Details += "| Nest | "
NumberOfAnts = self.GetNumberOfAntsInCell(TempCell)
if NumberOfAnts > 0:
Details += f"| Ants: {NumberOfAnts} | "
# Edit Begins Here
elif NumberOfAnts == 0:
print("No Ants Remaining - Simulation over")
quit()
# Edit Ends Here
NumberOfPheromones = self.GetNumberOfPheromonesInCell(TempCell)
if NumberOfPheromones > 0:
Details += f"| Pheromones: {NumberOfPheromones} | "
AmountOfFood = TempCell.GetAmountOfFood()
if AmountOfFood > 0:
Details += f"| {AmountOfFood} food | "
Details += "\n"
return Details
If the Queen is dead the simulation will end
C#
AL- Coombe Wood School - South Croydon
public override void AdvanceStage(List<Nest> Nests, List<Ant> Ants, List<Pheromone> Pheromones)
{
if (Ants == null)
{
return;
}
int AntsToCull = 0;
int Count = 0;
foreach (Ant A in Ants)
{
if (A.GetNestRow() == Row && A.GetNestColumn() == Column)
{
if (A.GetTypeOfAnt() == "queen")
{
Count += 10;
}
else
{
Count += 2;
}
}
//start of change
if (NumberOfQueens < 1)
{
Console.WriteLine("The Queen has died, the simulation cannot continue");
System.Threading.Thread.Sleep(2000);
Environment.Exit(0);
} // end of change
}
JAVA
King Olie of Harington School
public void advanceStage(int numberOfStages)
{
boolean queen = false;
for (int count = 1; count <= numberOfStages; count++)
{
queen = false;
for (Ant a : ants)
{
a.advanceStage(nests, ants, pheromones);
if(a.getTypeOfAnt() == "queen")
{
queen = true;}
}
}
if(!queen)
{
System.out.println("No queen detected ending sim");
System.exit(0);
// i know this is a bad habit. But i dont know other ways of stoping it easily without changing code in diffrent areas.
}
}
// it looks like code is ending like and some if and for loops but I just removed the inside to shorten it but kepts some stuff so you can ruffly see where it should be.
// this code lookes terible becuse i cant figgure out how to present it well in the edditer please feel free to make it look better. I tried my best.
Python
AE - Guildford County Sixth
At the end of Simulaton.AdvanceStage()
queen = False
for i in self._Ants:
if i.GetTypeOfAnt() == "queen":
queen = True
if not queen:
print("Simulation is ending at",self._Stage," because no more queen ants remain")
self.Running = False
break
Add an explanation of each simulation before the user is prompted to input the simulation number
C#
KW - Coombe Wood School - South Croydon
// START OF CHANGE - below the FIRST SimNo SWITCH
switch (SimNo)
{
case "1":
Console.WriteLine("This is simulation 1, a 5x5 grid with one nest and three food sources when started. Pheromone strength: 1000 with decay 50");
break;
case "2":
Console.WriteLine("This is simulation 2, a 5x5 grid with one nest and three food sources when started. Pheromone strength: 1000 with decay 100");
break;
case "3":
Console.WriteLine("This is simulation 3, a 10x10 grid with one nest and three food sources when started. Pheromone strength: 1000 with decay 25");
break;
case "4":
Console.WriteLine("This is simulation 4, a 10x10 grid with two nests and three food sources when started. Pheromone strength: 1000 with decay 25");
break;
}
// END OF CHANGE
</syntaxhighlight>
JAVA
King Olie of Harington School
//START OF CHANGE
static void displaySims() {
// yes i just copy and pasted the values from the Preliminary Material
System.out.println("1. Simulation 1 is a 5×5 grid with one nest. Five ants belong to that nest (one queen and four\r\n"
+ "workers). At the start of the simulation the nest has 500 food units in it. There are three sources\r\n"
+ "of food in the grid. It is possible that some of the food sources could be in the same cell as each\r\n"
+ "other. The strength of a new pheromone is 1000 and the pheromone decay rate is\r\n"
+ "50 per stage");
System.out.println("2. Simulation 2 is the same as simulation 1 except the pheromone decay rate is 100 per stage");
System.out.println("3. Simulation 3 is a 10×10 grid with one nest. Nine ants belong to that nest (one queen and eight\r\n"
+ "workers). At the start of the simulation the nest has 500 food units in it. There are three sources\r\n"
+ "of food in the grid. It is possible that some of the food sources could be in the same cell as each\r\n"
+ "other. The strength of a new pheromone is 1000 and the pheromone decay rate is\r\n"
+ "25 per stage");
System.out.println("4. Simulation 4 is a 10×10 grid with two nests. Six ants belong to each nest (one queen and five\r\n"
+ "workers). At the start of the simulation each nest has 500 food units in it. There are three sources\r\n"
+ "of food in the grid. It is possible that some of the food sources could be in the same cell as each\r\n"
+ "other. The strength of a new pheromone is 1000 and the pheromone decay rate is 25 per stage");
System.out.println("5. custom sim (added by king olie)");
}
//END OF CHANGE
Python
13D - JK - Guildford County School
#Add this function anywhere in the program
#start of change
def printSimDetails(params):
print()
print("This Simulation has:")
print(" - " + str(params[0]) + " nests")
print(" - a " + str(params[1]) + "x" + str(params[2]) + " grid")
print(" - " + str(params[3]) + " starting food in the nests")
print(" - " + str(params[4]) + " cells with food to start with")
print(" - " + str(params[5]) + " ants in each nest")
print(" - " + str(params[6]) + " strength for new pheremones")
print(" - " + str(params[7]) + " pheremone decay")
print()
#End of Change
#put this just after the elifs to check simulation parameters (around line 20)
#start of change
printSimDetails(SimulationParameters)
#end of change
Add a custom simulation. The user should be able to enter their own values for the simulation parameters
JAVA
King Olie of Harington School
//START OF CHANGE
case "5": // new sim
System.out.println("Please enter the values for the following: ");
System.out.println("Starting number of nests: ");
int startNumberOfNests = scanner.nextInt();
System.out.println("Number of Rows");
int numberOfRows = scanner.nextInt();
System.out.println("Number of columns: ");
int numberOfColums = scanner.nextInt();
System.out.println("Starting Food In Nest: ");
int startingFoodInNests = scanner.nextInt();
System.out.println("Starting number of food cells: ");
int startingNumberOfFoodCells = scanner.nextInt();
System.out.println("Starting ants in nest: ");
int startingAntsInNests = scanner.nextInt();
System.out.println("New pheromone strength: ");
int newPheromoneStrength = scanner.nextInt();
System.out.println("New pheromone Decay: ");
int newPheromoneDecay = scanner.nextInt();
simulationParameters = new ArrayList<Integer>(Arrays.asList(startNumberOfNests, numberOfRows, numberOfColums, startingFoodInNests, startingNumberOfFoodCells, startingAntsInNests, newPheromoneStrength, newPheromoneDecay));
break;
//END OF CHANGE
Python
13A - RH - Aylesbury Grammar School
# Line 20
# CHANGE
elif SimNo == "5":
print("Please enter the following values")
startNumberOfNests = input("Starting number of nests: ")
numberOfRows = input("Number of rows: ")
numberOfColumns = input("Number of columns: ")
startingFoodInNests = input("Starting Food In Nest: ")
startingNumberOfFoodCells = input("Starting number of food cells: ")
startingAntsInNests = input("Starting ants in nest: ")
newPheromoneStrength = input("New pheromone strength: ")
newPheromoneDecay = input("New pheromone Decay: ")
SimulationParameters = [
startNumberOfNests,
numberOfRows,
numberOfColumns,
startingFoodInNests,
startingNumberOfFoodCells,
startingAntsInNests,
newPheromoneStrength,
newPheromoneDecay
]
# END CHANGEsam
Add a simulation number 5 with its own parameters
C#
Coombe Wood School - South Croydon
Around line 36
//START OF CHANGE
case "5":
SimulationParameters = new List<int> {3, 15,15,500 , 3, 4, 1000, 25};
break;
//END OF CHANGE
//YOU CAN CHANGE ANY OF THE NUMBERS IN THE LIST TO MAKE YOUR OWN SIMULATION
JAVA
King Olie of Harington School
Line ~82
//START OF CHANGE
case "5":
simulationParameters = new ArrayList<Integer>(Arrays.asList(300, 105,105,5000 , 30, 40, 1000000, 2500));
break;
//END OF CHANGE
//YOU CAN CHANGE ANY OF THE NUMBERS IN THE LIST TO MAKE YOUR OWN SIMULATION
Python
13D - JT - Guildford County School
#Around line 19, after the elif for SimNo 4
#start of change
elif SimNo == "5":
SimulationParameters = [3, 20, 20, 1000, 6, 12, 2000, 50]
#End of Change
Make the grid be displayed as an actual grid
C#
DA - Coombe Wood School - South Croydon
//You need to add all 3 parts for it to work add the red bits only, the black is just to see where
//Around line 67
DisplayMenu();
Choice = GetChoice();
switch (Choice)
{
case "1":
Console.WriteLine(ThisSimulation.GetDetails());
break;
case "2":
int StartRow = 0, StartColumn = 0, EndRow = 0, EndColumn = 0;
GetCellReference(ref StartRow, ref StartColumn);
GetCellReference(ref EndRow, ref EndColumn);
Console.WriteLine(ThisSimulation.GetAreaDetails(StartRow, StartColumn, EndRow, EndColumn));
break;
case "3":
int Row = 0, Column = 0;
GetCellReference(ref Row, ref Column);
Console.WriteLine(ThisSimulation.GetCellDetails(Row, Column));
break;
case "4":
ThisSimulation.AdvanceStage(1);
Console.WriteLine($"Simulation moved on one stage{Environment.NewLine}");
break;
case "5":
Console.Write("Enter number of stages to advance by: ");
int NumberOfStages = Convert.ToInt32(Console.ReadLine());
ThisSimulation.AdvanceStage(NumberOfStages);
Console.WriteLine($"Simulation moved on {NumberOfStages} stages{Environment.NewLine}");
break;
//start of change
case "7";
ThisSimulation.DisplayGrid();
Break;
//end of change
//Around line 125
static void DisplayMenu()
{
Console.WriteLine();
Console.WriteLine("1. Display overall details");
Console.WriteLine("2. Display area details");
Console.WriteLine("3. Inspect cell");
Console.WriteLine("4. Advance one stage");
Console.WriteLine("5. Advance X stages");
//start of change
Console.WriteLine("7. Display grid view");
//end of change
Console.WriteLine("9. Quit");
Console.WriteLine();
Console.Write("> ");
}
//After the getdetails string ends, put this outside the brackets
public void DisplayGrid()
{
for (int row = 1; row <= NumberOfRows; row++)
{
for (int col = 1; col <= NumberOfColumns; col++)
{
Cell currentCell = Grid[GetIndex(row, col)];
string cellDisplay = "[";
bool hasContent = false;
if (GetNestInCell(currentCell) != null)
{
cellDisplay += "N";
hasContent = true;
}
if (GetNumberOfAntsInCell(currentCell) > 0)
{
cellDisplay += "A";
hasContent = true;
}
if (currentCell.GetAmountOfFood() > 0)
{
cellDisplay += "F";
hasContent = true;
}
if (GetNumberOfPheromonesInCell(currentCell) > 0)
{
cellDisplay += "P";
hasContent = true;
}
if (!hasContent)
{
cellDisplay += " ";
}
cellDisplay += "]";
Console.Write(cellDisplay + " ");
}
Console.WriteLine();
}
}
//END OF CHANGE
JAVA
King olie of Harington
public String getDetails() { // use format tools
String addes = "| %-35s ";
String layout = "";
String layerRowAdds = "-";
String layerRow = "";
String output = "";
String[] details = new String[numberOfColumns];
for (int i = 0; i < numberOfColumns; i++) {
layout += addes;
details[i] = "";
}
for (int i = 0; i < (38 * numberOfColumns); i++) {
layerRow += layerRowAdds;
}
layout += "|";
boolean didSomethink = false;
for (int row = 1; row <= numberOfRows; row++) {
for (int column = 1; column <= numberOfColumns; column++) {
Cell tempCell = grid.get(getIndex(row, column));
if (getNestInCell(tempCell) != null) {
details[column-1] += "Nest; ";
didSomethink = true;
}
int numberOfAnts = getNumberOfAntsInCell(tempCell);
if (numberOfAnts > 0) {
details[column-1] += "Ants: " + numberOfAnts + "; ";
didSomethink = true;
}
int numberOfPheromones = getNumberOfPheromonesInCell(tempCell);
if (numberOfPheromones > 0) {
details[column-1] += "Pheromones: " + numberOfPheromones + "; ";
didSomethink = true;
}
int amountOfFood = tempCell.getAmountOfFood();
if (amountOfFood > 0) {
details[column-1] += amountOfFood + " food; ";
didSomethink = true;
}
if(!didSomethink) {
details[column-1] = "BLANK";
}
didSomethink = false;
}
output += layerRow + "\n";
output += String.format(layout, details) + "\n";
for (int i = 0; i < numberOfRows; i++) {
details[i] = "";
}
}
output += layerRow + "\n";
return output;
}
Python - only works for a 5 x 5..SB - John Port Spencer Academy
def GetDetails(self):
print("GetDetails from Simulation - code started")
Details = "------------------------------------------------------------------------------------------------------------------------------------------------------------\n"
for Row in range(1, self._NumberOfRows + 1):
row = "|"
for Column in range(1, self._NumberOfColumns + 1):
count = 0
cell = ""
TempCell = self._Grid[self.__GetIndex(Row, Column)]
if self.GetNestInCell(TempCell) is not None:
cell += "Nest"
count += 1
NumberOfAnts = self.GetNumberOfAntsInCell(TempCell)
if NumberOfAnts > 0:
if count >= 1:
cell += f" Ants: {NumberOfAnts}"
else:
cell += f"Ants: {NumberOfAnts}"
count += 1
NumberOfPheromones = self.GetNumberOfPheromonesInCell(TempCell)
if NumberOfPheromones > 0:
if count >= 1:
cell += f" Pheromones: {NumberOfPheromones}"
else:
cell += f"Pheromones: {NumberOfPheromones}"
count += 1
AmountOfFood = TempCell.GetAmountOfFood()
if AmountOfFood > 0:
if count >= 1:
cell += f" {AmountOfFood} food"
else:
cell += f"{AmountOfFood} food"
count += 1
if count == 0:
cell += " "
cell = cell.center(30)
cell += "|"
row += cell
Details += row
num = len(row)
Details += f"\n{num*'-'}\n"
return Details
PythonRC
0:
item += f"Ants: {NumberOfAnts} "
NumberOfPheromones = self.GetNumberOfPheromonesInCell(TempCell)
if NumberOfPheromones > 0:
item += f"Pheromones: {NumberOfPheromones} "
AmountOfFood = TempCell.GetAmountOfFood()
if AmountOfFood > 0:
item += f"{AmountOfFood} food "
RowGrid.append(item)
Details.append(RowGrid)
return Details
def DisplayGrid(self):
for i in self.GetDetailsGrid():
for j in i:
print('|{:^32s}|'.format(j),end='')
print("")
print("")
Python
AE - Guildford County School
#method for the Simulation class
def DisplayGrid(self):
for row in range(0,self._NumberOfRows):
Details = ""
for column in range(self._NumberOfColumns):
Details += "|"
addSpace = True
CurrentCell = self._Grid[self.__GetIndex(row, column)]
N = self.GetNestInCell(CurrentCell)
if N is not None:
Details += f"Nest: ({N.GetFoodLevel()} food)"
addSpace = False
if self.GetNumberOfAntsInCell(CurrentCell) > 0:
Details += "Ants: " + str(self.GetNumberOfAntsInCell(CurrentCell))
addSpace = False
if self.GetNumberOfPheromonesInCell(CurrentCell) > 0:
Details += "Pheromones:"
for P in self._Pheromones:
if P.InSameLocation(CurrentCell):
Details += f"Ant {P.GetBelongsTo()}: strength = {P.GetStrength()}"
addSpace = False
if addSpace:
Details += " "
Details += "|"
print(Details)
print()
JAVA
Harington School - use of String.format() to evenly space the cell widths
public String getDetails() {
String cellFormat = "%-11s|";
String separator = "-";
for(int i=0; i<numberOfColumns; i++) {
separator += "------------";
}
String details = "";
for (int row = 1; row <= numberOfRows; row++) {
details += separator+"\n";
details+="|";
for (int column = 1; column <= numberOfColumns; column++) {
Cell tempCell = grid.get(getIndex(row, column));
String cellDetails = "";
if (getNestInCell(tempCell) != null) {
cellDetails += "N ";
}
int numberOfAnts = getNumberOfAntsInCell(tempCell);
if (numberOfAnts > 0) {
cellDetails += "A" + numberOfAnts + " ";
}
int numberOfPheromones = getNumberOfPheromonesInCell(tempCell);
if (numberOfPheromones > 0) {
cellDetails += "P" + numberOfPheromones + " ";
}
int amountOfFood = tempCell.getAmountOfFood();
if (amountOfFood > 0) {
cellDetails += "F" + amountOfFood + " ";
}
details += String.format(cellFormat, cellDetails);
}
details+="\n";
}
return details+separator;
}
Add appropriate error handling so that the program does not close when an invalid input is entered
C#
JD - Coombe Wood School - South Croydon
Changes takes place in the Main void, in the fifth switch case -
//START OF CHANGE
case "5":
Console.WriteLine("Enter in number of stages to advance, it must be under 20 digits");
string NumberOfStages = (Console.ReadLine()); //string used since it won't instantly crash the code when a "number" that's too long is input
if (NumberOfStages.Length > 19 || !NumberOfStages.All(char.IsDigit)) //the max ulong (unsigned 64 bit) number is 1.8x10^19, a 20 digit number. we exlude 20 digit numbers since if someone typed a 20 digit number bigger than 1.8x10^19, the code would crash. we also check to see if every character in the string is a digit
{
Console.WriteLine("Number entered is too large, or you have entered in letters. going back to main menu");
break;
}
ulong NumberOfStagesULong = (ulong)Convert.ToInt64(NumberOfStages); //converting string to ulong, so it can be used later
ThisSimulation.AdvanceStage((int)NumberOfStagesULong);
// END OF CHANGE
Console.WriteLine($"Simulation moved on {NumberOfStages} stages{Environment.NewLine}");
break;
Python
IH - BCSF - Leicester
this edits the main function between lines 9 and 74
def Main():
SimulationParameters = []
###
#
SimNo = input("Enter simulation number: ")
while SimNo not in ["1", "2", "3", "4"]:
SimNo = input("Enter simulation number: ")
if SimNo == "1":
SimulationParameters = [1, 5, 5, 500, 3, 5, 1000, 50]
elif SimNo == "2":
SimulationParameters = [1, 5, 5, 500, 3, 5, 1000, 100]
elif SimNo == "3":
SimulationParameters = [1, 10, 10, 500, 3, 9, 1000, 25]
elif SimNo == "4":
SimulationParameters = [2, 10, 10, 500, 3, 6, 1000, 25]
ThisSimulation = Simulation(SimulationParameters)
Choice = ""
while Choice != "9":
DisplayMenu()
Choice = GetChoice()
if Choice == "1":
print(ThisSimulation.GetDetails())
elif Choice == "2":
StartRow = 0
StartColumn = 0
EndRow = 0
EndColumn = 0
StartRow, StartColumn = GetCellReference()
EndRow, EndColumn = GetCellReference()
print(ThisSimulation.GetAreaDetails(StartRow, StartColumn, EndRow, EndColumn))
elif Choice == "3":
Row = 0
Column = 0
Row, Column = GetCellReference()
print(ThisSimulation.GetCellDetails(Row, Column))
elif Choice == "4":
ThisSimulation.AdvanceStage(1)
print("Simulation moved on one stage\n")
elif Choice == "5":
NumberOfStages = int(input("Enter number of stages to advance by: "))
ThisSimulation.AdvanceStage(NumberOfStages)
print(f"Simulation moved on {NumberOfStages} stages" + "\n")
input()
def DisplayMenu():
print()
print("1. Display overall details")
print("2. Display area details")
print("3. Inspect cell")
print("4. Advance one stage")
print("5. Advance X stages")
print("9. Quit")
print()
print("> ", end='')
def GetChoice():
Choice = input("pick a number: 1, 2, 3, 4, 5, 9")
while Choice not in ["1", "2", "3", "4", "5", "9"]:
Choice = input("pick a number: 1, 2, 3, 4, 5, 9")
return Choice
#
###
==='''Make a fighter ant class that fights and defends their nest from other types of ants'''===
{{CPTAnswerTab|JAVA}}
King Olie of Harington School
<syntaxhighlight lang="JAVA" line="1" start="1">
//START OF CHANGE
static class FighterAnt extends Ant{
// I wanted everything in one class so some best practice may not be used.
int health = 100;
FighterAnt(int startRow, int startColumn, int nestInRow, int nestInColumn) {
super(startRow, startColumn, nestInRow, nestInColumn);
typeOfAnt = "fighter";
health = 100;
}
//ant 0 is this ant and ant 1 is the other ant and it is the winner of the fight. only one surviver
// if healths out of 100 that could be the prob of hitting
public int fightEachOther(int healthOfOtherAnt) {
Random ranGen = new Random();
// you add 1 to each as the next int is exclusive with the last value. aka if 100 was input the output would be from 0-99
if(healthOfOtherAnt < health) { // this ant wins
healthOfOtherAnt -= ranGen.nextInt(healthOfOtherAnt +1);
health -= ranGen.nextInt((int) (health * 0.25 +1));
}
else if(healthOfOtherAnt > health) { // other ant wins
health -= ranGen.nextInt(health + 1);
healthOfOtherAnt -= ranGen.nextInt((int) (healthOfOtherAnt * 0.25 +1));
}
else { // luck, may the best win.
healthOfOtherAnt -= ranGen.nextInt(healthOfOtherAnt +1);
health -= ranGen.nextInt(health +1);
}
// if if statements in java are only 1 line long this works. no brakets needed
if (health <= 0 && healthOfOtherAnt <= 0 )
return 2; // both ants died
else if(health <= 0)
return 1; // this ant lost
else if(healthOfOtherAnt <= 0)
return 0; // this ant won
else
return 99; // no ants died
return 0;
}
// following pheromones to fight / protect food.
@Override
public void chooseCellToMoveTo(ArrayList<Integer> listOfNeighbours, int indexOfNeighbourWithStrongestPheromone) {
IntWrapper r, c;
if (amountOfFoodCarried > 0) {
if (row > nestRow) {
row -= 1;
} else if (row < nestRow) {
row += 1;
}
if (column > nestColumn) {
column -= 1;
} else if (column < nestColumn) {
column += 1;
}
} else if (indexOfNeighbourWithStrongestPheromone == -1) {
int indexToUse = chooseRandomNeighbour(listOfNeighbours);
r = new IntWrapper(row);
c = new IntWrapper(column);
changeCell(indexToUse, r, c);
row = r.value;
column = c.value;
} else {
int indexToUse = listOfNeighbours.indexOf(indexOfNeighbourWithStrongestPheromone);
r = new IntWrapper(row);
c = new IntWrapper(column);
changeCell(indexToUse, r, c);
row = r.value;
column = c.value;
}
}
public int getAntsHealth() {
return health;
}
}
//END OF CHANGE
// this is at no means complete. please amend and add more functionality and add your name. This is a mock up.
Add an option to read a file which can be used for the Simulation Parameters
Test File
name > sim1file.txt
Content:
--start file--
10
50
50
690
676
420
5000
5000
--end file--
JAVA
king Olie of Harington
System.out.println("Select (S)imulation or load a (F)ile: ");
String enterOption = scanner.nextLine();
enterOption.toUpperCase();
if(enterOption.contentEquals("F")) {
System.out.println("Enter File name with extention (.txt): ");
String file = scanner.nextLine();
/**
* file should be:
* value1
* value2
* value3
* ...
*/
simulationParameters = new ArrayList<Integer>();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null){
simulationParameters.add(Integer.parseInt(line));
}
}
else {
System.out.print("Enter simulation number: ");
Edit the Simulation class to add the same amount of food to the food cells as is added to each nest
JAVA
king Olie of HaringtonSimulation(ArrayList<Integer> simulationParameters) {
...
addFoodToCell(row, column, startingFoodInNest);
...
After a set of simulation parameters has been selected, display the simulation values
JAVA
king Olie of HaringtonString output;
output = "startingNumberOfNests is " + simulationParameters.get(0) +"\n";
output += "numberOfRows is " + simulationParameters.get(1) +"\n";
output += "numberOfColumns is " + simulationParameters.get(2) +"\n";
output += "startingFoodInNest is " + simulationParameters.get(3) +"\n";
output += "startingNumberOfFoodCells is " + simulationParameters.get(4) +"\n";
output += "startingAntsInNest is " + simulationParameters.get(5) +"\n";
output += "newPheromoneStrength is " + simulationParameters.get(6) +"\n";
output += "pheromoneDeca is " + simulationParameters.get(7);
System.out.println(output);
Prevent food from spawning within one cell of a nest
JAVA
king Olie of Haringtonfor (Nest n : nests) {
int x = n.getRow();
int y = n.getColumn();
int xdiff = Math.abs(x) - Math.abs(row);
int ydiff = Math.abs(x) - Math.abs(row);
xdiff = Math.abs(xdiff);
ydiff = Math.abs(ydiff);
if(xdiff == 1 || ydiff == 1 || (n.getRow() == row && n.getColumn() == column)) {
allowed = false;
}
}
Python
Bill Robinson# At the end of Simulation.__init__()
for N in self._Nests:
if abs(N.GetRow() - Row) < 2 and abs(N.GetColumn() - Column) < 2:
Allowed = False
self.AddFoodToCell(Row, Column, 500)
Swaps values in "Display area details" when the first cell entered is larger than the second one. [13]
JAVA
Charlotte of Harington In the "getAreaDetails()" method:
if(startRow>endRow) {
int temp = startRow;
startRow = endRow;
endRow = temp;
temp= startColumn;
startColumn = endColumn;
endColumn = temp;
}
if(startRow == endRow) {
if(startColumn>endColumn) {
int temp = startColumn;
startColumn = endColumn;
endColumn = temp;
}
}
JAVA
King Olie of Harington //This is a better presented and commented version of the code above from charlotte i did work on this myself but realsied their method was better so i used hers and added comments. While calling me a idiot.
if(startRow > endRow) {
int temp = startRow; //flip it so the start row is smaller
startRow = endRow;
endRow = temp;
temp = startColumn; // fliping collum so the area slected is the same
startColumn = endColumn;
endColumn = temp;
}
if(startRow == endRow) {
// if the rows equal and start colum is bigger then end coloum
// then you must flip the coloums to get the right area selected
if(startColumn > endColumn) {
int temp = startColumn;
startColumn = endColumn;
endColumn = temp;
}
}
Python
Bill Robinson # addition of first 4 lines below to choice 2 in Main():
if StartRow > EndRow:
StartRow, EndRow = EndRow, StartRow
if StartColumn > EndColumn:
StartColumn, EndColumn = EndColumn, StartColumn
print(ThisSimulation.GetAreaDetails(StartRow, StartColumn, EndRow, EndColumn))