跳转到内容

A-level 计算机/AQA/试卷 1/框架程序/2017

来自 Wikibooks,开放世界中的开放书籍

这是针对新的计算机科学规范。请记住,还有一个针对计算的 Comp1 考试(用于重考?),尽管这个特定页面是针对新课程的。

在这里可以提出关于一些问题的建议以及如何解决它们。

请保持尊重,不要破坏或篡改页面,因为这会影响学生备考!

添加一种方式让疾病杀死兔窝里的兔子

[编辑 | 编辑源代码]

C# 解决方案

不是答案 

答案

// Kieran South

// Animal class
protected double NaturalLifespan;
protected int ID;
protected static int NextID = 1;
protected int Age = 0;
protected double ProbabilityOfDeathOtherCauses;
protected double ProbabilityOfDeathDisease;
protected bool IsAlive;
protected static Random Rnd = new Random();

public Animal(int AvgLifespan, double AvgProbabilityOfDeathOtherCauses, int Variability)
{
  NaturalLifespan = AvgLifespan * CalculateRandomValue(100, Variability) / 100;
  ProbabilityOfDeathOtherCauses = AvgProbabilityOfDeathOtherCauses * CalculateRandomValue(100, Variability) / 100;
  ProbabilityOfDeathDisease = 0.1 * CalculateRandomValue(100, Variability) / 100;
  IsAlive = true;
  ID = NextID;
  NextID++;
}

// CheckIfKilledByOtherFactors method in Animal class

public virtual bool CheckIfKilledByOtherFactor()
{
  if (Rnd.Next(0, 100) < ProbabilityOfDeathOtherCauses * 100) // Kill by other factors
  {
    IsAlive = false;
    return true;
  }
      
  if (Rnd.Next(0, 100) < ProbabilityOfDeathDisease * 100 && this is Rabbit) // Kill rabbits by disease, not foxes
  {
   IsAlive = false;
   return true;
  }
  return false;
}


Delphi/Pascal 解决方案

答案 

答案

function Animal.CheckIfKilledByOtherFactor() : boolean;
  begin
    if random(100) < ProbabilityOfDeathOtherCauses * 100 then    
      begin
        IsAlive := False;
        CheckIfKilledByOtherFactor := True;     
      end;

    if self is Rabbit then //Checks for Rabbits only
      begin
      if random(100) < ProbabilityOfDeathOtherCauses * 100 then
        begin
          IsAlive := False;  //kill Rabbits with disease
          CheckIfKilledByOtherFactor := True;
        end;  
      end

    else
      CheckIfKilledByOtherFactor := False;   
  end;

//Harry Barron, Faringdon Community College


Java 解决方案

答案 

答案

//I spiced this up - any rabbit has a 1% chance of contracting disease at any simulation.
//If the rabbit Above/Below it in the Rabbits Array is infected then it has a 25% chance and if both do it's a 50% chance.
//If a rabbit is infeced it has a 10% chance to die, no matter how it was infected.
//Almost certainly won't come up in the exam, but good practice.

   public void infectedByDisease() {
        for (int i = 0; i < RabbitCount; i++) {
            int infectedProb = 0;
            if (Rabbits[i - 1].infected || Rabbits[i + 1].infected)
                if (Rabbits[i - 1].infected && Rabbits[i + 1].infected)
                    infectedProb = 50;
                else
                    infectedProb = 25;
            else
                infectedProb = 1;
            Random r = new Random();
            r.nextInt(100) + 1 <= infectedProb
            Rabbits[i].infected = true;
        }
    }

    public int killedbyDisease(boolean ShowDetail) {
        int DeathCount = 0;
        Random r = new Random();
        for (int i = 0; i < RabbitCount; i++) {
            if (Rabbits[i].infected && r.nextInt(10) == 0) {
                Rabbits[i] = null;
                DeathCount += 1;
            }
        }
        CompressRabbitList(DeathCount);
        if (ShowDetail) {
            Console.println("  " + DeathCount + " rabbits die of disease.");
        }

    }


Python 解决方案

答案 

答案

## Adapted Kill by other factors

  def __KillByOtherFactors(self, ShowDetail):
    DeathCount = 0
    DeathCountOF = 0
    DeathCountD = 0
    for r in range (0, self.__RabbitCount):
      if self.__Rabbits[r].CheckIfKilledByOtherFactor():
        self.__Rabbits[r] = None
        DeathCount += 1
        DeathCountOF += 1
      elif self.__Rabbits[r].CheckIfKilledByDisease():
        self.__Rabbits[r] = None
        DeathCount += 1
        DeathCountD += 1

    if ShowDetail:
        print(" ", DeathCountOF, "rabbits killed by other factors.")
        print(" ", DeathCountD, "rabbits killed by Disease.")
        
    self.__CompressRabbitList(DeathCount)

#########################################

## New function in the class, Animal.

  def CheckIfKilledByDisease(self):
    if random.randint(0, 100) < 25:
      self._IsAlive = False
      return True
    else:
      return False

## Ben (BigDaddy) Budmouth College
##          ^
## not as impressive as you'd like to think
##^^^^^


VB.NET 解决方案

答案 

答案

Private Sub disease(ByVal ShowDetail As Boolean, ByVal diseasekilled As Boolean, ByVal ProbabilityOfdisease As Double)

            If getdiseasekilled() Then

                ProbabilityOfDeathdisease = ProbabilityOfDeathdisease * 1.1
            Else
                ProbabilityOfDeathdisease = ProbabilityOfdisease * CalculateRandomValue(100, Variability) / 100
            End If

            Dim deathCount As Integer = 0
            For r = 0 To RabbitCount - 1
                If Rabbits(r).CheckIfKilledDisease(ProbabilityOfDeathdisease) Then
                    Rabbits(r) = Nothing
                    deathCount += 1

                End If
            Next

            setdiseasekilled(deathCount)

            CompressRabbitList(deathCount)
            If ShowDetail Then
                Console.WriteLine("  " & deathCount & " rabbits killed by disease.")
            End If

        End Sub

------------------------------------------------

Public Overridable Function CheckIfKilledDisease(ByVal ProbabilityOfDeathdisease As Double)

            If Rnd.Next(0, 100) < ProbabilityOfDeathdisease * 100 Then
                IsAlive = False
                Return True
            Else

                Return False
            End If

        End Function

--------------------------------------------

Public Function setdiseasekilled(ByVal deathcount As Integer)
        If deathcount > 0 Then
            diseaseKilled = True
        Else
            diseaseKilled = False

        End If
        Return diseaseKilled

    End Function

---------------------------------

    Public Function getdiseasekilled()
      
        Return diseaseKilled

    End Function

---------------------------------------------------------

//Call the following in the 'Advance Generation' Sub and declare the variables:

If RabbitCount > 0 Then
                disease(ShowDetail, diseasekilled, probabilityofdisease)
            End If

此代码还允许疾病传播,并且每轮疾病都会传播,兔子死亡的几率会更高。


VB.NET 解决方案(使用面向对象编程)

答案 

答案

Animal class:
Private diseased As Boolean

Public Overridable Sub Inspect()
        Console.Write("  ID " & ID & " ")
       Console.Write("Age " & Age & " ")
       Console.Write("LS " & NaturalLifespan & " ")
       If diseased = True Then
           Console.Write(" Diseased ")
       Else Console.Write(" Not diseased ")
       End If
       Console.Write("Pr dth " & Math.Round(ProbabilityOfDeathOtherCauses, 2) & " ")
   End Sub
 
Public Function Checkifinfected()
        Return diseased
    End Function
  
  Public Sub Becomeinfected() '(validation also added to prevent multiplier from being re-used)
        If diseased = False Then
            diseased = True
            ProbabilityOfDeathOtherCauses *= 1.1  ' increasing the value by 10%
        End If
    End Sub
Warren Class:
Private diseased As Boolean = False

Public Sub Inspect()
      Console.WriteLine("Periods Run " & PeriodsRun & " Size " & RabbitCount)
      If diseased = True Then
          Console.Write(" Diseased ")
      Else Console.Write(" Not diseased ")
 End if
  End Sub
Public Function Checkifinfected()
       Return diseased
   End Function
Public Sub Becomeinfected() '(validation also added to prevent multiplier from being re-used)
      If diseased = False Then
          diseased = True
          For looper = 0 To Rabbits.Length - 1
              If Not Rabbits(looper) Is Nothing Then
                  Rabbits(looper).Becomeinfected()
              End If
          Next
      End If
  End Sub

Simulation Class:

Private Sub AdvanceTimePeriod()
      Dim NewFoxCount As Integer = 0
 
      Private Sub AdvanceTimePeriod()
//-Lots of code that doesnt need to be shown-
      If ShowDetail Then
          Console.ReadKey()
      End If
      '''propagate()'''
      DrawLandscape()
 
      ' draw the updated version of the landscape
      Console.WriteLine()
  End Sub
Private Sub CreateLandscapeAndAnimals(ByVal InitialWarrenCount As Integer, ByVal InitialFoxCount As Integer, ByVal FixedInitialLocations As Boolean)
       ' build a set of grid locations with no contents yet
       For x = 0 To LandscapeSize - 1 ' visit all x references
           For y = 0 To LandscapeSize - 1 ' visit all y references
               Landscape(x, y) = New Location() ' make new location for x,y
           Next
       Next
 
       If FixedInitialLocations Then
           ' if user picked option 1 from first menu .....
           ' then create 5 warrens of different size 
           ' with 0 as the variability
           Landscape(1, 1).Warren = New Warren(Variability, 38)
           Landscape(2, 8).Warren = New Warren(Variability, 80)
           Landscape(9, 7).Warren = New Warren(Variability, 20)
           Landscape(10, 3).Warren = New Warren(Variability, 52)
           Landscape(13, 4).Warren = New Warren(Variability, 67)
           initialinfection(Landscape(1, 1).Warren)
           initialinfection(Landscape(10, 3).Warren)
           initialinfection(Landscape(13, 4).Warren)
           WarrenCount = 5  ' set count of warrens to number created above
 
 
           ' create 5 foxes at fixed locations use 0 as the variability
           Landscape(2, 10).Fox = New Fox(Variability)
           Landscape(6, 1).Fox = New Fox(Variability)
           Landscape(8, 6).Fox = New Fox(Variability)
           Landscape(11, 13).Fox = New Fox(Variability)
           Landscape(12, 4).Fox = New Fox(Variability)
           FoxCount = 5
           initialinfection(Landscape(12, 4).Fox)
       Else
           ' must have chosen option 2 from first menu
           For w = 0 To InitialWarrenCount - 1 ' loop to user choice
               CreateNewWarren() ' make warren with custom settings
           Next
           For f = 0 To InitialFoxCount - 1 ' loop to user choice
               CreateNewFox() ' make fox with custom settings
           Next
       End If
   End Sub
    Public Overloads Sub initialinfection(ByRef patientZero As Warren)
        patientZero.Becomeinfected()
    End Sub
    Public Overloads Sub initialinfection(ByRef patientZero As Animal)
        patientZero.Becomeinfected()
    End Sub
    Public Sub propagate()
        For x = 0 To LandscapeSize - 1
            For y = 0 To LandscapeSize - 1
                If Not Landscape(x, y).Fox Is Nothing Then
                    If Landscape(x, y).Fox.Checkifinfected = True Then spreaddisease(x, y)
                End If
                If Not Landscape(x, y).Warren Is Nothing Then
                    If Landscape(x, y).Warren.Checkifinfected = True Then spreaddisease(x, y)
                End If
            Next
        Next
    End Sub
    Private Sub spreaddisease(ByVal infectedx As Integer, ByVal infectedy As Integer)
        ' this sub looks for 
        For x = infectedx - 1 To infectedx + 1
            For y = infectedy - 1 To infectedy + 1
                If x < LandscapeSize And x > -1 Then
                    If y < LandscapeSize And y > -1 Then
                        If Not Landscape(x, y).Fox Is Nothing Then
                            Landscape(x, y).Fox.Becomeinfected()
                        End If
                        If Not Landscape(x, y).Warren Is Nothing Then
                            Landscape(x, y).Warren.Becomeinfected()
                        End If
                    End If
                End If
            Next
        Next
    End Sub

此代码允许疾病在兔窝和动物之间传播。它没有症状,但会将 ProbabilityOfDeathOtherCauses 变量增加 10%。此代码是由 Shaun Aziz 非常快速地制作的,几乎肯定包含很多错误。请随时修复它们并在下面添加您的姓名(最好连同您修复的内容一起添加):目前还没有人修复任何东西。 :(


自然灾害(例如风暴或火灾)影响给定半径内的动物数量

[编辑 | 编辑源代码]

C# 解决方案

答案 

答案

        private void AdvanceTimePeriod()
        {
            int NewFoxCount = 0;
            if (ShowDetail)
            {
                Console.WriteLine();
            }
            //Start of Fire//
            if (Rnd.Next(1, 5) <= 2)
            {
                int x, y, z;
                int PercentageToKill = 33;
                int radius = 2;
                x = Rnd.Next(0, LandscapeSize);
                y = Rnd.Next(0, LandscapeSize);
                Console.WriteLine("Fire at (" + x + "," + y + ")");
                for (int Xco = x - radius; Xco <= x + radius; Xco++)
                {
                    for (int Yco = y - radius; Yco <= y + radius; Yco++)
                    {
                        try {
                            if (Landscape[Xco, Yco].Warren != null)
                            {
                                int RabbitsToKill = Landscape[Xco, Yco].Warren.GetRabbitCount() * PercentageToKill / 100;
                                Landscape[Xco, Yco].Warren.EatRabbits(RabbitsToKill);
                                if (ShowDetail)
                                {
                                    Console.WriteLine(PercentageToKill + "% rabbits killed in Warren at (" + Xco + "," + Yco + ")");
                                }
                            }
                        }
                        catch { }
                    }
                }
            }
            //End of Fire//


Delphi/Pascal 解决方案

答案 

答案

//Start of Fire
    if (Random(20) <= 2) then
    begin
      FRadius := Random(5);
      PercentToKill := Random(100);
      xFire := Random(LandscapeSize);
      yFire := Random(LandscapeSize);

      Writeln('A fire has occured at (', XFire,',', YFire,')');

      for Xco := (xFire - FRadius) to (xFire + FRadius) do
        Begin
          for Yco := (yFire - FRadius) to (yFire + FRadius) do
            begin
            try
              begin
                if not(Landscape[Xco][Yco].Warren = nil) then
                  begin
                    RabbitsToKill := Round(Landscape[Xco][Yco].Warren.GetRabbitCount() * PercentToKill / 100);
                    Landscape[Xco][Yco].Warren.EatRabbits(RabbitsToKill);
                    
                    if (ShowDetail) then
                      Writeln(RabbitsToKill, ' have died in the fire at (', Xco, ',', Yco, ')');
                  end;
              end;
            except
            end;
          end;
        end;
      end;
//End of Fire

//Harry Barron, Faringdon Community College


Java 解决方案

答案 

答案

此方法需要从某个地方调用。我在模拟菜单中添加了一个选项来执行风暴代码。如果您像我一样通过菜单调用风暴,那么其他因素(例如兔子因自然原因死亡和被吃掉)仍然会对受影响的兔窝发生。

    private void StormLocation(){
        int locationX = Rnd.nextInt(LandscapeSize);
        int locationY = Rnd.nextInt(LandscapeSize);
        int radius = 5;
        System.out.println("Storm At: "+locationX+","+locationY + ", Radius:" + radius);
        for(int LocCentreY = locationY-(int) Math.floor(radius/2), endpoint = locationY+(int) Math.floor(radius/2); LocCentreY < endpoint+1; LocCentreY++){
            if(LocCentreY > 0 && LocCentreY < LandscapeSize){
                for(int LocCentreX = locationX-(int) Math.floor(radius/2), endpointX = locationX+(int) Math.floor(radius/2); LocCentreX < endpointX+1; LocCentreX++){
                    if(LocCentreX > 0 && LocCentreX < LandscapeSize){

                        if(Landscape[LocCentreX][LocCentreY].Warren != null){
                            int percentage = Rnd.nextInt(100);
                            int rabbitCount = Landscape[LocCentreX][LocCentreY].Warren.GetRabbitCount();
                            int rabbitcountnew = rabbitCount * percentage/100;
                            Landscape[LocCentreX][LocCentreY].Warren.EatRabbits(rabbitCount-rabbitcountnew);
                            System.out.println("Warren At "+LocCentreX+","+LocCentreY+" Was hit by the storm, lowering the rabbit count from "+rabbitCount+" to "+ rabbitcountnew);

                        }
                    }
                }
            }
        }
    }
// Joel LB, Twyford Sixth Form


Python 解决方案

答案 

答案

"""FIRE TRIGGER BASED ON RANDOM CHANCE
          INSERT AT START of AdvanceTimePeriod"""
    if random.randint(1,5) <= 2:
      self.fire(self.__LandscapeSize)

"""FIRE SUBROUTINE"""
  def fire(self, LandscapeSize):
    x = 9#random.randint(0,LandscapeSize)
    y = 5#random.randint(0, LandscapeSize)
    radius = random.randint(1,3)
    PercentageKill = 40
    print(radius, "Fire starts at (" + str(x) + "," + str(y) + ")")

    for xAxis in range(x - radius, x + radius+1):
      for yAxis in range(y - radius, y + radius+1):
        if 0 < xAxis < LandscapeSize and 0 < yAxis < LandscapeSize:
          if self.__Landscape[xAxis][yAxis].Warren is not None:
            rabbitDeaths = self.__Landscape[xAxis][yAxis].Warren.GetRabbitCount() * PercentageKill // 100
            self.__Landscape[xAxis][yAxis].Warren.EatRabbits(rabbitDeaths)

            if self.__ShowDetail:
              print(rabbitDeaths, "rabbits have met a grizzly end at (" + str(xAxis) + "," + str(yAxis) + ")")

##Alvise and Matt, Budmouth College


VB.NET 解决方案

答案 

答案

  Private Sub naturalDisaster()
            Dim x As Integer = Rnd.Next(0, LandscapeSize - 1)
            Dim y As Integer = Rnd.Next(0, LandscapeSize - 1)
            If Rnd.Next(0, 100) < 5 Then
                Console.WriteLine("A natural disaster has struck at " & x & "," & y & "!")
                For i As Integer = 0 To LandscapeSize - 1
                    For j As Integer = 0 To LandscapeSize - 1
                        If DistanceBetween(i, j, x, y) < 5 Then
                            If Not IsNothing(Landscape(i, j).Fox) Then
                                Landscape(i, j).Fox = Nothing
                                FoxCount -= 1
                                If ShowDetail Then
                                    Console.WriteLine("Fox at " & i & "," & j & " has been killed.")
                                End If
                            End If
                            If Not IsNothing(Landscape(i, j).Warren) Then
                                If Landscape(i, j).Warren.GetRabbitCount < 15 Then
                                    Landscape(i, j).Warren = Nothing
                                    WarrenCount -= 1
                                    If ShowDetail Then
                                        Console.WriteLine("Warren at " & i & "," & j & " has been destroyed.")
                                    End If
                                Else
                                    Dim rabbitsKilled As Integer = Rnd.Next(10, 15)
                                    Landscape(i, j).Warren.EatRabbits(rabbitsKilled)
                                    If ShowDetail Then
                                        Console.WriteLine(rabbitsKilled & " rabbits killed in warren at " & i & "," & j & ".")
                                    End If
                                End If
                            End If
                        End If
                    Next
                Next
            End If
        End Sub


检查输入坐标是否有效

[编辑 | 编辑源代码]

C# 解决方案

答案 

答案

//Charles' Linq solution is slow, since it iterates through the entire range and checks for equality.
//Other solutions use a try-catch block, which is bad practice, since exception throwing should be avoided
//unless a genuinely unforeseeable problem has occurred.
//My Solution: by (((Samuel Collins))):
private int InputCoordinate(char Coordinatename)
{
    int (((Coordinate)));
    Console.Write("  Input " + Coordinatename + " coordinate: ");
    while (!int.TryParse(Console.ReadLine(), out Coordinate) || Coordinate >= LandscapeSize || Coordinate < 0)
        Console.Write($"Invalid Input. Enter an integer from 0 to {LandscapeSize - 1}: ");
    return Coordinate;
}
//Note: string interpolation requires C# 6/7. The same behaviour can be achieved using + symbols in earlier versions.

//Written by Charles Batten using Linq for coordinate range checking
using System.Linq;
private int InputCoordinate(char Coordinatename)
{
   while (true)
   {
      Console.WriteLine("Enter the {0} coordinate:", Coordinatename);
      bool succeeded = Int32.TryParse(Console.ReadLine(), out int coordinate);

      if(succeeded && Enumerable.Range(0, LandscapeSize).Contains(coordinate))
      {
         return coordinate;
      }
      else
      {
         Console.WriteLine("The coordinate you entered was invalid.");
         Console.WriteLine("Please enter an integer between 0 and {0}", (LandscapeSize - 1));
      }
   }
}

//In Response To Luke's Attempt, I attempted to solve the problem and developed the following solution.
        private int InputCoordinate(char Coordinatename)
        {
            bool invalidInput = true;
            int Coordinate = 0;
            Console.Write("  Input " + Coordinatename + " coordinate: ");
            try
            {
                Coordinate = Convert.ToInt32(Console.ReadLine());
                do
                {
                    if (Coordinate > LandscapeSize)
                    {
                        Console.Write("Invalid Input Please Input A Value smaller than " + LandscapeSize + ": ");
                        Coordinate = Convert.ToInt32(Console.ReadLine());
                    }
                }
                while (Coordinate > LandscapeSize);
            }
            catch
            {
                Console.Write("Invalid Input: ");
                while(invalidInput == true)
                {
                    try
                    {
                        Coordinate = Convert.ToInt32(Console.ReadLine());
                        invalidInput = false;
                    }
                    catch
                    {
                     //Continues Loop If Invalid Input
                     invalidInput = true;
                    }
                }
            }
            return Coordinate;
        }
//Declyn Sealey, St Mary's College

//For a better solution:
        private int InputCoordinate(char Coordinatename)
        {
            int Coordinate = 0;
            while (true)
            {
                Console.Write("  Input " + Coordinatename + " coordinate: ");
                try
                {
                    Coordinate = Convert.ToInt32(Console.ReadLine());
                    if (0 <= Coordinate && Coordinate < LandscapeSize)
                    {
                        break;
                    }
                    else
                    {
                        Console.Write("Invalid Input. Try again");
                    }
                }
                catch
                {
                    Console.Write("Invalid Input. Try again");
                }
            }
            return Coordinate;
        }

//for a non monkeyed together solution that doesn't use unnecessary breaks
        private int InputCoordinate(char Coordinatename)
        {
            int Coordinate = 0;
            bool valid = true;
            while (valid)
            {
                Console.Write("  Input " + Coordinatename + " coordinate: ");
                try
                {
                    Coordinate = Convert.ToInt32(Console.ReadLine());
                    if (0 <= Coordinate && Coordinate < LandscapeSize)
                    {
                        valid = false;
                    }
                    else
                    {
                        Console.Write("Invalid Input. Try again");
                    }
                }
                catch
                {
                    Console.Write("Invalid Input. Try again");
                }
            }
            return Coordinate;
        }


Delphi/Pascal 解决方案

答案 

答案

// Add SysUtils to uses
function Simulation.InputCoordinate(CoordinateName : Char): integer;
  var
    Coordinate : integer;
    isInt : Boolean;
  begin
    isInt := False;
    while isInt = False do
    Begin
    write('  Input ' , CoordinateName, ' coordinate: ');
    try
    readln(Coordinate);
    isInt := True;
    except
    on E: EInOutError do
      Writeln('Please enter valid coordiantes');
    end;
    if Coordinate > LandscapeSize - 1 then
    repeat
    write('  Input ' , CoordinateName, ' coordinate: ');
    readln(Coordinate);
    until (Coordinate <= LandscapeSize - 1);
    End;
    InputCoordinate := Coordinate;
    end;

//Graveney School MVP's


Java 解决方案

答案 

答案

 private int InputCoordinate(char CoordinateName)
    {
        int Coordinate;
        Coordinate = Console.readInteger("  Input " + CoordinateName + " coordinate: ");
        while ( Coordinate < 0 || Coordinate > LandscapeSize ){
        	Console.println("This coordinate is not on the board, enter again.");
        	Coordinate = Console.readInteger("  Input " + CoordinateName + " coordinate: ");
        }
        return Coordinate;
    }

//This is the alternative solution and works by checking the coordinates for menu options 3 and 4, this is worse but still works:
            if (MenuOption == 3)
            {
                x = InputCoordinate('x');
                y = InputCoordinate('y');
               while ( x > LandscapeSize || x < 0 || y > LandscapeSize || y < 0){// validation
            	   Console.println("Sorry these coordinates are invalid, enter again");
            	   x = InputCoordinate('x');
                   y = InputCoordinate('y');
               }
                if (Landscape[x][y].Fox != null)
                {
                    Landscape[x][y].Fox.Inspect();
                }
               
             	   
            }
            if (MenuOption == 4)
            {
                x = InputCoordinate('x');
                y = InputCoordinate('y');
                while ( x > LandscapeSize || x < 0 || y > LandscapeSize || y < 0){// validation
             	   Console.println("Sorry these coordinates are invalid, enter again");
             	   x = InputCoordinate('x');
                    y = InputCoordinate('y');
                }
                if (Landscape[x][y].Warren != null )
                {
                    Landscape[x][y].Warren.Inspect();
                    ViewRabbits = Console.readLine("View individual rabbits (y/n)?");
                    if ( ViewRabbits.equals("y") )
                    {
                        Landscape[x][y].Warren.ListRabbits();
                    }
                }
            }


Python 解决方案

答案 

答案

  def __InputCoordinate(self, CoordinateName):
    while True:
      try:
        #&nbsp;Attempt to parse the input string as an integer
        Coordinate = int(input("  Input " + CoordinateName + " coordinate:"))
      except:
        #&nbsp;If parsing failed print the line and start the next iteration of the loop
        print("Input co-ordinate not an integer")
        continue
      #&nbsp;Once parsing was successful, check the integer is between 0 and the LandscapeSize
      if Coordinate in range(self.__LandscapeSize):
        #&nbsp;Break from the loop on success
        break
      else:
        #&nbsp;If the integer is not within the valid limits, print an error and go to the next loop iteration
        print("Co-ordinate must be between 0 and {0} inclusive".format(self.__LandscapeSize - 1))
    return Coordinate


VB.NET 解决方案

答案 

答案

    Private Function InputCoordinate(ByVal CoordinateName As Char) As Integer
            Dim inputtedCoordinate As String
            Dim Coordinate As Integer
            Dim Validity As Boolean = False
            Do Until Validity = True
                Console.Write("Enter " & CoordinateName & " co-ordinate: ")
                inputtedCoordinate = Console.ReadLine
                If Integer.TryParse(inputtedCoordinate, Coordinate) = True Then Validity = True
                'type check
                If Coordinate < 0 Or Coordinate > LandscapeSize - 1 Then Validity = False
                'range check
            Loop
            Return Coordinate
        End Function

        'by Brandon


显示该时期出生的兔子数量(这个问题不太可能,因为它已经在 Visual Basic 和 Java 中编码)

[编辑 | 编辑源代码]

(如果在推进时期时选择选项 1,可以做到)

C# 解决方案

答案 

答案

    private void AdvanceTimePeriod()
    {
			int newRabbitsBorn = 0;
      int NewFoxCount = 0; //Stores the number of new rabbits in a period
      if (ShowDetail)
      {
        Console.WriteLine();
      }
      for (int x = 0; x < LandscapeSize; x++)
      {
        for (int y = 0; y < LandscapeSize; y++)
        {
          if (Landscape[x, y].Warren != null)
          {
            if (ShowDetail)
            {
              Console.WriteLine("Warren at (" + x + "," + y + "):");
              Console.Write("  Period Start: ");
              Landscape[x, y].Warren.Inspect();
            }
            if (FoxCount > 0)
            {
              FoxesEatRabbitsInWarren(x, y);
            }
            if (Landscape[x, y].Warren.NeedToCreateNewWarren())
            {
              CreateNewWarren();
            }
            Landscape[x, y].Warren.AdvanceGeneration(ShowDetail);
            if (ShowDetail)
            {
              Console.Write("  Period End: ");
              Landscape[x, y].Warren.Inspect();
              Console.ReadKey();
            }
            if (Landscape[x, y].Warren.WarrenHasDiedOut())
            {
              Landscape[x, y].Warren = null;
              WarrenCount--;
            }

						newRabbitsBorn = newRabbitsBorn + Landscape[x, y].Warren.getNewRabbitsBorn(); //Adds up new rabbits born from each warren
						Landscape[x, y].Warren.resetNewRabbitsBorn(); //set back to 0

          }
        }
      }
			Console.WriteLine("Total number of rabbits born this period: " + newRabbitsBorn);
			newRabbitsBorn = 0;
//Rest of AdvanceTimePeriod() for Foxes

class Warren
  {
		public int totalRabbitsBorn = 0;
//Other Variables
private void MateRabbits(bool ShowDetail)
    {
      int Mate = 0;
      int Babies = 0;
      double CombinedReproductionRate;
      for (int r = 0; r < RabbitCount; r++)
      {
        if ((Rabbits[r].IsFemale()) && (RabbitCount + Babies < MaxRabbitsInWarren))
        {
          do
          {
            Mate = Rnd.Next(0, RabbitCount);
          } while ((Mate == r) || (Rabbits[Mate].IsFemale()));
          CombinedReproductionRate = (Rabbits[r].GetReproductionRate() + Rabbits[Mate].GetReproductionRate()) / 2;
          if (CombinedReproductionRate >= 1)
          {
            Rabbits[RabbitCount + Babies] = new Rabbit(Variability, CombinedReproductionRate);
						Babies++;
						totalRabbitsBorn++;
          }
        }
      }
      RabbitCount = RabbitCount + Babies;
      if (ShowDetail)
      {
        Console.WriteLine("  " + Babies + " baby rabbits born.");
      }
    }
		public int getNewRabbitsBorn()
		{
			return totalRabbitsBorn;
		}
		public void resetNewRabbitsBorn()
		{
			totalRabbitsBorn = 0;
		}

//Alex Marchant, UTC Reading


Delphi/Pascal 解决方案

答案 

答案

//Global Variable

  var
  NextID : integer = 1;
  NoOfRabbitsBorn: integer; //Added

//Within Warren.MateRabbits

    NoOfRabbitsBorn := NoOfRabbitsBorn + Babies; //Added
    RabbitCount := RabbitCount + Babies;
    if ShowDetail then
      writeln('  ', Babies, ' baby rabbits born.');

//Within Simulation.New

      writeln;
      writeln('The number of rabbits born in the last period: ', NoOfRabbitsBorn); //Added
      writeln;
      NoOfRabbitsBorn := 0; //Added
      writeln('1. Advance to next time period showing detail');
      writeln('2. Advance to next time period hiding detail');
      writeln('3. Inspect fox');
      writeln('4. Inspect warren');
      writeln('5. Exit');

//Callum, Exeter College


Java 解决方案

答案 

答案


Python 解决方案

答案 

答案

  """Add NewRabbitsThisPeriod to the start of AdvanceTimePeriod,
  it will reset every time period"""
  NewRabbitsThisPeriod = 0

  """Add Return Babies to the end of MateRabbits"""
  return Babies

  """In AdvanceGeneration Set NewRabbits equal to MateRabbits on the line MateRabbits is currently on. Return NewRabbits at the end of the line"""
  NewRabbits = self.__MateRabbits(ShowDetail)
  Return NewRabbits

  """in AdvanceTimePeriod Add the return Value of AdvanceGeneraton to NewRabbitsThisPeriod. Print if show detail after the first double for Loop"""
  NewRabbitsThisPeriod += self.__Landscape[x][y].Warren.AdvanceGeneration(self.__ShowDetail)
  if self.__ShowDetail:
  print("New Rabbits Born: " + str(NewRabbitsThisPeriod))
#Jordan, Budmouth College


VB.NET 解决方案

答案 

答案


放置动物数量的限制

[编辑 | 编辑源代码]

(如果选择选项 2,可以做到)

C# 解决方案

答案 

答案

                   class Program
    {
        static void Main(string[] args)
        {
            Simulation Sim;
            int MenuOption = 0;
            int LandscapeSize;
            int InitialWarrenCount;
            int InitialFoxCount;
            int Variability;
            bool FixedInitialLocations;

            do
            {
                Console.WriteLine("Predator Prey Simulation Main Menu");
                Console.WriteLine();
                Console.WriteLine("1. Run simulation with default settings");
                Console.WriteLine("2. Run simulation with custom settings");
                Console.WriteLine("3. Exit");
                Console.WriteLine();
                Console.Write("Select option: ");
                try
                {
                    MenuOption = Convert.ToInt32(Console.ReadLine());
                }
                catch
                {   bool validInput = false;
                    while(validInput == false)
                    {
                        Console.WriteLine("Invalid Input Please Try Again: ");
                        try
                        {
                            MenuOption = Convert.ToInt32(Console.ReadLine());
                            validInput = true;
                        }
                        catch
                        {
                        }
                    }
                }
                if ((MenuOption == 1) || (MenuOption == 2))
                {
                    if (MenuOption == 1)
                    {
                        LandscapeSize = 15;
                        InitialWarrenCount = 5;
                        InitialFoxCount = 5;
                        Variability = 0;
                        FixedInitialLocations = true;
                    }
                    else
                    {
                        Console.Write("Landscape Size: ");
                        LandscapeSize = Convert.ToInt32(Console.ReadLine());
                        Console.Write("Initial number of warrens: ");
                        InitialWarrenCount = Convert.ToInt32(Console.ReadLine());
                        while (InitialWarrenCount > 10) //Set The Limit as 10 for the InitialWarrenCount however this can be changed.
                        {
                            Console.Write("Too Many Warrens Please Input A Value Less Than 10: ");
                            InitialWarrenCount = Convert.ToInt32(Console.ReadLine());
                        }
                        Console.Write("Initial number of foxes: ");
                        InitialFoxCount = Convert.ToInt32(Console.ReadLine());
                        while(InitialFoxCount > 5) //Set The Limit as 5 for the InitialFoxCount however this can be changed.
                        {
                            Console.Write("Too Many Foxes Please Input A Value Less Than 5: ");
                            InitialFoxCount = Convert.ToInt32(Console.ReadLine());
                        }
                        Console.Write("Randomness variability (percent): ");
                        Variability = Convert.ToInt32(Console.ReadLine());
                        FixedInitialLocations = false;
                    }
                    Sim = new Simulation(LandscapeSize, InitialWarrenCount, InitialFoxCount, Variability, FixedInitialLocations);
                }
            } while (MenuOption != 3);
            Console.ReadKey();
        }
    }//Declyn Sealey, St Marys College

 static void Main(string[] args) //Allows user to input any number of warrens and foxes as long as the total 
                                 //does not exceed the total area
        {
            Simulation Sim;
            int MenuOption;
            int LandscapeSize;
            int InitialWarrenCount;
            int InitialFoxCount;
            int Variability;
            bool FixedInitialLocations;
            do
            {
                Console.WriteLine("Predator Prey Simulation Main Menu");
                Console.WriteLine();
                Console.WriteLine("1. Run simulation with default settings");
                Console.WriteLine("2. Run simulation with custom settings");
                Console.WriteLine("3. Exit");
                Console.WriteLine();
                Console.Write("Select option: ");
                MenuOption = Convert.ToInt32(Console.ReadLine());
                if ((MenuOption == 1) || (MenuOption == 2))
                {
                    if (MenuOption == 1)
                    {
                        LandscapeSize = 15;
                        InitialWarrenCount = 5;
                        InitialFoxCount = 5;
                        Variability = 0;
                        FixedInitialLocations = true;
                    }
                    else
                    {
                        Console.Write("Landscape Size: ");
                        LandscapeSize = Convert.ToInt32(Console.ReadLine());
                        int MaxWarren = LandscapeSize * LandscapeSize; //The max amount of warrens is one warren per square
                        Console.Write("Initial number of warrens: ");
                        InitialWarrenCount = Convert.ToInt32(Console.ReadLine());
                        if (InitialWarrenCount > MaxWarren) //If number is bigger than MaxWarren then user must input a smaller number 
                        {
                            Console.WriteLine("Invalid input, please enter a number less than " + MaxWarren);
                            Console.Write("Initial number of warrens: ");
                            InitialWarrenCount = Convert.ToInt32(Console.ReadLine());
                        }
                        int MaxFox = (LandscapeSize * LandscapeSize) - InitialWarrenCount + 1;  //The max amount of foxes is one fox  
                                                                                                //per left over squares
                        Console.Write("Initial number of foxes: ");                             //MaxFoxes and MaxWarrens always adds up                                                                                               
                        InitialFoxCount = Convert.ToInt32(Console.ReadLine());                  //to LandscapeSize^2
                        if (InitialFoxCount > MaxFox) //If number is bigger than MaxFox then user must input a smaller number
                        {
                            Console.WriteLine("Invalid input, please enter a number less than " + MaxFox);
                            Console.Write("Initial number of foxes: ");
                            InitialFoxCount = Convert.ToInt32(Console.ReadLine());
                        }
                        Console.Write("Randomness variability (percent): ");
                        Variability = Convert.ToInt32(Console.ReadLine());
                        FixedInitialLocations = false;
                    }
                    Sim = new Simulation(LandscapeSize, InitialWarrenCount, InitialFoxCount, Variability, FixedInitialLocations);
                }
            } while (MenuOption != 3);
            Console.ReadKey();
        }
    } //William Parkinson, Bridgwater College


Delphi/Pascal 解决方案

答案 

答案

procedure Main();
  var
    MenuOption : integer;
    LandscapeSize : integer;
    InitialWarrenCount : integer;
    InitialFoxCount : integer;
    Variability : integer;
    FixedInitialLocations : boolean;
    Sim : Simulation;
    validation : boolean; // Create a new validation boolean
  begin
    repeat
      writeln('Predator Prey Simulation Main Menu');
      writeln;
      writeln('1. Run simulation with default settings');
      writeln('2. Run simulation with custom settings');
      writeln('3. Exit');
      writeln;
      write('Select option: ');
      readln(MenuOption);
      if (MenuOption = 1) or (MenuOption = 2) then
        begin
          if MenuOption = 1 then
            begin
              LandscapeSize := 15;
              InitialWarrenCount := 5;
              InitialFoxCount := 5;
              Variability := 0;
              FixedInitialLocations := True;
            end
          else
            begin
              write('Landscape Size: ');
              readln(LandscapeSize);
              validation := false;
              repeat                       //Start of repeat
                write('Initial number of warrens: ');
                readln(InitialWarrenCount);
                if ((InitialWarrenCount <= sqr(LandscapeSize))and(InitialWarrenCount >= 0)) then
                  validation := true   // if statement to make sure a positive number inputted 
                else                   // and that no more warrens are enters than spaces avaialable
                  writeln('Invalid Input!')
              until (validation);                   //exits on the result of the validation
              validation := false;
              repeat                             //same validation for the number of foxes
                write('Initial number of foxes: ');
                readln(InitialFoxCount);
                if ((InitialFoxCount <= sqr(LandscapeSize))and(InitialFoxCount >= 0)) then
                  validation := true
                else
                  writeln('Invalid Input!');
              until (validation);
              write('Randomness variability (percent): ');
              readln(Variability);
              FixedInitialLocations := False;
            end;
          Sim := simulation.New(LandscapeSize, InitialWarrenCount, InitialFoxCount, Variability, FixedInitialLocations);
        end;
    until MenuOption = 3;
    readln;
  end; // Henry Atkins, Oakwood Park Grammar


Java 解决方案

答案 

答案

public class Main
{
    public static void main(String[] args) {
        Simulation Sim;
        int MenuOption;
        int LandscapeSize;
        int InitialWarrenCount;
        int InitialFoxCount;
        int Variability;
        Boolean FixedInitialLocations;
        do
        {
            Console.println("Predator Prey Simulation Main Menu");
            Console.println();
            Console.println("1. Run simulation with default settings");
            Console.println("2. Run simulation with custom settings");
            Console.println("3. Exit");
            Console.println();
            MenuOption = Console.readInteger("Select option: ");
            if (MenuOption == 1 || MenuOption == 2)
            {
                if (MenuOption == 1)
                {
                    LandscapeSize = 15;
                    InitialWarrenCount = 5;
                    InitialFoxCount = 5;
                    Variability = 0;
                    FixedInitialLocations = true;
                }
                else
                {   //Added input validation and restrictions on input like the number of initial warrens and foxes cannot be greater than the number of squares and that they have to be positive
                	LandscapeSize=-1;
                    LandscapeSize = Console.readInteger("Landscape Size: ");
                    while(LandscapeSize<0){
                    	Console.println("Please enter a number greater than 0!");
                    	LandscapeSize = Console.readInteger("Landscape Size: ");
                    }
                    
                    InitialWarrenCount=-1;
                    InitialWarrenCount = Console.readInteger("Initial number of warrens: ");
                    while(InitialWarrenCount<0 || InitialWarrenCount>=(LandscapeSize*LandscapeSize)){
                    	Console.println("Please enter a number between 0 and "+(LandscapeSize*LandscapeSize));
                    	InitialWarrenCount = Console.readInteger("Initial number of warrens: ");
                    }
                    
                    InitialFoxCount=-1; 
                    InitialFoxCount = Console.readInteger("Initial number of foxes: ");
                    while(InitialFoxCount<0 || InitialFoxCount>=(LandscapeSize*LandscapeSize)){
                    	Console.println("Please enter a number between 0 and "+(LandscapeSize*LandscapeSize));
                    	InitialFoxCount = Console.readInteger("Initial number of foxes: ");
                    }
                    
                    Variability=-2; 
                    Variability = Console.readInteger("Randomness variability (percent): ");
                    while(Variability<-1||Variability>101){
                    	Console.println("Please enter a number between 0 and 100!");
                    	 Variability = Console.readInteger("Randomness variability (percent): ");
                    }
                    
                    FixedInitialLocations = false;
                }
                Sim = new Simulation(LandscapeSize, InitialWarrenCount, InitialFoxCount, Variability, FixedInitialLocations);
            }
        } while (MenuOption != 3);
        Console.readLine();
    }
} // Gman, Reading School


Python 解决方案

答案 

答案

def Main():
  MenuOption = 0
  while MenuOption != 3:
    print("Predator Prey Simulation Main Menu")
    print()
    print("1. Run simulation with default settings")
    print("2. Run simulation with custom settings")
    print("3. Exit")
    print()
    MenuOption = int(input("Select option: "))
    if MenuOption == 1 or MenuOption == 2:
      if MenuOption == 1:
        LandscapeSize = 15
        InitialWarrenCount = 5
        InitialFoxCount = 5
        Variability = 0
        FixedInitialLocations = True
      else:
        LandscapeSize = int(input("Landscape Size: "))
        # ------- NEW -------
        #&nbsp;Store the LandscapeSize^2 in the variable 'Limit' because I'm lazy
        Limit = LandscapeSize * LandscapeSize
        
        #&nbsp;Get the InitialWarrenCount input and loop until it is less than the limit,
        # in this case LandscapeSize^2 as that's the max number of places on the board
        InitialWarrenCount = int(input("Initial number of warrens: "))
        while not InitialWarrenCount in range(0, Limit + 1):
            print("Please enter a value between 0 and {0} inclusive".format(Limit))
            InitialWarrenCount = int(input("Initial number of warrens: "))

        #&nbsp;Exactly the same deal as the warrens
        InitialFoxCount = int(input("Initial number of foxes: "))
        while not InitialFoxCount in range(0, Limit + 1):
            print("Please enter a value between 0 and {0} inclusive".format(Limit))
            InitialFoxCount = int(input("Initial number of foxes: "))
        # -------------------
        Variability = int(input("Randomness variability (percent): "))
        FixedInitialLocations = False
      Sim = Simulation(LandscapeSize, InitialWarrenCount, InitialFoxCount, Variability, FixedInitialLocations)
  input()


VB.NET 解决方案

答案 

答案


检查狐狸时,如果给定坐标中没有狐狸,显示错误消息并循环输入坐标

[编辑 | 编辑源代码]

C# 解决方案

答案 

答案

public Simulation(int LandscapeSize, int InitialWarrenCount, int InitialFoxCount, int Variability, bool FixedInitialLocations)
        {
            int menuOption;
            int x;
            int y;
            string viewRabbits;
            this.LandscapeSize = LandscapeSize;
            this.Variability = Variability;
            bool animalFound = false; //Bool used to make the search function loop is no animal is found.
            Landscape = new Location[LandscapeSize, LandscapeSize];
            CreateLandscapeAndAnimals(InitialWarrenCount, InitialFoxCount, FixedInitialLocations);
            DrawLandscape();

            do
            {
                Console.WriteLine();
                Console.WriteLine("1. Advance to next time period showing detail");
                Console.WriteLine("2. Advance to next time period hiding detail");
                Console.WriteLine("3. Inspect fox");
                Console.WriteLine("4. Inspect warren");
                Console.WriteLine("5. Exit");
                Console.WriteLine();
                Console.Write("Select option: ");
                menuOption = Convert.ToInt32(Console.ReadLine());

                if (menuOption == 1)
                {
                    TimePeriod++;
                    ShowDetail = true;
                    AdvanceTimePeriod();
                }
                if (menuOption == 2)
                {
                    TimePeriod++;
                    ShowDetail = false;
                    AdvanceTimePeriod();
                }
                if (menuOption == 3)
                {
                    do
                    {
                        x = InputCoordinate('x');
                        y = InputCoordinate('y');
                        if (Landscape[x, y].Fox != null)
                        {
                            animalFound = true; //Exits the loop when a fox has been found.
                            Landscape[x, y].Fox.Inspect();
                        }
                        else
                        {
                            animalFound = false;
                            //Tells the user there is no fox here.
                            Console.WriteLine("No fox found at (" + x + ", " + y + ")");

                            //Just in case they didn't mean to inspect:
                            Console.WriteLine("Would you like to continue the simulation? (y/n)");
                            if (Console.ReadLine() == "y")
                            {
                                animalFound = true;
                            }
                        }
                    }
                    while (animalFound == false);
                }
                if (menuOption == 4)
                {
                    do
                    {
                        x = InputCoordinate('x');
                        y = InputCoordinate('y');
                        if (Landscape[x, y].Warren != null)
                        {
                            animalFound = true;
                            Landscape[x, y].Warren.Inspect();
                            Console.Write("View individual rabbits (y/n)?");
                            viewRabbits = Console.ReadLine();
                            if (viewRabbits == "y")
                            {
                                Landscape[x, y].Warren.ListRabbits();
                            }
                        }
                        else
                        {
                            animalFound = false;
                            //Tells the user there is no warren here.
                            Console.WriteLine("No Warren found at (" + x + ", " + y + ")");

                            //Just in case they didn't mean to inspect:
                            Console.WriteLine("Would you like to continue the simulation? (y/n)");
                            if (Console.ReadLine() == "y")
                            {
                                animalFound = true;
                            }
                        }
                    }
                    while (animalFound == false);
                }
            }
            while (((WarrenCount > 0) || (FoxCount > 0)) && (menuOption != 5));
            Console.ReadKey();
        }
//Logan Dibnah, St Mary's College


Delphi/Pascal 解决方案

答案 

答案

      if MenuOption = 3 then
        begin
        Repeat
          x := InputCoordinate('x');  
          y := InputCoordinate('y');  
          if not(Landscape[x][y].Fox = nil) then  
            Landscape[x][y].fox.Inspect()  
          else
          begin
            Writeln;
            Writeln('No Fox was found at this location');
            Writeln;
          end
          until not(Landscape[x][y].Fox = nil)
        end;

//Harry Barron, Faringdon Community College


Java 解决方案

答案 

答案

if (MenuOption == 3)
            {
                x = InputCoordinate('x');
                y = InputCoordinate('y');
                
                //Validating x Co-ordinate
                while(x<0 || x>LandscapeSize){
                   System.out.println("Please enter in an x coordinate within range:");
                   x = InputCoordinate('x');
                }
                
                //Validating y Co-ordinate
                while(y<0 || y>LandscapeSize){
                   System.out.println("Please enter in an y coordinate within range:");
                   y = InputCoordinate('y');
                }
                
                //Validating that a fox is the position selected
                while (Landscape[x][y].Fox == null)
                {
                    System.out.println("Please enter in new coordinates:");
                   x = InputCoordinate('x');
                   y = InputCoordinate('y'); 
                }
                
                if(Landscape[x][y].Fox != null){
                    Landscape[x][y].Fox.Inspect();
                }
            
            }


Python 解决方案

答案 

答案

      if MenuOption == 3:
        while True:
            x = self.__InputCoordinate("x")
            y = self.__InputCoordinate("y")
            if not self.__Landscape[x][y].Fox is None:
              self.__Landscape[x][y].Fox.Inspect()
              break
            else:
              print("There is no fox at this location, try again")

Alternative Answer:

if MenuOption == 3:
        x = self.__InputCoordinate("x")
        y = self.__InputCoordinate("y")
        while self.__Landscape[x][y].Fox is None:
          print "Fox not found"
          x = self.__InputCoordinate("x")
          y = self.__InputCoordinate("y")
        self.__Landscape[x][y].Fox.Inspect()


Python 替代解决方案

答案 

答案

解决方案

if MenuOption == 3:
   Select=True
    while Select==True:
    x = self.__InputCoordinate("x")
    y = self.__InputCoordinate("y")
    if not self.__Landscape[x][y].Fox is None:
        self.__Landscape[x][y].Fox.Inspect()
        Select=False


VB.NET 解决方案

VB.NET 解决方案

答案 

答案

If MenuOption = 3 Then
                Do
                    x = InputCoordinate("x")
                    y = InputCoordinate("y")
                    'Gives repsonse when no fox is found
                    If Not Landscape(x, y).Fox Is Nothing Then
                        Landscape(x, y).Fox.Inspect()
                    Else
                        Console.WriteLine()
                        Console.WriteLine("No fox was found at this location")
                        Console.WriteLine()
                    End If
                Loop Until Not Landscape(x, y).Fox Is Nothing
            End If


添加一种新的动物(鹰/土狼?)可以猎杀狐狸

[编辑 | 编辑源代码]

C# 解决方案

答案,包括一只鹰和一只修改过的狐狸类,鹰有 25% 的几率会吃掉最近的狐狸,它具有相同的狐狸属性和有效的食物/死亡系统(它又快又脏,需要做很多改进)

答案

class Eagle : Animal
    {
        private int FoodUnitsNeeded = 10;
        private int FoodUnitsConsumedThisPeriod = 0;
        private const int DefaultLifespan = 7;
        private const double DefaultProbabilityDeathOtherCauses = 0.1;

        public Eagle(int Variability)
            : base(DefaultLifespan, DefaultProbabilityDeathOtherCauses, Variability)
        {
            FoodUnitsNeeded = (int)(10 * base.CalculateRandomValue(100, Variability) / 100);
        }

        public void AdvanceGeneration(bool ShowDetail)
        {
            if (FoodUnitsConsumedThisPeriod == 0)
            {
                IsAlive = false;
                if (ShowDetail)
                {
                    Console.WriteLine("  Eagle dies as has eaten no food this period.");
                }
            }
            else
            {
                if (CheckIfKilledByOtherFactor())
                {
                    IsAlive = false;
                    if (ShowDetail)
                    {
                        Console.WriteLine("  Eagle killed by other factor.");
                    }
                }
                else
                {
                    if (FoodUnitsConsumedThisPeriod < FoodUnitsNeeded)
                    {
                        CalculateNewAge();
                        if (ShowDetail)
                        {
                            Console.WriteLine("  Eagle ages further due to lack of food.");
                        }
                    }
                    CalculateNewAge();
                    if (!IsAlive)
                    {
                        if (ShowDetail)
                        {
                            Console.WriteLine("  Eagle has died of old age.");
                        }
                    }
                }
            }
        }

        public void ResetFoodConsumed()
        {
            FoodUnitsConsumedThisPeriod = 0;
        }

        public bool ReproduceThisPeriod()
        {
            const double ReproductionProbability = 0.25;
            if (Rnd.Next(0, 100) < ReproductionProbability * 100)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public void GiveFood(int FoodUnits)
        {
            FoodUnitsConsumedThisPeriod = FoodUnitsConsumedThisPeriod + FoodUnits;
        }

        public override void Inspect()
        {
            base.Inspect();
            Console.Write("Food needed " + FoodUnitsNeeded + " ");
            Console.Write("Food eaten " + FoodUnitsConsumedThisPeriod + " ");
            Console.WriteLine();
        }
    }

        private void DrawLandscape()
        {
            Console.WriteLine();
            Console.WriteLine("TIME PERIOD: " + TimePeriod);
            Console.WriteLine();
            Console.Write("    ");
            for (int x = 0; x < LandscapeSize; x++)
            {
                if (x < 10)
                {
                    Console.Write(" ");
                }
                Console.Write(x + " |");
            }
            Console.WriteLine();
            for (int x = 0; x <= LandscapeSize * 4 + 3; x++)
            {
                Console.Write("-");
            }
            Console.WriteLine();
            for (int y = 0; y < LandscapeSize; y++)
            {
                if (y < 10)
                {
                    Console.Write(" ");
                }
                Console.Write(" " + y + "|");
                for (int x = 0; x < LandscapeSize; x++)
                {
                    if (Landscape[x, y].Warren != null)
                    {
                        if (Landscape[x, y].Warren.GetRabbitCount() < 10)
                        {
                            Console.Write(" ");
                        }
                        Console.Write(Landscape[x, y].Warren.GetRabbitCount());
                    }
                    else
                    {
                        Console.Write("  ");
                    }
                    if (Landscape[x, y].Fox != null)
                    {
                        Console.Write("F");
                    }
                    else if (Landscape[x, y].Eagle != null)
                    {
                        Console.Write("E");
                    }
                    else
                    {
                        Console.Write(" ");
                    }
                    Console.Write("|");
                }
                Console.WriteLine();
            }
        }
    }
  private void EagleEatFox(int EagleX, int EagleY)
        {
            int ClosestFoxX = 0, ClosestFoxY = 0;
            double ClosestDistance = 999;
            for(int x = 0; x < LandscapeSize; x++)
            {
                for (int y = 0; y < LandscapeSize; y++)
                {
                    if (Landscape[x, y].Fox != null)
                    {
                        if(DistanceBetween(EagleX, EagleY, x, y) < ClosestDistance)
                        {
                            ClosestDistance = DistanceBetween(EagleX, EagleY, x, y);
                            ClosestFoxX = x;
                            ClosestFoxY = y;
                        }
                    }  
                }
            }
            if (Rnd.Next(1, 100) < 25)
            {
                Landscape[ClosestFoxX, ClosestFoxY].Fox = null;
                Landscape[EagleX, EagleY].Eagle.GiveFood(10);
                Console.WriteLine("Fox Eaten At: (" + ClosestFoxX + "," + ClosestFoxY + ")");
            }
        }
 private void AdvanceTimePeriod()
        {
            int NewFoxCount = 0;
            if (ShowDetail)
            {
                Console.WriteLine();
            }
            for (int x = 0; x < LandscapeSize; x++)
            {
                for (int y = 0; y < LandscapeSize; y++)
                {
                    if (Landscape[x, y].Warren != null)
                    {
                        if (ShowDetail)
                        {
                            Console.WriteLine("Warren at (" + x + "," + y + "):");
                            Console.Write("  Period Start: ");
                            Landscape[x, y].Warren.Inspect();
                        }
                        if (FoxCount > 0)
                        {
                            FoxesEatRabbitsInWarren(x, y);
                        }
                        if (Landscape[x, y].Warren.NeedToCreateNewWarren())
                        {
                            CreateNewWarren();
                        }
                        Landscape[x, y].Warren.AdvanceGeneration(ShowDetail);
                        if (ShowDetail)
                        {
                            Console.Write("  Period End: ");
                            Landscape[x, y].Warren.Inspect();
                            Console.ReadKey();
                        }
                        if (Landscape[x, y].Warren.WarrenHasDiedOut())
                        {
                            Landscape[x, y].Warren = null;
                            WarrenCount--;
                        }
                    }
                }
            }
            for (int x = 0; x < LandscapeSize; x++)
            {
                for (int y = 0; y < LandscapeSize; y++)
                {
                    if (Landscape[x, y].Fox != null)
                    {
                        if (ShowDetail)
                        {
                            Console.WriteLine("Fox at (" + x + "," + y + "): ");
                        }
                        Landscape[x, y].Fox.AdvanceGeneration(ShowDetail);
                        if (Landscape[x, y].Fox.CheckIfDead())
                        {
                            Landscape[x, y].Fox = null;
                            FoxCount--;
                        }
                        else
                        {
                            if (Landscape[x, y].Fox.ReproduceThisPeriod())
                            {
                                if (ShowDetail)
                                {
                                    Console.WriteLine("  Fox has reproduced. ");
                                }
                                NewFoxCount++;
                            }
                            if (ShowDetail)
                            {
                                Landscape[x, y].Fox.Inspect();
                            }
                            Landscape[x, y].Fox.ResetFoodConsumed();
                        }
                    }
                }
            }
            for (int x = 0; x < LandscapeSize; x++)
            {
                for (int y = 0; y < LandscapeSize; y++)
                {
                    if (Landscape[x, y].Eagle != null)
                    {
                        if (ShowDetail)
                        {
                            Console.WriteLine("Eagle at (" + x + "," + y + "): ");
                        }
                        EagleEatFox(x, y);
                        Landscape[x, y].Eagle.AdvanceGeneration(ShowDetail);
                        if (Landscape[x, y].Eagle.CheckIfDead())
                        {
                            Landscape[x, y].Eagle = null;
                            EagleCount--;
                        }
                        else
                        {
                            if (Landscape[x, y].Eagle.ReproduceThisPeriod())
                            {
                                if (ShowDetail)
                                {
                                    Console.WriteLine("  Eagle has reproduced. ");
                                }

                            }
                            if (ShowDetail)
                            {
                                Landscape[x, y].Eagle.Inspect();
                            }
                            Landscape[x, y].Eagle.ResetFoodConsumed();
                        }
                    }
                }
                if (NewFoxCount > 0)
                {
                    if (ShowDetail)
                    {
                        Console.WriteLine("New foxes born: ");
                    }
                    for (int f = 0; f < NewFoxCount; f++)
                    {
                        CreateNewFox();
                    }
                }
                if (ShowDetail)
                {
                    Console.ReadKey();
                }
                DrawLandscape();
                Console.WriteLine();
            }
        }
 static void Main(string[] args)
        {
            Simulation Sim;
            int MenuOption;
            int LandscapeSize;
            int InitialWarrenCount;
            int InitialFoxCount;
            int InitialEagleCount;
            int Variability;
            bool FixedInitialLocations;
            do
            {
                Console.WriteLine("Predator Prey Simulation Main Menu");
                Console.WriteLine();
                Console.WriteLine("1. Run simulation with default settings");
                Console.WriteLine("2. Run simulation with custom settings");
                Console.WriteLine("3. Exit");
                Console.WriteLine();
                Console.Write("Select option: ");
                MenuOption = Convert.ToInt32(Console.ReadLine());
                if ((MenuOption == 1) || (MenuOption == 2))
                {
                    if (MenuOption == 1)
                    {
                        LandscapeSize = 15;
                        InitialWarrenCount = 5;
                        InitialFoxCount = 5;
                        InitialEagleCount = 5;
                        Variability = 0;
                        FixedInitialLocations = true;
                    }
                    else
                    {
                        Console.Write("Landscape Size: ");
                        LandscapeSize = Convert.ToInt32(Console.ReadLine());
                        Console.Write("Initial number of warrens: ");
                        InitialWarrenCount = Convert.ToInt32(Console.ReadLine());
                        Console.Write("Initial number of foxes: ");
                        InitialFoxCount = Convert.ToInt32(Console.ReadLine());
                        Console.Write("Initial Number of eagles: ");
                        InitialEagleCount = Convert.ToInt32(Console.ReadLine());
                        Console.Write("Randomness variability (percent): ");
                        Variability = Convert.ToInt32(Console.ReadLine());
                        FixedInitialLocations = false;
                    }
                    Sim = new Simulation(LandscapeSize, InitialWarrenCount, InitialFoxCount, Variability, FixedInitialLocations, InitialEagleCount);
                }
            } while (MenuOption != 3);
            Console.ReadKey();
        }
    }
// Harry G Poole High School


Delphi/Pascal 解决方案

答案目前不完整。将在两天内完成它(添加了一些功能,请参见第一个答案下面的内容)

答案

//This method only allows eagle to kill fox. There is not reporoduction, death or food units for eagle. This can be implemented but takes time.
//Also if you make any changes to the constuctors or procedures in the class declaration, you must change them when you implement that constructor or procedure   
// In the fox class add 'killedbyeagle' parameter to AdvanceGeneration
 procedure AdvanceGeneration(ShowDetail : boolean; killedbyeagle:boolean);

//Create a new class
Type Eagle = class(Animal)  //Creating the Eagle Class
     Private
      DefaultLifespan : integer;    // Some properties these dont really get used though
      DefaultProbabilityDeathOtherCauses : double;
     Public
     Constructor New(Variability :integer); Overload;  // Creating the actual object Eagle
end;

//Add to the Location Class under Public
 Eagle:Eagle;  // Allowing Eagle to be part of the location class

//Add to the simulation class under Private
Eaglecount:integer;
killedbyeagle:boolean;
Procedure EaglesEatFoxes(FoxX:integer;FoxY:integer);  // Eats Foxes procedure
//Add parameter to CreateLandscapeAnimals as shown below
procedure CreateLandscapeAndAnimals(InitialWarrenCount : integer; InitialFoxCount : integer; FixedInitialLocations : Boolean; InitialsEaglesCount:integer);

//Add parameter to the constructor under Public in Simulation Class as shown below
constructor New(LandscapeSizeInput : integer; InitialWarrenCount : integer; InitialFoxCount : integer; VariabilityInput : integer; FixedInitialLocations : boolean; InitialEaglesCount:integer);

//Add this after Fox.New constructor
Constructor Eagle.New(Variability :integer);
begin
self.New(DefaultLifespan, DefaultProbabilityDeathOtherCauses, Variability); //Just creates the Eagle  and initialises some values
End;

//Modify the first part Fox.AdvanceGeneration
procedure Fox.AdvanceGeneration(ShowDetail : boolean ; killedbyeagle:boolean);
   begin
      IF killedbyEagle then   
          begin
            IsAlive := False;   //set to true if an Eagle has found it
            if ShowDetail then
            writeln('Fox killed by eagle.');
          end
         else
          begin
          writeln('No sighting  by eagle') ; //
    end;

// Add to the Location.New Constructor
Eagle:=nil;

//Add this to the Simulation.New constructor after FoxCount
Eaglecount:=0;

{By Dayo(Did the majority) and Jalp(Fixed Errors)}

//using your code outlined above i managed to implement the eagle further into the program where it displays on the screen and kills foxes

//add this code to the main procedure after the number of foxes 
write('Initial number of eagles: ');
readln(InitialeagleCount);

//add this to the Simulation.CreateLandscapeAndAnimals procedure
var
  e : integer; 
// add this to the else statement under the fox creation
for e  := 0 to InitialEagleCount - 1 do // add eagles into the landscape
  CreateNewEagle();

//add this to the Simulation class
procedure CreateNewEagle(); // create the new eagle in the simulation

//create a new procedure in simulation to create the eagle similar to the fox
procedure Simulation.CreateNewEagle(); // create new eagle
  var
    x : integer;
    y : integer;
    begin
      repeat
      x := Random(landscapesize);
      y := random(landscapesize);
      until landscape[x][y].Eagle = nil;         // make sure there is no eagle already in that spot
        if showdetail then
          writeln(' New Eagle at (',x, ',',y, ')');
        Landscape[x][y].Eagle := eagle.new(Variability);
    end;

//edit the display so that it looks nicer inside the Simulation.DrawLandscape procedure
 for x := 0 to LandscapeSize - 1 do
      begin
        if x < 10 then
          write(' ');
        write(x, '  |');   //another space for spacing
      end;
    writeln;
    for x:=0 to LandscapeSize * 5 + 3 do // 5 was a 4 to change for spacing
      write('-');
//also add in under the fox input
            if not(self.Landscape[x][y].Eagle = nil) then
              write('E')
            else
              write(' ');
//in Simulation.AdvanceTimePeriod add this variable
eaglespotted : boolean;

//and add this at the start of the fox loop 
            if ShowDetail then
              Writeln('Fox at (', x, ',', y, '): ');
            EagleSpotted := self.EaglesEatFoxes(x,y); // if the fox is spotted by the eagle
            Landscape[x][y].Fox.AdvanceGeneration(ShowDetail,eagleSpotted);// add if the eagle eats the fox

// form the example i changed the EaglesEatFoxes to a function that returned boolean like so
Function EaglesEatFoxes(FoxX : integer; FoxY : integer): boolean; // function return boolean

// the then edited code for the simulation.EaglesEatFoxes
function Simulation.EaglesEatFoxes(FoxX: Integer; FoxY: Integer): boolean; // calculates a random value
  var
    i : integer;
  begin
    i := random(1000);        // on some condition then the function is true
    if i mod 37 = 0 then       // example if the number is divisible by 37 then it is true
      EaglesEatFoxes := true
    else
      EaglesEatFoxes := false;
  end;

//this then makes it possible for the eagle to spot and kill the fox, the eagle still has no food needed and cannot die but adds some functionality
//Henry Atkins, Oakwood Park Grammar


Java 解决方案

答案 

答案

我想到的这个作为快速测试。我确信这可以用更有效的方式完成,但这样做确实有效。在底部附近有更多说明!

class AlexHunter extends Animal {
	private static final int DefaultLifeSpan = 1000;
	private static final double DefaultProbabilityDeathOtherCauses = 0.0;
	static int LandscapeSize = Simulation.getLandscapeSize();
	static int[] x = new int[(int) Math.pow(LandscapeSize, 2)];
	static int[] y = new int[(int) Math.pow(LandscapeSize, 2)];
	
	static int a = 0;
	
	public AlexHunter(int Variability) {
		super(DefaultLifeSpan, DefaultProbabilityDeathOtherCauses, Variability);
	}
	
	public static void findFox(Location[][] Landscape) {
		// This finds where the foxes are on the map and stores the x and y coordinates in separate arrays
		for (int i = 0; i < LandscapeSize; i++) {
			for (int j = 0; j < LandscapeSize; j++) {
				if (Landscape[i][j].Fox != null) {
					
					x[a] = i;
					y[a] = j;
					
					a++;
				}
				
			}
		}
	}
	
	public static void killRandomFox(Location[][] Landscape) {
		// This takes a random set of coordinates of where the foxes are and kills the fox in that coordinate
		int coord = Rnd.nextInt(a);
		
		Landscape[x[coord]][y[coord]].Fox = null;
		
		Console.println("Fox has been murdered at (" + x[coord] + ", " + y[coord] + ") by The Hunter");
	}
	
}

// Call the findFoxes method in the AdvanceTimePeriod method in the Simluation class at the beginning and then put the below line of code just before the if(showdetail) condition:

     if (Rnd.nextInt(100) < 10) {
        	AlexHunter.killRandomFox(Landscape);
        }

// Hope that makes sense!

// Harnaam Jandoo - Reading School


Python 解决方案

答案 

答案

# This is a simple solution that can be improved upon with variability, making the eagles move, etc
#&nbsp;But as none of that is specified in the question (and it's two in the morning) I'll let you do that!
#&nbsp;Also worth noting is that these eagles are tanks and will pretty much destroy all foxes as they will kill all foxes with a Euclidian distance <= 5
#&nbsp;They also cannot die, breed or move. However, this would not be hard to implement using the animal class

#&nbsp;Add an Eagle property to the existing Location class
#&nbsp;This is so we can store instances of the Eagle in different locations in the grid
class Location:
  def __init__(self):
    self.Fox = None
    self.Warren = None
    #&nbsp;---------- New ----------
    self.Eagle = None
    #&nbsp;-------------------------

#&nbsp;Add an EagleCount variable to Simulation in the init method
#&nbsp;This is so we can keep track of all the Eagle instances
self.__EagleCount = 0

#&nbsp;Create an Eagle class that inherits from Animal (I just stole the constructor from the fox but this is where you can get creative)
class Eagle(Animal):
  def __init__(self, Variability):
    self.__DEFAULT_LIFE_SPAN = 7
    self.__DEFAULT_PROBABILITY_DEATH_OTHER_CAUSES = 0.1
    super(Eagle, self).__init__(self.__DEFAULT_LIFE_SPAN, self.__DEFAULT_PROBABILITY_DEATH_OTHER_CAUSES, Variability)
    self.__FoodUnitsNeeded = int(10 * self._CalculateRandomValue(100, Variability) / 100)
    self.__FoodUnitsConsumedThisPeriod  = 0

#&nbsp;Add a KilledByEagle property in the Fox class (This is lazy but it works)
#&nbsp;It should be false by default
KilledByEagle = False

#&nbsp;Add the eagles in the Simulation.__CreateLandscapeAndAnimals() method
#&nbsp;Add the following lines of code after and outside of the FixedInitialLocations conditional
#&nbsp;Loop from 0 - n eagles that need to be placed (I hard coded 5)
#&nbsp;Check different Locations on the grid until it can place an eagle
for e in range(0, 5):
      x = random.randint(0, self.__LandscapeSize - 1)
      y = random.randint(0, self.__LandscapeSize - 1)

      while not self.__Landscape[x][y].Eagle is None:
        x = random.randint(0, self.__LandscapeSize - 1)
        y = random.randint(0, self.__LandscapeSize - 1)

      if self.__ShowDetail:
        print("New Eagle at ({0}, {1})".format(x, y))

      self.__Landscape[x][y].Eagle = Eagle(self.__Variability)
      self.__EagleCount += 1

#&nbsp;Overwrite the CheckIfKilledByOtherFactor() method in the fox class, inherited from the animal class
#&nbsp;Add a conditional to check if Fox.KilledByEagle is true. If not run the original method and return its values
#&nbsp;Reference the parent class method using super(Fox, self)
def CheckIfKilledByOtherFactor(self):
    if self.KilledByEagle:
      print("Eagles killed fox!")
      self._IsAlive = False
      return True
    else:
      return super(Fox, self).CheckIfKilledByOtherFactor()

#&nbsp;Create an __EaglesEatFox() method in Simulation that takes a fox's x and y
#&nbsp;It will loop through each space in the grid and check for an eagle
#&nbsp;Once an eagle is found it will check the Euclidian distance between the Eagle and the Fox
#&nbsp;If the distance is less than 5 is will mark the Fox for death when the AdvanceGeneration() method is run on it
def __EaglesEatFox(self, foxX, foxY):
    for EagleX in range(0, self.__LandscapeSize):
      for EagleY in range(0, self.__LandscapeSize):
        if not self.__Landscape[EagleX][EagleY].Eagle is None:
          dist = self.__DistanceBetween(EagleX, EagleY, foxX, foxY)
          # print("Distance = {0}".format(dist))

          if dist <= 5:
            self.__Landscape[foxX][foxY].Fox.KilledByEagle = True

#&nbsp;In Simulation().__AdvanceTimePeriod() run the __EaglesEatFox() method just before the AdvanceGeneration method is run on the fox (in the second set of loops)
#&nbsp;Pass it the current X and Y coordinates of the fox
#&nbsp;In this example the count will always be 5 but you could add the ability for them to breed and die
#&nbsp;A lot of this can be achieved using the animal class we are inheriting from
if self.__EagleCount > 0:
            self.__EaglesEatFox(x, y)


VB.NET 解决方案

答案 

答案

//Ben Sosteric Riddlesdown
Dim InitialEagleCount As Integer
        Dim Variability As Integer
        Dim FixedInitialLocations As Boolean
        Do
            Console.WriteLine("Predator Prey Simulation Main Menu")
            Console.WriteLine()
            Console.WriteLine("1. Run simulation with default settings")
            Console.WriteLine("2. Run simulation with custom settings")
            Console.WriteLine("3. Rabbit Paradise")
            Console.WriteLine("4. Exit")
            Console.WriteLine()
            Console.Write("Select option: ")
            MenuOption = CInt(Console.ReadLine())
            If MenuOption = 1 Or MenuOption = 2 Or MenuOption = 3 Then
                If MenuOption = 1 Then
                    LandscapeSize = 14
                    InitialWarrenCount = 5
                    InitialFoxCount = 5
                    InitialEagleCount = 5
                    Variability = 0
                    FixedInitialLocations = True
                ElseIf MenuOption = 3 Then
                    LandscapeSize = 20
                    InitialWarrenCount = 20
                    InitialFoxCount = 0
                    InitialEagleCount = 0
                    Variability = 1
                    FixedInitialLocations = False

                Else
                    Console.Write("Landscape Size: ")
                    LandscapeSize = CInt(Console.ReadLine())
                    Console.Write("Initial number of warrens: ")
                    InitialWarrenCount = CInt(Console.ReadLine())
                    Console.Write("Initial number of foxes: ")
                    InitialFoxCount = CInt(Console.ReadLine())
                    Console.WriteLine("Initial number of eagles: ")
                    InitialEagleCount = CInt(Console.ReadLine)
                    Console.Write("Randomness variability (percent): ")
                    Variability = CInt(Console.ReadLine())
                    FixedInitialLocations = False
                End If
                Dim Sim As New Simulation(LandscapeSize, InitialWarrenCount, InitialFoxCount, InitialEagleCount, Variability, FixedInitialLocations)
            End If

Class Location
        Public Fox As Fox
        Public Warren As Warren
        Public Eagle As Eagles

        Public Sub New()
            Fox = Nothing
            Warren = Nothing
            Eagle = Nothing
        End Sub
    End Class

Class Simulation
        Private Landscape(,) As Location
        Private TimePeriod As Integer = 0
        Private WarrenCount As Integer = 0
        Private FoxCount As Integer = 0
        Private Eaglecount As Integer = 0
        Private ShowDetail As Boolean = False
        Private LandscapeSize As Integer
        Private Variability As Integer
        Private Shared Rnd As New Random()

        Public Sub New(ByVal LandscapeSize As Integer, ByVal InitialWarrenCount As Integer, ByVal InitialFoxCount As Integer, ByVal InitialEagleCount As Integer, ByVal Variability As Integer, ByVal FixedInitialLocations As Boolean)
            Dim MenuOption As Integer
            Dim x As Integer
            Dim y As Integer
            Dim ViewRabbits As String
            Dim checkfox As Boolean
            Me.LandscapeSize = LandscapeSize
            Me.Variability = Variability
            Landscape = New Location(LandscapeSize, LandscapeSize) {}
            CreateLandscapeAndAnimals(InitialWarrenCount, InitialFoxCount, InitialEagleCount, FixedInitialLocations)
            DrawLandscape()
            Do
                Console.WriteLine()
                Console.WriteLine("0. Advance time by 10 periods hiding detail")
                Console.WriteLine("1. Advance to next time period showing detail")
                Console.WriteLine("2. Advance to next time period hiding detail")
                Console.WriteLine("3. Inspect fox")
                Console.WriteLine("4. Inspect warren")
                Console.WriteLine("5. Inspect Eagle")
                Console.WriteLine("6. Exit")
//Under the same sub
If MenuOption = 5 Then
                    x = InputCoordinate("x")
                    y = InputCoordinate("y")
                    If Not Landscape(x, y).Eagle Is Nothing Then
                        Landscape(x, y).Eagle.Inspect()
                    End If
                End If
            Loop While (WarrenCount > 0 Or FoxCount > 0 Or Eaglecount > 0) And MenuOption <> 6
            Console.ReadKey()

 Private Sub AdvanceTimePeriod(ByVal menuoption As Integer)
            Dim NewFoxCount As Integer = 0
            Dim NewEagleCount As Integer = 0
            If ShowDetail Then
                Console.WriteLine()
            End If
            For z = 0 To 9
                If menuoption <> 0 Then
                    z = 9
                End If
                For x = 0 To LandscapeSize - 1
                    For y = 0 To LandscapeSize - 1
                        If Not Landscape(x, y).Warren Is Nothing Then
                            If ShowDetail Then
                                Console.WriteLine("Warren at (" & x & "," & y & "):")
                                Console.Write("  Period Start: ")
                                Landscape(x, y).Warren.Inspect()
                            End If
                            If FoxCount > 0 Then
                                FoxesEatRabbitsInWarren(x, y)
                            End If
                            If Eaglecount > 0 Then
                                EaglesEatFoxes(x, y)
                            End If
//Under same sub
 For x = 0 To LandscapeSize - 1
                    For y = 0 To LandscapeSize - 1
                        If Not Landscape(x, y).Eagle Is Nothing Then
                            If ShowDetail Then
                                Console.WriteLine("Eagle at (" & x & "," & y & "): ")
                            End If
                            Landscape(x, y).Eagle.AdvanceGeneration(ShowDetail)
                            If Landscape(x, y).Eagle.CheckIfDead() Then
                                Landscape(x, y).Eagle = Nothing
                                Eaglecount -= 1
                            Else
                                If Landscape(x, y).Eagle.ReproduceThisPeriod() Then
                                    If ShowDetail Then
                                        Console.WriteLine("  Eagle has reproduced. ")
                                    End If
                                    NewEagleCount += 1
                                End If
                                If ShowDetail Then
                                    Landscape(x, y).Eagle.Inspect()
                                End If
                                Landscape(x, y).Eagle.ResetFoodConsumed()
                            End If
                        End If
                    Next
                Next
                If NewEagleCount > 0 Then
                    If ShowDetail Then
                        Console.WriteLine("New Eagles born: ")
                    End If
                    For f = 0 To NewEagleCount - 1
                        CreateNewEagle()
                    Next
                End If
                If ShowDetail Then
                    Console.ReadKey()
                End If
                DrawLandscape()
                Console.WriteLine()
            Next
        End Sub

Private Sub CreateLandscapeAndAnimals(ByVal InitialWarrenCount As Integer, ByVal InitialFoxCount As Integer, ByVal InitialEagleCount As Integer, ByVal FixedInitialLocations As Boolean)

Landscape(3, 7).Eagle = New Eagles(Variability, 45)
                Landscape(4, 9).Eagle = New Eagles(Variability, 70)
                Landscape(1, 6).Eagle = New Eagles(Variability, 45)
                Landscape(8, 4).Eagle = New Eagles(Variability, 45)
                Landscape(11, 5).Eagle = New Eagles(Variability, 45)
                Eaglecount = 5
            Else
                For w = 0 To InitialWarrenCount - 1
                    CreateNewWarren()
                Next
                For f = 0 To InitialFoxCount - 1
                    CreateNewFox()
                Next
                For e = 0 To InitialEagleCount - 1
                    CreateNewEagle()
                Next
            End If
        End Sub

Private Sub CreateNewEagle()
            Dim x As Integer
            Dim y As Integer
            Do
                x = Rnd.Next(0, LandscapeSize)
                y = Rnd.Next(0, LandscapeSize)
            Loop While Not Landscape(x, y).Eagle Is Nothing
            If ShowDetail Then
                Console.WriteLine("  New Eagle at (" & x & "," & y & ")")
            End If
            Landscape(x, y).Eagle = New Eagles(Variability, 46)
            Eaglecount += 1
        End Sub

  Private Sub EaglesEatfoxes(ByVal WarrenX As Integer, ByVal WarrenY As Integer)
            Dim FoodConsumed As Integer
            Dim PercentToEat As Integer
            Dim Dist As Double
            Dim RabbitsToEat As Integer
            Dim RabbitCountAtStartOfPeriod As Integer = Landscape(WarrenX, WarrenY).Warren.GetRabbitCount()
            For EagleX = 0 To LandscapeSize - 1
                For EagleY = 0 To LandscapeSize - 1
                    If Not Landscape(EagleX, EagleY).Eagle Is Nothing Then
                        Dist = DistanceBetween(EagleX, EagleY, WarrenX, WarrenY)
                        If Dist <= 3.5 Then
                            PercentToEat = 20
                        ElseIf Dist <= 7 Then
                            PercentToEat = 10
                        Else
                            PercentToEat = 0
                        End If
                        RabbitsToEat = CInt(Math.Round(CDbl(PercentToEat * RabbitCountAtStartOfPeriod / 100)))
                        FoodConsumed = Landscape(WarrenX, WarrenY).Warren.EatRabbits(RabbitsToEat)
                        Landscape(EagleX, EagleY).Eagle.GiveFood(FoodConsumed)
                        If ShowDetail Then
                            Console.WriteLine("  " & FoodConsumed & " foxes eaten by Eagle at (" & EagleX & "," & EagleY & ").")
                        End If
                    End If
                Next
            Next
        End Sub

 Private Sub DrawLandscape()
If Not Landscape(x, y).Eagle Is Nothing Then
                        Console.Write("E")
                    Else
                        Console.Write(" ")
                    End If
                    Console.Write("|")
                Next
                Console.WriteLine()
            Next
        End Sub

Class Eagles
        Inherits Animal
        Enum Genders
            Male
            Female
        End Enum
        Private ReproductionRate As Double
        Private FoodUnitsNeeded As Integer = 10
        Private FoodUnitsConsumedThisPeriod As Integer = 0
        Private Const DefaultLifespan As Integer = 7
        Private Const DefaultProbabilityDeathOtherCauses As Double = 0.1
        Private Const GenderratioEagle As Integer = 34
        Private Gender As Genders

        Public Sub New(ByVal Variability As Integer, ByVal parentsreproductionrate As Double)
            MyBase.New(DefaultLifespan, DefaultProbabilityDeathOtherCauses, Variability)
            FoodUnitsNeeded = CInt(10 * MyBase.CalculateRandomValue(100, Variability) / 100)
            ReproductionRate = parentsreproductionrate * MyBase.CalculateRandomValue(100, Variability) / 100
            If Rnd.Next(0, 100) < GenderratioEagle Then
                Gender = Genders.Male
            Else
                Gender = Genders.Female
            End If
        End Sub

        Public Sub AdvanceGeneration(ByVal ShowDetail As Boolean)
            If FoodUnitsConsumedThisPeriod = 0 Then
                IsAlive = False
                If ShowDetail Then
                    Console.WriteLine("  Eagle dies as has eaten no food this period.")
                End If
            Else
                If CheckIfKilledByOtherFactor() Then
                    IsAlive = False
                    If ShowDetail Then
                        Console.WriteLine("  Eagle killed by other factor.")
                    End If
                Else
                    If FoodUnitsConsumedThisPeriod < FoodUnitsNeeded Then
                        CalculateNewAge()
                        If ShowDetail Then
                            Console.WriteLine("  Eagle ages further due to lack of food.")
                        End If
                    End If
                    CalculateNewAge()
                    If Not IsAlive Then
                        If ShowDetail Then
                            Console.WriteLine("  Eagle has died of old age.")
                        End If
                    End If
                End If
            End If
        End Sub

        Public Sub ResetFoodConsumed()
            FoodUnitsConsumedThisPeriod = 0
        End Sub

        Public Function ReproduceThisPeriod() As Boolean
            Const ReproductionProbability As Double = 0.10
            If Rnd.Next(0, 100) < ReproductionProbability * 100 And Gender = Genders.Female Then
                Return True
            Else
                Return False
            End If
        End Function

        Public Sub GiveFood(ByVal FoodUnits As Integer)
            FoodUnitsConsumedThisPeriod = FoodUnitsConsumedThisPeriod + FoodUnits
        End Sub

        Public Overrides Sub Inspect()
            MyBase.Inspect()
            Console.Write("Food needed " & FoodUnitsNeeded & " ")
            Console.Write("Food eaten " & FoodUnitsConsumedThisPeriod & " ")
            Console.WriteLine()
            MyBase.Inspect()
            Console.Write("Rep rate " & Math.Round(ReproductionRate, 1) & " ")
            If Gender = Genders.Female Then
                Console.WriteLine("Gender Female")
            Else
                Console.WriteLine("Gender Male")
            End If
        End Sub
    End Class


狐狸每次时期都有一个随机的几率向最近的兔窝移动

[编辑 | 编辑源代码]

C# 解决方案

包括一个新的过程和附加的 AdvanceTimePeriod 过程,唯一的问题是狐狸有可能会被移动两次,在狐狸类中添加一个布尔值来表示它们是否在那个时期被移动过,就能解决这个问题。答案 

答案

 private void AdvanceTimePeriod()
        {
            int NewFoxCount = 0;
            if (ShowDetail)
            {
                Console.WriteLine();
            }
            for (int x = 0; x < LandscapeSize; x++)
            {
                for (int y = 0; y < LandscapeSize; y++)
                {
                    if (Landscape[x, y].Warren != null)
                    {
                        if (ShowDetail)
                        {
                            Console.WriteLine("Warren at (" + x + "," + y + "):");
                            Console.Write("  Period Start: ");
                            Landscape[x, y].Warren.Inspect();
                        }
                        if (FoxCount > 0)
                        {
                            FoxesEatRabbitsInWarren(x, y);
                        }
                        if (Landscape[x, y].Warren.NeedToCreateNewWarren())
                        {
                            CreateNewWarren();
                        }
                        Landscape[x, y].Warren.AdvanceGeneration(ShowDetail);
                        if (ShowDetail)
                        {
                            Console.Write("  Period End: ");
                            Landscape[x, y].Warren.Inspect();
                            Console.ReadKey();
                        }
                        if (Landscape[x, y].Warren.WarrenHasDiedOut())
                        {
                            Landscape[x, y].Warren = null;
                            WarrenCount--;
                        }
                    }
                }
            }
            for (int x = 0; x < LandscapeSize; x++)
            {
                for (int y = 0; y < LandscapeSize; y++)
                {
                    if (Landscape[x, y].Fox != null )
                    {
                        if (ShowDetail)
                        {
                            Console.WriteLine("Fox at (" + x + "," + y + "): ");
                        }
                        
                        Landscape[x, y].Fox.AdvanceGeneration(ShowDetail);
                        if (Landscape[x, y].Fox.CheckIfDead())
                        {
                            Landscape[x, y].Fox = null;
                            FoxCount--;
                        }
                        else
                        {
                            if (Landscape[x, y].Fox.ReproduceThisPeriod())
                            {
                                if (ShowDetail)
                                {
                                    Console.WriteLine("  Fox has reproduced. ");
                                }
                                NewFoxCount++;
                            }
                            if (ShowDetail)
                            {
                                Landscape[x, y].Fox.Inspect();
                            }
                            Landscape[x, y].Fox.ResetFoodConsumed();
                            MoveFox(x, y, ref Landscape);
                        }
                    }
                }
            }

            if (NewFoxCount > 0)
            {
                if (ShowDetail)
                {
                    Console.WriteLine("New foxes born: ");
                }
                for (int f = 0; f < NewFoxCount; f++)
                {
                    CreateNewFox();
                }
            }
            if (ShowDetail)
            {
                Console.ReadKey();
            }
            DrawLandscape();
            Console.WriteLine();
        }

 private void MoveFox(int FoxX, int FoxY, ref Location[,] Landscape)
        {
            double ClosestWarren = 0;
            int ClosestWarrenX = 0, ClosestWarrenY = 0, NewFoxX = 0, NewFoxY = 0;
            for(int i = 0; i < Landscape.GetLength(0); i++)
            {
                for(int j = 0; j < Landscape.GetLength(1); j++)
                {
                    if (Landscape[i, j].Warren != null)
                    {
                        if (DistanceBetween(FoxX, FoxY, i, j) < ClosestWarren || ClosestWarren == 0)
                        {
                            ClosestWarren = DistanceBetween(FoxX, FoxY, i, j);
                            ClosestWarrenX = i;
                            ClosestWarrenY = j;
                        }
                    }
                }
            }
            if(ClosestWarrenX < FoxX)
            {
                NewFoxX = FoxX-1;
            }
            if (ClosestWarrenY < FoxY)
            {
                NewFoxY = FoxY-1;
            }
            if (ClosestWarrenX > FoxX)
            {
                NewFoxX = FoxX+1;
            }
            if (ClosestWarrenY > FoxY)
            {
                NewFoxY = FoxY+1;
            }
            if(ClosestWarrenX == FoxX)
            {
                NewFoxX = FoxX;
            }
            if (ClosestWarrenY == FoxY)
            {
                NewFoxY = FoxY;
            }
            Landscape[NewFoxX, NewFoxY].Fox = Landscape[FoxX, FoxY].Fox;
            Landscape[FoxX, FoxY].Fox = null;
        }


Delphi/Pascal 解决方案

答案 

答案


Java 解决方案

答案 

答案


Python 解决方案

答案 

答案

#Add to the method __AdvanceTimePeriod on the Simulation class between fox loop and add new foxes loop
    for x in range (0, self.__LandscapeSize):
      for y in range (0, self.__LandscapeSize):
        if not self.__Landscape[x][y].Fox is None and self.__Landscape[x][y].Fox.MoveThisPeriod():
            NewX,NewY = self.__FoxMovesToWarran(x,y)
            Fox =  self.__Landscape[x][y].Fox
            self.__Landscape[x][y].Fox = None
            self.__Landscape[NewX][NewY].Fox = Fox
            if self.__ShowDetail:
              if NewX != x or NewY != y:
                print("Fox at (", x, ",", y, "): ", sep = "")
                print("  Fox has moved to (", NewX, ",", NewY, ")")
#Add to the class Simulation
  def __FoxMovesToWarran(self,FoxX,FoxY):
    Warrens = []
    NewFoxLocation = [FoxX,FoxY]
    for WarrenX in range(0, self.__LandscapeSize):
      for WarrenY in range (0, self.__LandscapeSize):
        if not self.__Landscape[WarrenX][WarrenY].Warren is None:
          Dist = self.__DistanceBetween(FoxX, FoxY, WarrenX, WarrenY)
          Warrens.append({
            "X":WarrenX,
            "Y":WarrenY,
            "Dist":Dist
          })
    ClosestWarren = sorted(Warrens, key=lambda Warren: Warren["Dist"])[0]
    if ClosestWarren["X"] > FoxX and self.__Landscape[FoxX+1][FoxY].Fox == None and self.__Landscape[FoxX+1][FoxY].Warren == None:
      NewFoxLocation[0] +=1
    elif ClosestWarren["X"] < FoxX and self.__Landscape[FoxX-1][FoxY].Fox == None and self.__Landscape[FoxX-1][FoxY].Warren == None:
      NewFoxLocation[0] -=1
    if ClosestWarren["Y"] > FoxY+1 and self.__Landscape[FoxX][FoxY+1].Fox == None and self.__Landscape[FoxX][FoxY+1].Warren == None:
      NewFoxLocation[1] +=1
    elif ClosestWarren["Y"] < FoxY-1 and self.__Landscape[FoxX][FoxY-1].Fox == None and self.__Landscape[FoxX][FoxY-1].Warren == None:
      NewFoxLocation[1] -=1
    return NewFoxLocation[0],NewFoxLocation[1]
#add to the class Fox
  def MoveThisPeriod(self): 
    MOVE_PROBABILITY  = 0.5
    if random.randint(0, 100) < MOVE_PROBABILITY * 100:
      return True
    else:
      return False
#Max @ The Manchester College


VB.NET 解决方案

答案 

答案

'Extension to the answer 2 code in the below problem
'View that problem first to get all of the code to make this work

                            If Landscape(x, y).Fox.moveforfood() = True Then 'Calls on an extension of the fox class
                                Dim x2, y2 As Integer
                                Dim choice As Integer = Rnd.Next(1, 5) 'This is changed from 4 to 5
                                Dim move As Boolean = False

                                Dim closestX, closestY As Integer 'These 2 variables are added to aid the extension
                                Dim closestwarren As Boolean = False

                                Do

                                    If choice = 1 Then 'North
                                        x2 = x
                                        y2 = y - 1
                                    ElseIf choice = 2 Then 'East
                                        x2 = x + 1
                                        y2 = y
                                    ElseIf choice = 3 Then 'South
                                        x2 = x
                                        y2 = y + 1
                                    ElseIf choice = 4 Then 'West
                                        x2 = x - 1
                                        y2 = y

                                        'An additional choice has been added
                                    ElseIf choice = 5 Then
                                        closestX = closestwarrenX(x, y) 'This calls upon the functions that find the coordinates of the closest warren to the fox
                                        closestY = closestwarrenY(x, y)
                                        'once found the fox is moved closer to the warren by comparing the warren x and fox x to see how the foxes needs to be changed
                                        If closestX > x Then
                                            x2 = x + 1
                                        ElseIf closestX < x Then
                                            x2 = x - 1
                                        ElseIf closestX = x Then
                                            x2 = x
                                        End If
                                        'The same is the carried out for the y coordinates
                                        If closestY > y Then
                                            y2 = y + 1
                                        ElseIf closestY < y Then
                                            y2 = y - 1
                                        ElseIf closestY = y Then
                                            y2 = y
                                        End If
                                        'This boolean statement is in place to show additional detail if show detail is selected
                                        closestwarren = True
                                    End If
                                    If x2 > LandscapeSize Or y2 > LandscapeSize Then
                                        move = False
                                    Else
                                        If Landscape(x2, y2).Fox Is Nothing Then
                                            Landscape(x2, y2).Fox = Landscape(x, y).Fox
                                            Landscape(x, y).Fox = Nothing
                                            If ShowDetail = True Then
                                                If closestwarren = False Then
                                                    Console.WriteLine("Fox moved from (" & x & "," & y & ") to (" & x2 & "," & y2 & ") due to a lack of food")
                                                Else
                                                    'This is a unique message for if the fox is moving closer to a warren
                                                    Console.WriteLine("Fox moved closer to the warren at (" & closestX & "," & closestY & ") from (" & x & "," & y & ") to (" & x2 & "," & y2 & ")")
                                                    closestwarren = False
                                                End If
                                            End If
                                            move = True
                                        Else
                                            move = False
                                        End If
                                    End If
                                Loop Until move = True

                                Landscape(x2, y2).Fox.ResetFoodConsumed()
                            Else
                                Landscape(x, y).Fox.ResetFoodConsumed()
                            End If
'Create these 2 functions in the simulation class
   Private Function closestwarrenX(ByRef foxx As Integer, ByRef foxy As Integer)
            Dim distance As Double = 0
            Dim distance2 As Double
            Dim warrenX As Integer

            For X = 0 To LandscapeSize - 1
                For Y = 0 To LandscapeSize - 1
                    If Not Landscape(X, Y).Warren Is Nothing Then
                        If distance = 0 Then
                            distance = DistanceBetween(foxx, foxy, X, Y)
                            warrenX = X

                        Else
                            distance2 = DistanceBetween(foxx, foxy, X, Y)
                            If distance2 < distance Then
                                distance = distance2
                                warrenX = X
                            End If
                        End If
                    End If
                Next
            Next
            Return warrenX
        End Function
        Private Function closestwarrenY(ByRef foxx As Integer, ByRef foxy As Integer)
            Dim distance As Double = 0
            Dim distance2 As Double
            Dim warrenY As Integer

            For X = 0 To LandscapeSize - 1
                For Y = 0 To LandscapeSize - 1
                    If Not Landscape(X, Y).Warren Is Nothing Then
                        If distance = 0 Then
                            distance = DistanceBetween(foxx, foxy, X, Y)
                            warrenY = Y
                        Else
                            distance2 = DistanceBetween(foxx, foxy, X, Y)
                            If distance2 < distance Then
                                distance = distance2
                                warrenY = Y
                            End If
                        End If
                    End If
                Next
            Next
            Return warrenY
        End Function
'J.M, Year 13 student


如果狐狸没有吃够那一次的食物,它就会随机方向移动

[edit | edit source]

(可以扩展到像上一个问题一样向最近的兔子洞移动)

C# 解决方案

答案 

答案

//In the simulation class:

private void AdvanceTimePeriod()
        {
            int NewFoxCount = 0;
            if (ShowDetail)
            {
                Console.WriteLine();
            }
            for (int x = 0; x < LandscapeSize; x++)
            {
                for (int y = 0; y < LandscapeSize; y++)
                {
                    if (Landscape[x, y].Warren != null)
                    {
                        if (ShowDetail)
                        {
                            Console.WriteLine("Warren at (" + x + "," + y + "):");
                            Console.Write("  Period Start: ");
                            Landscape[x, y].Warren.Inspect();
                        }
                        if (FoxCount > 0)
                        {
                            FoxesEatRabbitsInWarren(x, y);
                        }
                        if (Landscape[x, y].Warren.NeedToCreateNewWarren())
                        {
                            CreateNewWarren();
                        }
                        Landscape[x, y].Warren.AdvanceGeneration(ShowDetail);
                        if (ShowDetail)
                        {
                            Console.Write("  Period End: ");
                            Landscape[x, y].Warren.Inspect();
                            Console.ReadKey();
                        }
                        if (Landscape[x, y].Warren.WarrenHasDiedOut())
                        {
                            Landscape[x, y].Warren = null;
                            WarrenCount--;
                        }
                    }
                }
            }
            for (int x = 0; x < LandscapeSize; x++)
            {
                for (int y = 0; y < LandscapeSize; y++)
                {
                    if (Landscape[x, y].Fox != null)    
                    {
                        if (ShowDetail)
                        {
                            Console.WriteLine("Fox at (" + x + "," + y + "): ");
                        }
                        Landscape[x, y].Fox.AdvanceGeneration(ShowDetail);
                        if (Landscape[x, y].Fox.CheckIfDead())
                        {
                            Landscape[x, y].Fox = null;
                            FoxCount--;
                        }
                        else
                        {
                            if (Landscape[x, y].Fox.ReproduceThisPeriod())
                            {
                                if (ShowDetail)
                                {
                                    Console.WriteLine("  Fox has reproduced. ");
                                }
                                NewFoxCount++;
                            }
                            if (ShowDetail)
                            {
                                Landscape[x, y].Fox.Inspect();
                            }

                            //Edit: removed ==true 
                            if (Landscape[x, y].Fox.MoveFox()) //Move Fox ------------------------------
                            {
                                int x2;
                                int y2;
                                do
                                {
                                    x2 = Rnd.Next(0, 14);   //Creates a new random number < 14
                                    y2 = Rnd.Next(0, 14);   //Creates a new random number < 14
                                    
                                } //Edit: moved code out of Do loop so if we get a null point twice,we don't attempt to move a null object, also properly checks for empty spot
                                while(Landscape[x2, y2].Warren != null && Landscape[x2, y2].Fox != null);  //Makes sure the new location is empty
                                Landscape[x, y].Fox.ResetFoodConsumed();
                                Landscape[x2, y2].Fox = Landscape[x, y].Fox;    //Clones the old fox into the new location
                                Landscape[x, y].Fox = null;     //Removes the old fox
                                // Edit: only shows detail if asked for
                                if (ShowDetail){
                                Console.WriteLine(" Fox moves to ({0},{1}) due to lack of food.", x2, y2);
                            }
                            }
                            // Edit: Removed need for else 
                        }
                    }
                }
            }
            if (NewFoxCount > 0)
            {
                if (ShowDetail)
                {
                    Console.WriteLine("New foxes born: ");
                }
                for (int f = 0; f < NewFoxCount; f++)
                {
                    CreateNewFox();
                }
            }
            if (ShowDetail)
            {
                Console.ReadKey();
            }
            DrawLandscape();
            Console.WriteLine();
        }

//In the Fox : Animal class:
public bool MoveFox()//Move Fox ------------------------------------------------------------------------------
        {
            //Edit: Removed need for "move" boolean var
            if (FoodUnitsConsumedThisPeriod < FoodUnitsNeeded)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

// Will Anderson, The Harvey Grammar School
// Edited by JW, The Harvey Grammar School


Delphi/Pascal 解决方案

答案 

答案


Java 解决方案

答案 

答案


Python 解决方案

答案 

答案

  1. 在 ADVANCEPERIOD 中

如果 self.__Landscape[x][y].Fox 不为空

           if self.__Landscape[x][y].Fox.GetEatenEnoughFood() is False:
             OldXL = x-1
             OldXU = x+1
             OldYL = y-1
             OldYU = y+1
             if x == 0:
               OldXL = 0
             elif x == self.__LandscapeSize - 1:
               OldXU = self.__LandscapeSize - 1
             if y == 0:
               OldYL = 0
             elif y == self.__LandscapeSize - 1:
               OldYU = self.__LandscapeSize - 1
             NewX = random.randint(OldXL, OldXU)
             NewY = random.randint(OldYL, OldYU)
             while not self.__Landscape[NewX][NewY].Fox is None:
               NewX = random.randint(OldXL, OldXU)
               NewY = random.randint(OldYL, OldYU)
             self.__Landscape[NewX][NewY].Fox = self.__Landscape[x][y].Fox
             self.__Landscape[x][y].Fox = None
             print("(",x,",",y,") has moved to (",NewX,",",NewY,")",sep="")
  1. 在 FOX 类中

def __init__(self, Variability)

   self.__DEFAULT_LIFE_SPAN = 7
   self.__DEFAULT_PROBABILITY_DEATH_OTHER_CAUSES = 0.1
   super(Fox, self).__init__(self.__DEFAULT_LIFE_SPAN, self.__DEFAULT_PROBABILITY_DEATH_OTHER_CAUSES, Variability)
   self.__FoodUnitsNeeded = int(10 * self._CalculateRandomValue(100, Variability) / 100)
   self.__FoodUnitsConsumedThisPeriod  = 0
   self.__EatenEnoughFood = True
 def AdvanceGeneration(self, ShowDetail):
   self.__EatenEnoughFood = True
   if self.__FoodUnitsConsumedThisPeriod == 0:
     self._IsAlive = False
     if ShowDetail:
       print("  Fox dies as has eaten no food this period.")
   else:
     if self.CheckIfKilledByOtherFactor():
       self._IsAlive = False
       if ShowDetail:
         print("  Fox killed by other factor.")
     else:
       if self.__FoodUnitsConsumedThisPeriod < self.__FoodUnitsNeeded:
         self.CalculateNewAge()
         self.__EatenEnoughFood = False
         if ShowDetail:
           print("  Fox ages further due to lack of food.")
       self.CalculateNewAge()
       if not self._IsAlive:
         if ShowDetail:
           print("  Fox has died of old age.")
 def GetEatenEnoughFood(self):
返回 self.__EatenEnoughFood


VB.NET 解决方案

答案 

答案


答案 2

答案

Private Sub AdvanceTimePeriod()
            Dim NewFoxCount As Integer = 0
            If ShowDetail Then
                Console.WriteLine()
            End If
            For x = 0 To LandscapeSize - 1
                For y = 0 To LandscapeSize - 1
                    If Not Landscape(x, y).Warren Is Nothing Then
                        If ShowDetail Then
                            Console.WriteLine("Warren at (" & x & "," & y & "):")
                            Console.Write("  Period Start: ")
                            Landscape(x, y).Warren.Inspect()
                        End If
                        If FoxCount > 0 Then
                            FoxesEatRabbitsInWarren(x, y)
                        End If
                        If Landscape(x, y).Warren.NeedToCreateNewWarren() Then
                            CreateNewWarren()
                        End If
                        Landscape(x, y).Warren.AdvanceGeneration(ShowDetail)
                        If ShowDetail Then
                            Console.Write("  Period End: ")
                            Landscape(x, y).Warren.Inspect()
                            Console.ReadKey()
                        End If
                        If Landscape(x, y).Warren.WarrenHasDiedOut() Then
                            Landscape(x, y).Warren = Nothing
                            WarrenCount -= 1
                        End If
                    End If
                Next
            Next
            For x = 0 To LandscapeSize - 1
                For y = 0 To LandscapeSize - 1
                    If Not Landscape(x, y).Fox Is Nothing Then
                        If ShowDetail Then
                            Console.WriteLine("Fox at (" & x & "," & y & "): ")
                        End If
                        Landscape(x, y).Fox.AdvanceGeneration(ShowDetail)
                        If Landscape(x, y).Fox.CheckIfDead() Then
                            Landscape(x, y).Fox = Nothing
                            FoxCount -= 1
                        Else
                            If Landscape(x, y).Fox.ReproduceThisPeriod() Then
                                If ShowDetail Then
                                    Console.WriteLine("  Fox has reproduced. ")
                                End If
                                NewFoxCount += 1
                            End If
                            If ShowDetail Then
                                Landscape(x, y).Fox.Inspect()
                            End If

                            If Landscape(x, y).Fox.moveforfood() = True Then 'Calls on an extension of the fox class
                                Dim x2, y2 As Integer
                                Dim choice As Integer = Rnd.Next(1, 4)
                                Dim move As Boolean = False

                                Do 'This loop wil run until a valid move has been processed

                                   
                                    'Can be extended to allow for varying move distances, e.g. those who have eaten a certain amount of food can move 2 space
                                    If choice = 1 Then 'North
                                        x2 = x
                                        y2 = y - 1
                                    ElseIf choice = 2 Then 'East
                                        x2 = x + 1
                                        y2 = y
                                    ElseIf choice = 3 Then 'South
                                        x2 = x
                                        y2 = y + 1
                                    ElseIf choice = 4 Then 'West
                                        x2 = x - 1
                                        y2 = y
                                    End If

                                    If x2 > LandscapeSize Or y2 > LandscapeSize Then 'This makes sure that the new coordinates do not go off of the grid
                                        move = False
                                    Else
                                        If Landscape(x2, y2).Fox Is Nothing Then 'This statement checks to see if there is already a fox in the new position
                                            Landscape(x2, y2).Fox = Landscape(x, y).Fox 'Moves the data of the fox being moved to the new coordinate
                                            Landscape(x, y).Fox = Nothing 'Sets the old position of the fox to nothing
                                            If ShowDetail = True Then
                                                Console.WriteLine("Fox moved from " & x & "," & y & " to " & x2 & "," & y2 & " due to a lack of food")
                                            End If
                                            move = True
                                        Else
                                            move = False
                                        End If
                                    End If
                                Loop Until move = True

                                Landscape(x2, y2).Fox.ResetFoodConsumed()
                            Else
                                Landscape(x, y).Fox.ResetFoodConsumed()
                            End If

                        End If
                    End If
                Next
            Next
            If NewFoxCount > 0 Then
                If ShowDetail Then
                    Console.WriteLine("New foxes born: ")
                End If
                For f = 0 To NewFoxCount - 1
                    CreateNewFox()
                Next
            End If
            If ShowDetail Then
                Console.ReadKey()
            End If
            DrawLandscape()
            Console.WriteLine()
        End Sub

'Addition to the fox class
        Public Function moveforfood() As Boolean
            'This determines whether or not the fox is able to move/ needs to move
            If FoodUnitsConsumedThisPeriod < FoodUnitsNeeded Then
                Return True
            Else
                Return False
            End If
        End Function
'J.M, Year 13 student


如果狐狸移动,下一时间段所需的的食物量应该与其移动的距离成正比增加

[edit | edit source]

C# 解决方案

答案 

答案


Delphi/Pascal 解决方案

答案 

答案


Java 解决方案

答案 

答案


Python 解决方案

答案 

答案


VB.NET 解决方案

答案 

答案


动物除了食物还需要水才能生存

[edit | edit source]

C# 解决方案

答案 

答案


Delphi/Pascal 解决方案

答案 

答案


Java 解决方案

答案 

答案

class Fox extends Animal {
	private int FoodUnitsNeeded = 10;
	private int WaterNeeded = 10; //add new variable for water that is needed
	private int FoodUnitsConsumedThisPeriod = 0;
	private int WaterConsumedThisPeriod = 0; //add new variable for water consumed this period
	private static final int DefaultLifespan = 7;
	private static final double DefaultProbabilityDeathOtherCauses = 0.1;
	private int FoxCount = 0;
	private Fox[] Foxes;
	 double ReproductionProbability;
	

	public Fox(int Variability) {

		super(DefaultLifespan, DefaultProbabilityDeathOtherCauses, Variability);
		FoodUnitsNeeded = (int) (10 * this.CalculateRandomValue(100, Variability) / 100);
	}

	public int GetFoxCount() {

		return FoxCount;
	}

	public void AdvanceGeneration(Boolean ShowDetail) {
		if (FoodUnitsConsumedThisPeriod == 0 || WaterConsumedThisPeriod == 0) { // test if water consumed this period is also 0
			IsAlive = false;
			if (ShowDetail) {
				Console.println("  Fox dies as has eaten no food or drank no water this period."); //change this message to fit water also
			}
		} else {
			if (CheckIfKilledByOtherFactor()) {
				IsAlive = false;
				if (ShowDetail) {
					Console.println("  Fox killed by other factor.");
				}
			} else {
				if (FoodUnitsConsumedThisPeriod < FoodUnitsNeeded || WaterConsumedThisPeriod < WaterNeeded) { //test if water consumed this period is also less than the water need
					CalculateNewAge();
					if (ShowDetail) {
						Console.println("  Fox ages further due to lack of food or water."); //change this message to fit water also
					}
				}
				
				CalculateNewAge();
				if (!IsAlive) {
					if (ShowDetail) {
						Console.println("  Fox has died of old age.");
					}
				}
			}
		}
	}

	public void ResetFoodAndWaterConsumed() { //change name of class to include water (change name also in advanceTimePeriod)
		FoodUnitsConsumedThisPeriod = 0;
		WaterConsumedThisPeriod = 0; //reset water consumed to 0
	}

	public Boolean ReproduceThisPeriod() {
	  ReproductionProbability = 0.25;
		if (Rnd.nextInt(100) < ReproductionProbability * 100) {
			return true;
		} else {
			return false;
		}
	}

	public void GiveFoodAndWater(int FoodUnits, int WaterUnits) {
		FoodUnitsConsumedThisPeriod = FoodUnitsConsumedThisPeriod + FoodUnits;
		WaterConsumedThisPeriod = WaterConsumedThisPeriod + WaterUnits; // add water units to water units consumed this period
		
	
	}
}

	//Nathan Balfour, Thomas Alleyne Academy


Python 解决方案

答案 

答案


VB.NET 解决方案

答案 

答案


如果狐狸吃掉了比它需要更多的食物,它的繁殖率就会提高

[edit | edit source]

(可以扩展到降低移动的几率/移动范围)

C# 解决方案

答案 

答案

class Fox : Animal
    {
        double ReproductionProbability = 0.25;              // Declare at the start
        private double FoodUnitsNeeded = 10;                // Change to a double
        private double FoodUnitsConsumedThisPeriod = 0;     // Change to a double
        private const int DefaultLifespan = 7;
        private const double DefaultProbabilityDeathOtherCauses = 0.1;

// In the "public bool ReproduceThisPeriod() method
public bool ReproduceThisPeriod()
        {
            if (FoodUnitsConsumedThisPeriod > FoodUnitsNeeded)  // Compares the food units eaten this period with the food units needed
            {

                double increase = FoodUnitsConsumedThisPeriod / FoodUnitsNeeded;   // Create a new double variable called increase

                if (ReproductionProbability > 0.25)
                {
                    ReproductionProbability = 0.25;   // Resets the foxes ReproductionProbability to 0.25 at the start
                }
                ReproductionProbability = ReproductionProbability * increase; // Times increase by ReproductionProbability to get a new ReproductionProbability
                Console.WriteLine("the reproduction probability is  " + ReproductionProbability);
                
            }

// Adam Williams, The Harvey Grammar School


Delphi/Pascal 解决方案

答案 

答案


Java 解决方案

答案 

答案

public void GiveFood(int FoodUnits, double ReproductionProbability) {
		FoodUnitsConsumedThisPeriod = FoodUnitsConsumedThisPeriod + FoodUnits;
		
		if(FoodUnitsConsumedThisPeriod > FoodUnitsNeeded){
			ReproductionProbability = 0.5;
		}
	}

	//Nathan Balfour, Thomas Alleyne Academy


Python 解决方案

答案 

答案

def AdvanceGeneration(self, ShowDetail):
    if self.__FoodUnitsConsumedThisPeriod == 0:
      self._IsAlive = False
      if ShowDetail:
        print("  Fox dies as has eaten no food this period.")
    else:
      if self.CheckIfKilledByOtherFactor():
        self._IsAlive = False
        if ShowDetail:
          print("  Fox killed by other factor.")
      else:
        if self.__FoodUnitsConsumedThisPeriod < self.__FoodUnitsNeeded:
          self.CalculateNewAge()
          if ShowDetail:
            print("  Fox ages further due to lack of food.")
        self.CalculateNewAge()
        if self.__FoodUnitsConsumedThisPeriod > self.__FoodUnitsNeeded:
          self.__IncreasedProbability = random.randint(0, self.__FoodUnitsConsumedThisPeriod)/100
        if not self._IsAlive:
          if ShowDetail:
            print("  Fox has died of old age.")

  def ReproduceThisPeriod(self): 
    REPRODUCTION_PROBABILITY  = 0.25
    if random.randint(0, 100) < (REPRODUCTION_PROBABILITY + self.__IncreasedProbability) * 100:
      print()
      return True
    else:
      return False


VB.NET 解决方案

答案 

答案

Class Fox
    Inherits Animal
    'New variable to store the reproduction rate
    Private ReproductionProbability As Double = 0.25

    Public Sub GiveFood(ByVal FoodUnits As Integer)
        FoodUnitsConsumedThisPeriod = FoodUnitsConsumedThisPeriod + FoodUnits
        'increase the reproduction rate by 10% when food consumed is greater than food needed
        If FoodUnitsConsumedThisPeriod > FoodUnitsNeeded Then
            ReproductionProbability *= 1.1
        End If
    End Sub

    Public Function ReproduceThisPeriod() As Boolean
        '-- Line Removed -> Const ReproductionProbability As Double = 0.25
        If Rnd.Next(0, 100) < ReproductionProbability * 100 And Gender = Genders.Female Then
            Return True
        Else
            Return False
        End If
    End Function

End Class

'Mohammad Noyan Choudhury, City University of London


在网格中添加只有特定动物才能生存的地理区域(例如:兔子无法在山区建立兔子洞,狐狸也难以生存,但老鹰可以繁衍生息等)

[edit | edit source]

C# 解决方案

答案 

答案


Delphi/Pascal 解决方案

答案 

答案


Java 解决方案

答案 

答案



Python 解决方案

答案 

答案

Location 类

 def __init__(self):
   self.Fox = None
   self.Warren = None
   self.Mountain = None
  1. 在程序和模拟的主要部分添加相关变量,例如 MountainCount 和 InitialMountainCount。

Simulation 类

 def __init__(self,LandscapeSize, InitialWarrenCount, InitialFoxCount, Variability, FixedInitialLocations,InitialMountainCount):
   self.__ViewRabbits = ""
   self.__TimePeriod = 0
   self.__WarrenCount = 0
   self.__FoxCount = 0
   self.__MountainCount = 0
   self.__ShowDetail = False
   self.__LandscapeSize = LandscapeSize
   self.__Variability = Variability
   self.__FixedInitialLocations = FixedInitialLocations
   self.__Landscape = []

def Main()

 MenuOption = 0
 while MenuOption != 3:
   print("Predator Prey Simulation Main Menu")
   print()
   print("1. Run simulation with default settings")
   print("2. Run simulation with custom settings")
   print("3. Exit")
   print()
   MenuOption = int(input("Select option: "))
   if MenuOption == 1 or MenuOption == 2:
     if MenuOption == 1:
       LandscapeSize = 15
       InitialMountainCount = 1
       InitialWarrenCount = 5
       InitialFoxCount = 5
       Variability = 0
       FixedInitialLocations = True
     else:
       LandscapeSize = int(input("Landscape Size: "))
       InitialWarrenCount = int(input("Initial number of warrens: "))
       InitialFoxCount = int(input("Initial number of foxes: "))
       InitialMountainCount = int(input("Initial number of Mountains: "))
       Variability = int(input("Randomness variability (percent): "))
       FixedInitialLocations = False
     Sim = Simulation(LandscapeSize, InitialWarrenCount, InitialFoxCount, Variability, FixedInitialLocations,InitialMountainCount)
 input()
  1. mountains 类用于提供山的大小,以便在后续添加山时进行检查。

class Mountain()

 def __init__(self):
   self.__MountainList=[]
 def CreateMountain():
   random=random.randint(1,99)
   self.__MountainList.append(random)
  1. 还需要修改绘制地形函数,以便在有山的时候添加一个 M。

def __DrawLandscape(self)

   print()
   print("TIME PERIOD:", self.__TimePeriod)
   print()
   print("   ", end = "")
   for x in range (0, self.__LandscapeSize):
     if x < 10:
       print(" ", end = "")
     print(x, "|", end = "")
   print()
   for x in range (0, self.__LandscapeSize * 4 + 3):
     print("-", end = "")
   print()
   for y in range (0, self.__LandscapeSize):
     if y < 10:
       print(" ", end = "")
     print("", y, "|", sep = "", end = "")
     for x in range (0, self.__LandscapeSize):
       if not self.__Landscape[x][y].Warren is None:
         if self.__Landscape[x][y].Warren.GetRabbitCount() < 10:
           print(" ", end = "")
         print(self.__Landscape[x][y].Warren.GetRabbitCount(), end = "")
       else:
         print("  ", end = "")
       if not self.__Landscape[x][y].Fox is None:
         print("F", end = "")
       if not self.__Landscape[x][y].Mountain is None:
         print("M", end = "")
       else:
         print(" ", end = "")
       print("|", end = "")
     print()
  1. 最后,允许默认和自定义设置中添加山。

def __CreateLandscapeAndAnimals(self, InitialWarrenCount, InitialFoxCount, FixedInitialLocations,InitialMountainCount)

   for x in range (0, self.__LandscapeSize):
     for y in range (0, self.__LandscapeSize):
       self.__Landscape[x][y] = Location()
   if FixedInitialLocations:
     self.__Landscape[1][1].Warren = Warren(self.__Variability, 38)
     self.__Landscape[2][8].Warren = Warren(self.__Variability, 80) 
     self.__Landscape[9][7].Warren = Warren(self.__Variability, 20)
     self.__Landscape[10][3].Warren = Warren(self.__Variability, 52)
     self.__Landscape[13][4].Warren = Warren(self.__Variability, 67)
     self.__WarrenCount = 5
     self.__Landscape[2][10].Fox = Fox(self.__Variability)
     self.__Landscape[6][1].Fox = Fox(self.__Variability)
     self.__Landscape[8][6].Fox = Fox(self.__Variability)
     self.__Landscape[11][13].Fox = Fox(self.__Variability)
     self.__Landscape[12][4].Fox = Fox(self.__Variability)
     self.__FoxCount = 5
     self.__Landscape[2][2].Mountain = Mountain()
     self.__MountainCount = 1
   else:
     for w in range (0, InitialWarrenCount):
       self.__CreateNewWarren()
     for f in range (0, InitialFoxCount):
       self.__CreateNewFox()
     for m in range (0, InitialMountainCount):
       self.__CreateNewMountain()

def __CreateNewMountain(self)

   x = random.randint(0, self.__LandscapeSize - 1)
   y = random.randint(0, self.__LandscapeSize - 1)
   while not self.__Landscape[x][y].Mountain is None:
     x = random.randint(0, self.__LandscapeSize - 1)
     y = random.randint(0, self.__LandscapeSize - 1)
   if self.__ShowDetail:
     print("  You have discovered a Mountain  at (", x, ",", y, ")", sep = "")
   self.__Landscape[x][y].Mountain = Mountain()
   self.__MountainCount += 1
  1. 为了防止兔子洞出现在山附近,请在 CreateNewWarren 函数中添加以下代码
def __CreateNewWarren(self):
   x = random.randint(0, self.__LandscapeSize - 1)
   y = random.randint(0, self.__LandscapeSize - 1)
   while not self.__Landscape[x][y].Warren is None and not self.__Landscape[x][y].Mountain is None:
     x = random.randint(0, self.__LandscapeSize - 1)
     y = random.randint(0, self.__LandscapeSize - 1)
   if self.__ShowDetail:
     print("New Warren at (", x, ",", y, ")", sep = "")
   self.__Landscape[x][y].Warren = Warren(self.__Variability)
   self.__WarrenCount += 1

Charles Naden-Lamb Fallibroome Academy


VB.NET 解决方案

答案 

答案


如果已经添加了其他动物(例如老鹰),让它们更倾向于在新增的地理区域附近狩猎。(上述内容的扩展)。

[edit | edit source]

C# 解决方案

答案 

答案


Delphi/Pascal 解决方案

答案 

答案


Java 解决方案

答案 

答案


Python 解决方案

答案 

答案


VB.NET 解决方案

答案 

答案


为了繁殖,必须要有两个或两个以上同种动物在相邻的格子中。

[edit | edit source]

C# 解决方案

答案 

答案


Delphi/Pascal 解决方案

答案 

答案


Java 解决方案

答案 

答案


Python 解决方案

答案 

答案


VB.NET 解决方案

答案 

答案


(扩展) 让所有动物能够建立自己的家(例如狐狸的洞穴或老鹰的巢穴)。

[edit | edit source]

C# 解决方案

答案 

答案


Delphi/Pascal 解决方案

答案 

答案


Java 解决方案

答案 

答案


Python 解决方案

答案 

答案


VB.NET 解决方案

答案 

答案


为兔子添加食物来源(例如草)。

[edit | edit source]

C# 解决方案

答案 

答案


Delphi/Pascal 解决方案

答案 

答案


Java 解决方案

答案 

答案


Python 解决方案

答案 

答案


VB.NET 解决方案

答案 

答案


(扩展) 流星,以较低的随机概率出现,并摧毁兔子洞和狐狸(单独的类)。

[edit | edit source]

C# 解决方案

答案 

答案

// add a bool called MeteorCanSpawn in the simulation class
	
// this method does not create a new class but edits the advancetimeperiod subroutine and creates a new one instead which is quicker
	
	
private void AdvanceTimePeriod()
	
        {
	
            int meteorSpawnProability = Rnd.Next(1, 1000);
	
	
            if (meteorSpawnProability > 900 && meteorSpawnProability < 950)
	
            {
	
                int speed = Rnd.Next(75000, 500000);
	
                int size = Rnd.Next(1, 50);
	
	
                if (speed > 10000 && size > LandscapeSize)
	
                {
	
                    MeteorCanSpawn = true;
	
                }
	
            }
	
	
            int NewFoxCount = 0;
	
            if (ShowDetail)
	
            {
	
                Console.WriteLine();
	
            }
	
            for (int x = 0; x < LandscapeSize; x++)
	
            {
	
                for (int y = 0; y < LandscapeSize; y++)
	
                {
	
                    if (Landscape[x, y].Warren != null)
	
                    {
	
                        if (ShowDetail)
	
                        {
	
                            Console.WriteLine("Warren at (" + x + "," + y + "):");
	
                            Console.Write("  Period Start: ");
	
                            Landscape[x, y].Warren.Inspect();
	
                        }
	
                        if (FoxCount > 0)
	
                        {
	
                            FoxesEatRabbitsInWarren(x, y);
	
                        }
	
                        if (Landscape[x, y].Warren.NeedToCreateNewWarren())
	
                        {
	
                            CreateNewWarren();
	
                        }
	
                        Landscape[x, y].Warren.AdvanceGeneration(ShowDetail);
	
                        if (ShowDetail)
	
                        {
	
                            Console.Write("  Period End: ");
	
                            Landscape[x, y].Warren.Inspect();
	
                            Console.ReadKey();
	
                        }
	
                        if (Landscape[x, y].Warren.WarrenHasDiedOut())
	
                        {
	
                            Landscape[x, y].Warren = null;
	
                            WarrenCount--;
	
                        }
	
                    }
	
                }
	
            }
	
            for (int x = 0; x < LandscapeSize; x++)
	
            {
	
                for (int y = 0; y < LandscapeSize; y++)
	
                {
	
                    if (Landscape[x, y].Fox != null)
	
                    {
	
                        if (ShowDetail)
	
                        {
	
                            Console.WriteLine("Fox at (" + x + "," + y + "): ");
	
                        }
	
                        Landscape[x, y].Fox.AdvanceGeneration(ShowDetail);
	
                        if (Landscape[x, y].Fox.CheckIfDead())
	
                        {
	
                            Landscape[x, y].Fox = null;
	
                            FoxCount--;
	
                        }
	
                        else
	
                        {
	
                            if (Landscape[x, y].Fox.ReproduceThisPeriod())
	
                            {
	
                                if (ShowDetail)
	
                                {
	
                                    Console.WriteLine("  Fox has reproduced. ");
	
                                }
	
                                NewFoxCount++;
	
                            }
	
                            if (ShowDetail)
	
                            {
	
                                Landscape[x, y].Fox.Inspect();
	
                            }
	
                            Landscape[x, y].Fox.ResetFoodConsumed();
	
                        }
	
                    }
	
                }
	
            }
	
            if (NewFoxCount > 0)
	
            {
	
                if (ShowDetail)
	
                {
	
                    Console.WriteLine("New foxes born: ");
	
                }
	
                for (int f = 0; f < NewFoxCount; f++)
	
                {
	
                    CreateNewFox();
	
                }
	
            }
	
            if (ShowDetail)
	
            {
	
                Console.ReadKey();
	
            }
	
	
            if (MeteorCanSpawn)
	
            {
	
                Console.WriteLine("A meteor has been sighted and will make impact");
	
                int currentFoxes = FoxCount;
	
                int currentWarrens = WarrenCount;
	
                int rabbits = 0;
	
	
                for (int x = 0; x < LandscapeSize; x++)
	
                {
	
                    for (int y = 0; y < LandscapeSize; y++)
	
                    {
	
                        if (Landscape[x,y].Fox != null)
	
                        {
	
                            Landscape[x, y].Fox = null;
	
                        }
	
                    }
	
                }
	
	
                for (int x = 0; x < LandscapeSize; x++)
	
                {
	
                    for (int y = 0; y < LandscapeSize; y++)
	
                    {
	
                        if (Landscape[x, y].Warren != null)
	
                        {
	
                            rabbits = Landscape[x, y].Warren.GetRabbitCount();
	
                            Landscape[x, y].Warren = null;
	
                        }
	
                    }
	
                }
	
                TimePeriod = 0;
	
                MeteorResult(currentFoxes, currentWarrens, rabbits);
	
	
            } else
	
            {
	
                Console.WriteLine("A meteor has been sighted however will not be making impact");
	
                DrawLandscape();
	
            }
	
            Console.WriteLine();
	
        }
	
	
        private void MeteorResult(int fox, int warren, int rabbits)
	
        {
	
            Console.WriteLine("As a result of the meteor, a total of " + fox + " foxes were killed, around " + warren + " warrens were destroyed which killed upto " + rabbits + " rabbits");
	
            Console.WriteLine("The simulation is over");
	
            Console.ReadKey();
	
        }


Delphi/Pascal 解决方案

答案 

答案


Java 解决方案

答案 

答案

'''Installation : Past this method in the Simulation Class'''

private void BridgeMeteor() {
    Landscape = new Meteor().SpawnMeteor(Landscape, LandscapeSize, ShowDetail);
}

'''Installation : Call the Method in AdvancedTimePeriod() just before DrawLandscape()
Installation : Now paste the Meteor Class in the very bottom of the code'''

class Meteor {
    
    // Created By Jonny Dyer (Reigate College)
    
    public double SpawnVariability;
    
    public Meteor() {
        SpawnVariability = 0.0125;
    }
    
    public Location[][] SpawnMeteor(Location[][] Landscape, int LandscapeSize, boolean ShowDetail) {
        if (AllowSpawn(SpawnVariability)) {
            int CenterX = new Random().nextInt(LandscapeSize);
            int CenterY = new Random().nextInt(LandscapeSize);
            Landscape[CenterX][CenterY].Meteor = new Meteor();
            if (ShowDetail) {
                Console.println("Meteor Crashed (" + CenterX + "," + CenterY + ")");
            }
            if (CenterX + 1 < LandscapeSize) {
                Landscape[CenterX+1][CenterY].Meteor = new Meteor();
            }
            if (CenterX - 1 >= 0) {
                Landscape[CenterX-1][CenterY].Meteor = new Meteor();
            }
            if (CenterY + 1 < LandscapeSize) {
                Landscape[CenterX][CenterY+1].Meteor = new Meteor();
            }
            if (CenterY - 1 >= 0) {
                Landscape[CenterX][CenterY-1].Meteor = new Meteor();
            }
        }
        Landscape = KillAnimals(Landscape, LandscapeSize);
        return Landscape;
    }
    
    public boolean AllowSpawn(double Variability) {
        if (new Random().nextDouble() <= Variability) {
            return true;
        }
        return false;
    }
    
    public Location[][] KillAnimals(Location[][] Landscape, int LandscapeSize) {
        for (int x=0; x<LandscapeSize; x++) {
            for (int y=0; y<LandscapeSize; y++) {
                if (Landscape[x][y].Meteor != null && Landscape[x][y].Warren != null) {
                    Landscape[x][y].Warren = null;
                }
                if (Landscape[x][y].Meteor != null && Landscape[x][y].Fox != null) {
                    Landscape[x][y].Fox = null;
                }
            }
        }
        return Landscape;
    }
    
}


Python 解决方案

答案 

答案

#The question itself wasn't entirely clear on specifics such as how large the area of effect should be but as a default you can see in my Meteor class #that the strike radius of sorts is 3.
#Below are all of the classes that were changed in order to implement the Meteor feature, along with comments giving brief descriptions on the purpose #of each change.

class Location:
  def __init__(self):
    self.Fox = None
    self.Warren = None
    self.Meteor = None #Sets default, necessary for all objects.

def __AdvanceTimePeriod(self):
  NewFoxCount = 0
  if self.__ShowDetail:
    print()
  for x in range (0, self.__LandscapeSize):
    for y in range (0, self.__LandscapeSize):
      if not self.__Landscape[x][y].Warren is None:
        if self.__ShowDetail:
          print("Warren at (", x, ",", y, "):", sep = "")
          print("  Period Start: ", end = "")
          self.__Landscape[x][y].Warren.Inspect()
        if self.__FoxCount > 0:
          self.__FoxesEatRabbitsInWarren(x, y)
        if self.__Landscape[x][y].Warren.NeedToCreateNewWarren():
          self.__CreateNewWarren()
        self.__Landscape[x][y].Warren.AdvanceGeneration(self.__ShowDetail)
        if self.__ShowDetail:
          print("  Period End: ", end = "")
          self.__Landscape[x][y].Warren.Inspect()
          input()
        if self.__Landscape[x][y].Warren.WarrenHasDiedOut():
          self.__Landscape[x][y].Warren = None
          self.__WarrenCount -= 1
  for x in range (0, self.__LandscapeSize):
    for y in range (0, self.__LandscapeSize):
      if not self.__Landscape[x][y].Fox is None:
        if self.__ShowDetail:
          print("Fox at (", x, ",", y, "): ", sep = "")
        self.__Landscape[x][y].Fox.AdvanceGeneration(self.__ShowDetail)
        if self.__Landscape[x][y].Fox.CheckIfDead():
          self.__Landscape[x][y].Fox = None
          self.__FoxCount -= 1
        else:
          if self.__Landscape[x][y].Fox.ReproduceThisPeriod():
            if self.__ShowDetail:
              print("  Fox has reproduced. ")
            NewFoxCount += 1
          if self.__ShowDetail:
            self.__Landscape[x][y].Fox.Inspect()
          self.__Landscape[x][y].Fox.ResetFoodConsumed()
  if NewFoxCount > 0:
    if self.__ShowDetail:
      print("New foxes born: ")
    for f in range (0, NewFoxCount):
      self.__CreateNewFox()
  if self.__ShowDetail:
    input()
  meteorValue = random.randint(1,20) #Generates random integer between 1 and 20, giving a 1 in 20 chance each time, of a Meteor spawning.
  if meteorValue == 1:
    xCoOrd = random.randint(0,14)
    yCoOrd = random.randint(0,14) #Picks random coordinates which will be where the Meteor spawns, and will be the centre for the area of effect.
    self.__Landscape[xCoOrd][yCoOrd].Meteor = Meteor(self.__Variability, xCoOrd, yCoOrd, self.__Landscape, self.__FoxCount, self.__WarrenCount)
    self.__Landscape = self.__Landscape[xCoOrd][yCoOrd].Meteor.Strike() #Calls the strike function of the Meteor class.
  self.__DrawLandscape()
  print()

def __DrawLandscape(self):
  print()
  print("TIME PERIOD:", self.__TimePeriod)
  print()
  print("   ", end = "")
  for x in range (0, self.__LandscapeSize):
    if x < 10:
      print(" ", end = "")
    print(x, "|", end = "")
  print()
  for x in range (0, self.__LandscapeSize * 4 + 3):
    print("-", end = "")
  print()
  for y in range (0, self.__LandscapeSize):
    if y < 10:
      print(" ", end = "")
    print("", y, "|", sep = "", end = "")
    for x in range (0, self.__LandscapeSize):
      if not self.__Landscape[x][y].Warren is None:
        if self.__Landscape[x][y].Warren.GetRabbitCount() < 10:
          print(" ", end = "")
        print(self.__Landscape[x][y].Warren.GetRabbitCount(), end = "")
      else:
        print("  ", end = "")
      if not self.__Landscape[x][y].Fox is None:
        print("F", end = "")
      else:
        print(" ", end = "")
      if not self.__Landscape[x][y].Meteor is None:
        print("M", end = "") #Allows placement of the M character, indicating a Meteor strike.
      print("|", end = "")
    print()

class Meteor:
  def __init__(self, Variability, currentX, currentY, landScape, foxCount, warrenCount, strikeRadius = 3):
    self.__strikeRadius = strikeRadius
    self.__currentX = currentX
    self.__currentY = currentY
    self.__landScape = landScape
    self.__foxCount = foxCount
    self.__warrenCount = warrenCount #Receives the randomly generated coordinates and the current landscape array to allow for easy editing.

  def Strike(self):
    self.__startingX = self.__currentX - self.__strikeRadius
    self.__startingY = self.__currentY - self.__strikeRadius #The strike area coordinates need to 'start' at a value "strikeRadius" less than the #current x and y values
    self.__xValues = []
    self.__yValues = []
    for i in range(0,((2*self.__strikeRadius) + 1)): #2* because the area of effect needs to cover both 'sides' of the Meteor placement.
      self.__xValues.append(self.__startingX + i)
      self.__yValues.append(self.__startingY + i)
    for x in self.__xValues:
      for y in self.__yValues: 
        if 0 <= x <= 14 and 0 <= y <= 14: #The values produced by the previous 'for' loop can give coordinates that are outside the board so this #checks the current coordinate is inside the board.
          if not self.__landScape[x][y].Fox is None:
            self.__landScape[x][y].Fox = None #If a fox is in the coordinate, it is removed by setting it to 'None'.
            self.__foxCount -= 1 #Reduce the fox count by 1.
          elif not self.__landScape[x][y].Warren is None:
            self.__landScape[x][y].Warren = None #If a warren is in the coordinate, it is removed by setting it to 'None'.
            self.__warrenCount -= 1 #Reduce the warren count by 1.
    return self.__landScape, self.__foxCount, self.__warrenCount #Return all the variables that were passed to us from the Simulation object, that are #required to continue the game.


VB.NET 解决方案

答案 

答案


提高狐狸在棋盘特定区域死亡的概率

[edit | edit source]

C# 解决方案

答案 

答案


Delphi/Pascal 解决方案

答案 

答案


Java 解决方案

答案 

答案


Python 解决方案

答案 

答案

class Location:
  def __init__(self):
    self.Fox = None
    self.Warren = None
    self.DangerZone = None #Added DangerZone to location

#Creation of class DangerZone
class DangerZone:
  def __init__(self, Variability = random.randint(0, 100)): #If not given randomly calculate the value of Variability
    self.__DeathFactor = Variability

  def DoesKillAnimal(self):
    PosShift = random.randint(0, (100 - self.__DeathFactor)) #Shift the position the bracket being checked for. E.g. 0 - 50 could become 10 - 60 etc.
    Rand = random.randint(0, 100) #Calculate a random number
    IsKilled = Rand in range(PosShift, PosShift+self.__DeathFactor) #If number falls in bracket Fox has been killed.
    return IsKilled

#Modifications to Simulation.__AdvanceTimePeriod()
for x in range (0, self.__LandscapeSize):
      for y in range (0, self.__LandscapeSize):
        if not self.__Landscape[x][y].Fox is None:
          if self.__ShowDetail:
            print("Fox at (", x, ",", y, "): ", sep = "")
          if not self.__Landscape[x][y].DangerZone is None: #Check if the location is a dangerzone as well
            self.__Landscape[x][y].Fox.AdvanceGeneration(self.__ShowDetail, self.__Landscape[x][y].DangerZone.DoesKillAnimal()) #If so check if the dangerzone kills the Fox
          if self.__Landscape[x][y].Fox.CheckIfDead():
            self.__Landscape[x][y].Fox = None
            self.__FoxCount -= 1
          else:
            if self.__Landscape[x][y].Fox.ReproduceThisPeriod():
              if self.__ShowDetail:
                print("  Fox has reproduced. ")
              NewFoxCount += 1
            if self.__ShowDetail:
              self.__Landscape[x][y].Fox.Inspect()
            self.__Landscape[x][y].Fox.ResetFoodConsumed()

#Modifications to Simulation.__CreateLandscapeAndAnimals
  def __CreateLandscapeAndAnimals(self, InitialWarrenCount, InitialFoxCount, FixedInitialLocations):
    for x in range (0, self.__LandscapeSize):
      for y in range (0, self.__LandscapeSize):
        self.__Landscape[x][y] = Location()
    if FixedInitialLocations:
      self.__Landscape[1][1].Warren = Warren(self.__Variability, 38)
      self.__Landscape[2][8].Warren = Warren(self.__Variability, 80)
      self.__Landscape[9][7].Warren = Warren(self.__Variability, 20)
      self.__Landscape[10][3].Warren = Warren(self.__Variability, 52)
      self.__Landscape[13][4].Warren = Warren(self.__Variability, 67)
      self.__WarrenCount = 5
      self.__Landscape[2][10].Fox = Fox(self.__Variability)
      self.__Landscape[6][1].Fox = Fox(self.__Variability)
      self.__Landscape[8][6].Fox = Fox(self.__Variability)
      self.__Landscape[11][13].Fox = Fox(self.__Variability)
      self.__Landscape[12][4].Fox = Fox(self.__Variability)
      self.__FoxCount = 5
    else:
      for w in range (0, InitialWarrenCount):
        self.__CreateNewWarren()
      for f in range (0, InitialFoxCount):
        self.__CreateNewFox()
    DangerX, DangerY = (10,10) #Give coordinates for the centre point of the dangerzone
    for x in range(DangerX - 5, DangerX + 5):
      for y in range(DangerY - 5, DangerY + 5):
        self.__Landscape[x][y].DangerZone = DangerZone()
   #Method could be amended to have user give size and location

#Modifications to the Fox class
class Fox(Animal):
  def __init__(self, Variability):
    self.__DEFAULT_LIFE_SPAN = 7
    self.__DEFAULT_PROBABILITY_DEATH_OTHER_CAUSES = 0.1
    super(Fox, self).__init__(self.__DEFAULT_LIFE_SPAN, self.__DEFAULT_PROBABILITY_DEATH_OTHER_CAUSES, Variability)
    self.__FoodUnitsNeeded = int(10 * self._CalculateRandomValue(100, Variability) / 100)
    self.__FoodUnitsConsumedThisPeriod  = 0
 
  def AdvanceGeneration(self, ShowDetail, DangerKills = False): #If not given assume Fox not killed by dangerzone
    if self.__FoodUnitsConsumedThisPeriod == 0:
      self._IsAlive = False
      if ShowDetail:
        print("  Fox dies as has eaten no food this period.")
    else:
      if self.CheckIfKilledByOtherFactor() or DangerKills: # OR between other reasons and danger zone
        self._IsAlive = False 
        if ShowDetail:
          print("  Fox killed by {}.".format('danger zone' if DangerKills else 'other factors')) #Change statement to give reason for death
      else:
        if self.__FoodUnitsConsumedThisPeriod < self.__FoodUnitsNeeded:
          self.CalculateNewAge()
          if ShowDetail:
            print("  Fox ages further due to lack of food.")
        self.CalculateNewAge()
        if not self._IsAlive:
          if ShowDetail:
            print("  Fox has died of old age.")
# Max Pinfield, Ringwood School


VB.NET 解决方案

答案 

答案


巨人的统治(过于复杂,不太可能实现)

[edit | edit source]

这段代码的灵感来源于电脑生存游戏“饥荒”。它对代码进行了许多改进和补充,其中一些已经在上文中完成了。但主要的功能是将模拟变成游戏,允许用户在景观中四处走动,并与兔子洞、狐狸以及你可能已经实现的任何其他实体进行交互。

挑战列表如下:

  1. 将玩家随机放置在一个空闲的位置。在景观上显示玩家姓名首字母。
  2. 在景观中四处走动。你可以选择 N、E、S、W 进行移动,每次移动代表一个时间段。或者你可以原地不动。
  3. 为玩家添加健康和饥饿属性。你可以通过菜单选项显示这些属性。每个时间段后,饥饿属性会降低 1 个单位。
  4. 允许玩家与狐狸搏斗。只有当玩家距离狐狸 2 个单位时,并且玩家吓唬了狐狸才能发生战斗。狐狸不会吓唬玩家。赢了战斗会获得随机数量的食物,玩家的健康值也会受到伤害。因此,如果你输了战斗,玩家就会死亡,并返回到默认模拟(旁观模式)。
  5. 接下来添加鹰类。鹰可以通过偷袭来攻击玩家。这意味着鹰可以在景观中移动,但现在显示可能会出现错误。例如,如果玩家、兔子洞和鹰都在同一个格子中,情况就会变得很糟糕。所以要确保鹰不能进入有玩家和兔子洞的格子。每个模拟只能有一只鹰(目前),如果鹰在 2 个格子范围内,它有 10% 的概率攻击玩家。当鹰攻击时,玩家的健康值会降低 10 点。最后,确保鹰有它自己的健康和饥饿的私有属性。

Python 解决方案

答案

巨蟒统治的解决方案 Thomas O'Keeffe (BEEF CORP)

女王伊丽莎白学校,柯比龙斯代尔

############
Location Class

class Location:
  def __init__(self):
    self.Fox = None
    self.Warren = None
    self.Player = None

################
New Player Class

class Player:
  def __init__(self):
    self.__PlayerName = raw_input("Enter player name: ")
    self.__Health = 50
    self.__Hunger = 50

  def DisplayStats(self):
    print ""
    print "Player: " + self.__PlayerName
    print "Health: " + str(self.__Health) + "  Hunger: " + str(self.__Hunger)
    print ""

  def GetPlayerName(self):
    return self.__PlayerName

  def GetHealth(self):
    return self.__Health

  def GetHunger(self):
    return self.__Hunger

  def EatRabbit(self):
    self.__Hunger += 5

  def EatFox(self):
    self.__Hunger += 15

  def TakeHits(self, Hits):
    self.__Health -= Hits

  def FoodDrop(self):
    self.__Hunger -= 1

  def IsPlayerDead(self):
    if (self.__Health > 0) and (self.__Hunger > 0):
      return False
    else:
      return True

#################
New Simulation Menu

    while (self.__WarrenCount > 0 or self.__FoxCount > 0) and MenuOption != 5:
      print
      if not self.__PlayerAlive:
        # DEFAULT MENU CHOICES #
        print ""
        print "0. Join the simulation. "
        print "1. Advance to next time period showing detail"
        print "2. Advance to next time period hiding detail"
        print "3. Inspect fox"
        print "4. Inspect warren"
        print "5. Exit"
        print ""

        MenuOption = int(raw_input("Select option: "))
        if MenuOption == 0:
          self.__AddPlayerToGame()
          self.__TimePeriod += 1
          self.__ShowDetail = False
          self.__AdvanceTimePeriod()
        if MenuOption == 1:
          self.__TimePeriod += 1
          self.__ShowDetail = True
          self.__AdvanceTimePeriod()
        if MenuOption == 2:
          self.__TimePeriod += 1
          self.__ShowDetail = False
          self.__AdvanceTimePeriod()
        if MenuOption == 3:
          x = self.__InputCoordinate("x")
          y = self.__InputCoordinate("y")
          if not self.__Landscape[x][y].Fox is None:
            self.__Landscape[x][y].Fox.Inspect()
        if MenuOption == 4:
          x = self.__InputCoordinate("x")
          y = self.__InputCoordinate("y")
          if not self.__Landscape[x][y].Warren is None:
            self.__Landscape[x][y].Warren.Inspect()
            self.__ViewRabbits = raw_input("View individual rabbits (y/n)? ")
            if self.__ViewRabbits == "y":
              self.__Landscape[x][y].Warren.ListRabbits()

      else:
        PlayerX,PlayerY = self.__ReturnPlayerLocation()
        # PLAYER MENU CHOICES #
        print ""
        print "0. View Player Stats"
        print "1. Move"
        print "2. Stay Put"
        if self.__PlayerCanFightFox():
          print "3. Fight Nearest Fox" 
        print ""

##################
Fox Fight Methods

  def __FightFox(self):
    FoxX, FoxY, NearestFoxDist = self.__NearestFox()
    PlayerX,PlayerY = self.__ReturnPlayerLocation()
    print ""
    print "Fighting fox at: " , FoxX , FoxY
    raw_input("")
    print ""
    # Fox Will take a random number of hits #
    # if the hits is greater than player health, fox wins, player dies #
    FoxHits = random.randint(0,50)
    print "The fox bit you" , FoxHits, "times! "
    if self.__Landscape[PlayerX][PlayerY].Player.GetHealth() - FoxHits > 0:
      print "You killed the fox. "
      self.__Landscape[PlayerX][PlayerY].Player.TakeHits(FoxHits)
      self.__Landscape[PlayerX][PlayerY].Player.EatFox()
      self.__Landscape[FoxX][FoxY].Fox = None 
    else:
      print "Fox killed player. "
      self.__PlayerAlive = False
      self.__Landscape[PlayerX][PlayerY].Player = None

  def __PlayerCanFightFox(self):
    NearestFoxX,NearestFoxY,NearestFoxDist = self.__NearestFox()
    if  NearestFoxDist <= 2:
      return True
    else:
      return False

  def __NearestFox(self):
    NearestFoxDist = 10000
    PlayerX,PlayerY = self.__ReturnPlayerLocation()
    for FoxX in range (0, self.__LandscapeSize):
      for FoxY in range (0, self.__LandscapeSize):
        if not self.__Landscape[FoxX][FoxY].Fox is None:
          DistToFox = self.__DistanceBetween(PlayerX,PlayerY,FoxX,FoxY)
          if DistToFox < NearestFoxDist:
            NearestFoxDist = DistToFox
            NearestFoxX,NearestFoxY = FoxX,FoxY
            
    return NearestFoxX,NearestFoxY,NearestFoxDist

  def __ReturnPlayerLocation(self):
    for X in range (0, self.__LandscapeSize):
      for Y in range (0, self.__LandscapeSize):
        if not self.__Landscape[X][Y].Player is None:
          PlayerX,PlayerY = X,Y
    return PlayerX,PlayerY

###########
Move Player and Other Methods

  def __MovePlayer(self):
    Direction = raw_input("Which direction are you going to move? NESW? : ")
    Direction = str.upper(Direction)
    PlayerX,PlayerY = self.__ReturnPlayerLocation()[0],self.__ReturnPlayerLocation()[1]
    OriginX,OriginY= PlayerX,PlayerY
    if Direction == 'N':
      PlayerY -= 1
    elif Direction  == 'E':
      PlayerX += 1
    elif Direction == 'S':
      PlayerY += 1
    elif Direction == 'W':
      PlayerX -= 1
    else:
      print "Invalid direction! Try again. "
      self.__MovePlayer()

    self.__Landscape[PlayerX][PlayerY].Player = self.__Landscape[OriginX][OriginY].Player
    self.__Landscape[OriginX][OriginY].Player = None

  def __AddPlayerToGame(self):
    self.__PlayerAlive = True
    if not raw_input("Random Location? Y/N: ") in ['y','Y']:
      x = int(raw_input("Input X: "))
      y = int(raw_input("Input Y: "))
    else:              
      x = random.randint(0, self.__LandscapeSize - 1)
      y = random.randint(0, self.__LandscapeSize - 1)
      while (not self.__Landscape[x][y].Warren is None) or (not self.__Landscape[x][y].Fox is None):
        x = random.randint(0, self.__LandscapeSize - 1)
        y = random.randint(0, self.__LandscapeSize - 1)

    self.__Landscape[x][y].Player = Player()
    print ""
    print "Welcome " + self.__Landscape[x][y].Player.GetPlayerName() + " ..."
    print "You have entered the game at position: " + str(x) + "," + str(y)


考试题 - 2017 年 6 月

[edit | edit source]

验证 Simulation 类中的输入坐标子例程(考试题 - 2017 年 6 月)

[edit | edit source]

C# 解决方案

答案 

答案


Delphi/Pascal 解决方案

答案 

答案


Java 解决方案

答案 

答案

    private int InputCoordinate(char CoordinateName)
    {
        int Coordinate;
        Coordinate = Console.readInteger("  Input " + CoordinateName + " coordinate: ");
        //edit: validate coordinate input
        while(Coordinate < 0 || Coordinate > LandscapeSize){
            Console.println("INVALID COORDINATE");
            Coordinate = Console.readInteger("Input " + CoordinateName + " coordinate: ");
        }
        return Coordinate;
    }

//Psalmjrel Paulin - St. Brendan's Sixthform College


Python 解决方案

答案 

答案

def __InputCoordinate(self, CoordinateName):
    # COMPLETELY UNVALIDATED; strings, empty values, incorrect lengths will all break this, until now.

    while True:
      try:
        # Attempt to parse the input string as an integer
        Coordinate = int(input("  Input " + CoordinateName + " coordinate:"))
      except:
        # If parsing failed print the line and start the next iteration of the loop
        print("Input co-ordinate not an integer")
        continue

      # Once parsing was successful, check the integer is between 0 and the LandscapeSize
      if Coordinate in range(self.__LandscapeSize):
        # Break from the loop on success
        break
      else:
        # If the integer is not within the valid limits, print an error and go to the next loop iteration
        print("Co-ordinate must be between 0 and {0} inclusive".format(self.__LandscapeSize - 1))

    return Coordinate   # only when number input is valid.

  #--------------------------------------------------------------------------------------------------------------------------------------------

  S Wood - Ossett Sixth


兔子的其他原因导致的死亡率随着年龄增长而上升,雄性兔子死亡率上升速度更快。(考试题 - 2017 年 6 月)

[编辑 | 编辑源代码]

C# 解决方案

答案 

答案


Delphi/Pascal 解决方案

答案 

答案


Java 解决方案

答案 

答案


Python 解决方案

答案 

答案

  ##------------------ Q10 - Calculate New Rabbit Age -------------------------------------
  ##------------------ This will override the original Animal Class version ---------------
  def CalculateNewAge(self):    
    if self.__Gender == Genders.Male:                                           ## Add in the gender check for Male...
      # Get the 'self._ProbabilityOfDeathOtherCauses' (from Animal class as we are overriding)...
      self._ProbabilityOfDeathOtherCauses = self._ProbabilityOfDeathOtherCauses * 1.5     # Then Multiply it by 50%.
      #print("Found Male")
        
    if (self.__Gender == Genders.Female) and (self._Age >= 1):                  ## Add in gender check for Female as well as Age being 2 or over. If so change probability...
      # Get the 'self._ProbabilityOfDeathOtherCauses' (from Animal class as we are overriding)...
      self._ProbabilityOfDeathOtherCauses = self._ProbabilityOfDeathOtherCauses + 0.05    # Then Add the 0.05 each time the female rabbits age.
      #print("Found Female")
    
    ## Build in an override (polymorphism) of the CalculateNewAge() subroutine for the Rabbit class to push its own specific aging on the original Animal class version.
    ## This will use the newly calculated 'Probability of Death by Other Causes' as a parameter to be overridden.
    super(Rabbit, self).CalculateNewAge()

  ##---------------------------------------------------------------------------------------

## S Wood - Ossett Sixth


在景观上添加一条河流 (考试题 - 2017年6月)

[编辑 | 编辑源代码]

C# 解决方案

答案 

答案


Delphi/Pascal 解决方案

答案 

答案


Java 解决方案

答案 

答案


Python 解决方案

答案 

答案


11.1 - Location 类的程序代码。

class Location:
  def __init__(self):
    self.Fox = None
    self.Warren = None
    ##---------- Q11 ----------------
    self.River = None
    ##-------------------------------

### S Wood - Ossett Sixth ###

11.2 - Simulation 类中 CreateLandscapeAndAnimals 子例程的程序代码。

##----------------------------- Q11 - River ----------------------------------------------------------------------
  def __CreateLandscapeAndAnimals(self, InitialWarrenCount, InitialFoxCount, FixedInitialLocations):
    for x in range (0, self.__LandscapeSize):
      for y in range (0, self.__LandscapeSize):
        self.__Landscape[x][y] = Location()
    if FixedInitialLocations:
      self.__Landscape[1][1].Warren = Warren(self.__Variability, 38)
      self.__Landscape[2][8].Warren = Warren(self.__Variability, 80) 
      self.__Landscape[9][7].Warren = Warren(self.__Variability, 20)
      self.__Landscape[10][3].Warren = Warren(self.__Variability, 52)
      self.__Landscape[13][4].Warren = Warren(self.__Variability, 67)
      self.__WarrenCount = 5
      self.__Landscape[2][10].Fox = Fox(self.__Variability)
      self.__Landscape[6][1].Fox = Fox(self.__Variability)
      self.__Landscape[8][6].Fox = Fox(self.__Variability)
      self.__Landscape[11][13].Fox = Fox(self.__Variability)
      self.__Landscape[12][4].Fox = Fox(self.__Variability)
      self.__FoxCount = 5
      ##---------------------------- Form River on row 2
      for x in range (0, self.__LandscapeSize):
        for y in range (2, 3):
          self.__Landscape[x][y].River = "R"
      ##---------------------------- Form River on column 5
      for x in range (5, 6):
        for y in range (0, self.__LandscapeSize):
          self.__Landscape[x][y].River = "R"

    else:
      for w in range (0, InitialWarrenCount):
        self.__CreateNewWarren()
      for f in range (0, InitialFoxCount):
        self.__CreateNewFox()

### S Wood - Ossett Sixth ###

11.3 - Simulation 类中 DrawLandscape 子例程的程序代码。

##----------------------------- Q11 - River ----------------------------------------------------------------------
  def __DrawLandscape(self):
    print()
    print("TIME PERIOD:", self.__TimePeriod)
    print()
    print("   ", end = "")
    for x in range (0, self.__LandscapeSize):
      if x < 10:
        print(" ", end = "")
      print(x, "|", end = "")
    print()
    for x in range (0, self.__LandscapeSize * 4 + 3):
      print("-", end = "")
    print()
    for y in range (0, self.__LandscapeSize):
      if y < 10:
        print(" ", end = "")
      print("", y, "|", sep = "", end = "")
      for x in range (0, self.__LandscapeSize):
        if not self.__Landscape[x][y].Warren is None:
          if self.__Landscape[x][y].Warren.GetRabbitCount() < 10:
            print(" ", end = "")
          print(self.__Landscape[x][y].Warren.GetRabbitCount(), end = "")
        else:
          print("  ", end = "")
        if not self.__Landscape[x][y].Fox is None:
          print("F", end = "")
        ##------------------------------------------------- Draw River onto Landscape -------------------
        elif not self.__Landscape[x][y].River is None:
          print("R", end = "")
        else:
          print("L", end = "")
        ##-----------------------------------------------------------------------------------------------
        print("|", end = "")
      print()

### S Wood - Ossett Sixth ###

11.4 - Simulation 类中 CreateWarrenCreateNewFox 子例程的程序代码。

##----------------------------- Q11 - River ----------------------------------------------------------------------

  def __CreateNewWarren(self):
    x = random.randint(0, self.__LandscapeSize - 1)
    y = random.randint(0, self.__LandscapeSize - 1)
    ##---------------------------------------------------- Check for River, do NOT place
    while not self.__Landscape[x][y].River is None:
      self.__Landscape[x][y].Warren is None
    ##----------------------------------------------------
    while not self.__Landscape[x][y].Warren is None:
      x = random.randint(0, self.__LandscapeSize - 1)
      y = random.randint(0, self.__LandscapeSize - 1)
    if self.__ShowDetail:
      print("New Warren at (", x, ",", y, ")", sep = "")
    self.__Landscape[x][y].Warren = Warren(self.__Variability)
    self.__WarrenCount += 1
  
  def __CreateNewFox(self):
    x = random.randint(0, self.__LandscapeSize - 1)
    y = random.randint(0, self.__LandscapeSize - 1)
    ##---------------------------------------------------- Check for River, do NOT place
    while not self.__Landscape[x][y].River is None:
      self.__Landscape[x][y].Fox is None
    ##----------------------------------------------------
    while not self.__Landscape[x][y].Fox is None:
      x = random.randint(0, self.__LandscapeSize - 1)
      y = random.randint(0, self.__LandscapeSize - 1)
    if self.__ShowDetail:
      print("  New Fox at (", x, ",", y, ")", sep = "")
    self.__Landscape[x][y].Fox = Fox(self.__Variability)
    self.__FoxCount += 1

### S Wood - Ossett Sixth ###


阻止动物在移动时穿越河流 (考试题 - 2017年6月)

[编辑 | 编辑源代码]

C# 解决方案

答案 

答案


Delphi/Pascal 解决方案

答案 

答案


Java 解决方案

答案 

答案


Python 解决方案

答案 

答案

华夏公益教科书