跳轉到內容

A-level 計算機/AQA/試卷 1/框架程式/2024

來自 Wikibooks,開放世界的開放書籍

這是針對 AQA A Level 計算機科學規範。

這是可以對一些問題可能是什麼以及如何解決它們提出建議的地方。

請尊重他人,不要破壞頁面,因為這會影響學生備考!

請不要在此頁面上討論問題。請使用 討論頁面

C 部分預測

[編輯 | 編輯原始碼]

2024 年的試卷 1 將包含總共 11 分的問題(一個 3 分題,一個 2 分題和一個 6 分題)。只要你熟悉程式,即你理解每一行程式碼,並且你知道每一行程式碼的作用(可以使用 ChatGPT 和 Gemini 來實現)。重要的是使用所有可用的工具,這將很容易。我預測今年將會有一個關於單元格繼承的問題,他們會問這意味著什麼,所以價值 3 分。此外,還可能有一個關於重寫的問題,他們可能會問關於受保護、私有和公共方法的區別(從過往試卷中看)。

D 部分預測

[編輯 | 編輯原始碼]

框架程式上的程式設計問題

  • 2024 年試卷包含 4 道題:5 分題、6 分題以及兩道 14 分題 - 這些分數包括螢幕截圖,所以編碼的可能分數會高 1-2 分。另外,請問有人可以為這些問題新增更多 VB.net 解決方案嗎?給版主的留言 - 我添加了一個我認為可能會出現的問題,請放一個連結,然後刪除這條訊息 - 感謝您提供的如此出色的資源,幫助所有學生!
  • 2023 年試卷 1 包含 4 道題:5 分題、9 分題、10 分題以及 13 分題 - 這些分數包括螢幕截圖,所以編碼的可能分數會低 1-2 分。
  • 2022 年試卷 1 包含 4 道題:5 分題、9 分題、11 分題以及 13 分題 - 這些分數包括螢幕截圖,所以編碼的可能分數會低 1-2 分。
  • 2021 年試卷 1 包含 4 道題:6 分題、8 分題、9 分題以及 14 分題 - 這些分數包括螢幕截圖,所以編碼的可能分數會低 1-2 分。
  • 2020 年試卷 1 包含 4 道題:6 分題、8 分題、11 分題以及 12 分題 - 這些分數包括螢幕截圖,所以編碼的可能分數會低 1-2 分。
  • 2019 年試卷 1 包含 4 道題:5 分題、8 分題、9 分題以及 13 分題 - 這些分數包括螢幕截圖,所以編碼的可能分數會低 1-2 分。
  • 2018 年試卷 1 包含 5 道題:2 分題、5 分題、兩道 9 分題以及 12 分題 - 這些分數包括螢幕截圖。
  • 2017 年試卷 1 包含 5 道題:5 分題、三道 6 分題以及 12 分題。

當前問題是本頁面貢獻者推測的。

問題 1 - 符號大小寫 [3 分]

[編輯 | 編輯原始碼]

不接受小寫符號。例如,如果你輸入 'q',它不被識別為 'Q'。修復這個問題。

C#

簡單的解決方案,只需新增 .ToUpper() 即可,它會將你的小寫輸入轉換為大寫,並允許它們正常工作。}}

private string GetSymbolFromUser()
{
     string Symbol = "";
     while (!AllowedSymbols.Contains(Symbol))
     {
          Console.Write("Enter symbol: ");
          Symbol = Console.ReadLine().ToUpper();
      }
      return Symbol;
}


Delphi/Pascal


Java

    private String getSymbolFromUser() {
        String symbol = "";
        while (!allowedSymbols.contains(symbol)) {
            Console.write("Enter symbol: ");
            symbol = Console.readLine();
            symbol = symbol.toUpperCase(); //added line
        }
        return symbol;
    }


Python

    def __GetSymbolFromUser(self):
        Symbol = ""
        while not Symbol in self.__AllowedSymbols:
            Symbol = input("Enter symbol: ").upper()
        return Symbol


VB.NET

一個簡單的解決方案,只需新增 UCase 將所有輸入更改為大寫即可。

  Private Function GetSymbolFromUser() As String
            Dim Symbol As String = ""
            While Not AllowedSymbols.Contains(Symbol)
                Console.Write("Enter symbol: ")
                Symbol = UCase(Console.ReadLine())
            End While
            Return Symbol
        End Function


問題 2 - 遊戲檔案不存在 [4 分]

[編輯 | 編輯原始碼]

如果輸入了不存在的檔名,遊戲將無法玩(無限迴圈)。修改程式,以便在這種情況下播放預設遊戲,並顯示適當的訊息以指示這一點。

C#

static void Main(string[] args)
{
    string Again = "y";
    int Score;
    while (Again == "y")
    {
        Console.Write("Press Enter to start a standard puzzle or enter name of file to load: ");
        string Filename = Console.ReadLine();
        Puzzle MyPuzzle;
        if (Filename.Length > 0)
        {
            // new code for question 2 - use try/catch in main and otherwise cause default game to be played

            try
            {
                MyPuzzle = new Puzzle(Filename + ".txt");
            }
            catch
            {
                Console.WriteLine("Invalid file. Playing default puzzle instead.");
                MyPuzzle = new Puzzle(8, Convert.ToInt32(8 * 8 * 0.6));
            }
            // end of new code for question 2
        }
        else
        {
            MyPuzzle = new Puzzle(8, Convert.ToInt32(8 * 8 * 0.6));
        }
        Score = MyPuzzle.AttemptPuzzle();
        Console.WriteLine("Puzzle finished. Your score was: " + Score);
        Console.Write("Do another puzzle? ");
        Again = Console.ReadLine().ToLower();
    }
    Console.ReadLine();
}

// try/catch removed from loadPuzzle subroutine
private void LoadPuzzle(string Filename)
{

    using (StreamReader MyStream = new StreamReader(Filename))
    {
        int NoOfSymbols = Convert.ToInt32(MyStream.ReadLine());
        for (var Count = 1; Count <= NoOfSymbols; Count++)
        {
            AllowedSymbols.Add(MyStream.ReadLine());
        }
        int NoOfPatterns = Convert.ToInt32(MyStream.ReadLine());
        for (var Count = 1; Count <= NoOfPatterns; Count++)
        {
            List<string> Items = MyStream.ReadLine().Split(',').ToList();
            Pattern P = new Pattern(Items[0], Items[1]);
            AllowedPatterns.Add(P);
        }
        GridSize = Convert.ToInt32(MyStream.ReadLine());
        for (var Count = 1; Count <= GridSize * GridSize; Count++)
        {
            Cell C;
            List<string> Items = MyStream.ReadLine().Split(',').ToList();
            if (Items[0] == "@")
            {
                C = new BlockedCell();
            }
            else
            {
                C = new Cell();
                C.ChangeSymbolInCell(Items[0]);
                for (var CurrentSymbol = 1; CurrentSymbol < Items.Count; CurrentSymbol++)
                {
                    C.AddToNotAllowedSymbols(Items[CurrentSymbol]);
                }
            }
            Grid.Add(C);
        }
        Score = Convert.ToInt32(MyStream.ReadLine());
        SymbolsLeft = Convert.ToInt32(MyStream.ReadLine());
    }
}
}}


Delphi/Pascal


Java

//Change loadfile to return a boolean to say if it was successful

    private boolean loadPuzzle(String filename) {
        boolean success = true;
        try {
            File myStream = new File(filename);
            Scanner scan = new Scanner(myStream);
            int noOfSymbols = Integer.parseInt(scan.nextLine());
            for (int count = 0; count < noOfSymbols; count++) {
                allowedSymbols.add(scan.nextLine());
            }
            int noOfPatterns = Integer.parseInt(scan.nextLine());
            for (int count = 0; count < noOfPatterns; count++) {
                String[] items = scan.nextLine().split(",", 2);
                Pattern p = new Pattern(items[0], items[1]);
                allowedPatterns.add(p);
            }
            gridSize = Integer.parseInt(scan.nextLine());
            for (int count = 1; count <= gridSize * gridSize; count++) {
                Cell c;
                String[] items = scan.nextLine().split(",", 2);
                if (items[0].equals("@")) {
                    c = new BlockedCell();
                } else {
                    c = new Cell();
                    c.changeSymbolInCell(items[0]);
                    for (int currentSymbol = 1; currentSymbol < items.length; currentSymbol++) {
                        c.addToNotAllowedSymbols(items[currentSymbol]);
                    }
                }
                grid.add(c);
            }
            score = Integer.parseInt(scan.nextLine());
            symbolsLeft = Integer.parseInt(scan.nextLine());
        } catch (Exception e) {
            Console.writeLine("Puzzle not loaded");
            success = false;
        }
        return success;
    }

//Change the Puzzle(filename) constructor to load a default 8*8 puzzle if the filename is invalid

    public Puzzle(String filename) {
        grid = new ArrayList<>();
        allowedPatterns = new ArrayList<>();
        allowedSymbols = new ArrayList<>();
        if (!loadPuzzle(filename)) {
            //the puzzle could not be loaded - run normal game with default size and symbols
            score = 0;
            symbolsLeft = (int) (8*8*0.6);
            gridSize = 8;
            grid = new ArrayList<>();
            for (int count = 1; count < gridSize * gridSize + 1; count++) {
                Cell c;
                if (getRandomInt(1, 101) < 90) {
                    c = new Cell();
                } else {
                    c = new BlockedCell();
                }
                grid.add(c);
            }
            allowedPatterns = new ArrayList<>();
            allowedSymbols = new ArrayList<>();
            Pattern qPattern = new Pattern("Q", "QQ**Q**QQ");
            allowedPatterns.add(qPattern);
            allowedSymbols.add("Q");
            Pattern xPattern = new Pattern("X", "X*X*X*X*X");
            allowedPatterns.add(xPattern);
            allowedSymbols.add("X");
            Pattern tPattern = new Pattern("T", "TTT**T**T");
            allowedPatterns.add(tPattern);
            allowedSymbols.add("T");
        }
    }


Python

   def __LoadPuzzle(self, Filename):
       try:
           with open(Filename) as f:
               NoOfSymbols = int(f.readline().rstrip())
               for Count in range (1, NoOfSymbols + 1):
                   self.__AllowedSymbols.append(f.readline().rstrip())
               NoOfPatterns = int(f.readline().rstrip())
               for Count in range(1, NoOfPatterns + 1):
                   Items = f.readline().rstrip().split(",")
                   P = Pattern(Items[0], Items[1])
                   self.__AllowedPatterns.append(P)
               self.__GridSize = int(f.readline().rstrip())
               for Count in range (1, self.__GridSize * self.__GridSize + 1):
                   Items = f.readline().rstrip().split(",")
                   if Items[0] == "@":
                       C = BlockedCell()
                       self.__Grid.append(C)
                   else:
                       C = Cell()
                       C.ChangeSymbolInCell(Items[0])
                       for CurrentSymbol in range(1, len(Items)):
                           C.AddToNotAllowedSymbols(Items[CurrentSymbol])
                       self.__Grid.append(C)
               self.__Score = int(f.readline().rstrip())
               self.__SymbolsLeft = int(f.readline().rstrip())
       except:
           print("Puzzle not loaded")
           Main()
#WikiBooks Q2


VB.NET

這有助於重置程式碼,以便程式不會陷入無限迴圈中,試圖收集無法使用的資訊。允許使用者再次重新輸入謎題的檔名。

        Private Sub LoadPuzzle(Filename As String)
            Try
                Using MyStream As New StreamReader(Filename)
                    Dim NoOfSymbols As Integer = MyStream.ReadLine()
                    For Count = 1 To NoOfSymbols
                        AllowedSymbols.Add(MyStream.ReadLine())
                    Next
                    Dim NoOfPatterns As Integer = MyStream.ReadLine()
                    For Count = 1 To NoOfPatterns
                        Dim Items As List(Of String) = MyStream.ReadLine().Split(",").ToList()
                        Dim P As Pattern = New Pattern(Items(0), Items(1))
                        AllowedPatterns.Add(P)
                    Next
                    GridSize = Convert.ToInt32(MyStream.ReadLine())
                    For Count = 1 To GridSize * GridSize
                        Dim C As Cell
                        Dim Items As List(Of String) = MyStream.ReadLine().Split(",").ToList()
                        If Items(0) = "@" Then
                            C = New BlockedCell()
                        Else
                            C = New Cell()
                            C.ChangeSymbolInCell(Items(0))
                            For CurrentSymbol = 1 To Items.Count - 1
                                C.AddToNotAllowedSymbols(Items(CurrentSymbol))
                            Next
                        End If
                        Grid.Add(C)
                    Next
                    Score = MyStream.ReadLine()
                    SymbolsLeft = MyStream.ReadLine()
                End Using
            Catch
                Console.WriteLine("Puzzle not loaded")
                Call Main() 
            End Try
        End Sub

替代方法 --> 問題要求我們只接受存在的檔案,否則播放預設遊戲。我使用了函式,因為它更容易記住。

主 Sub

Sub Main()
    Dim Again As String = "y"
    Dim Score As Integer
    While Again = "y"
        Console.Write("Press Enter to start a standard puzzle or enter name of file to load: ")
        Dim Filename As String = Console.ReadLine()
        Dim MyPuzzle As Puzzle
        If Filename.Length > 0 And isValid(Filename) Then ' added function here
            MyPuzzle = New Puzzle(Filename & ".txt")
        Else
            MyPuzzle = New Puzzle(8, Int(8 * 8 * 0.6))
        End If
        Score = MyPuzzle.AttemptPuzzle()
        Console.WriteLine("Puzzle finished. Your score was: " & Score)
        Console.Write("Do another puzzle? ")
        Again = Console.ReadLine().ToLower()
    End While
    Console.ReadLine()
End Sub

isValid 函式

Function isValid(path As String) As Boolean
    Try
        If File.Exists(path + ".txt") Then ' adding .txt will cause the code to not read the file
            Dim inp() As String = File.ReadAllLines(path + ".txt") ' reads all input
            If inp.Length > 0 Then ' checks if file is empty
                Return True
            Else
                Console.WriteLine("File is empty.")
                Return False
            End If
        Else
            Console.WriteLine("File does not exist.")
            Return False
        End If
    Catch ex As Exception ' if we experience any exceptions, then we can presume that the file is not a game file
        Console.WriteLine("Error reading file: " & ex.Message)
        Return False
    End Try
End Function


問題 3 - 炸燬方塊(被阻擋的單元格) [10 分]

[編輯 | 編輯原始碼]

有一個“炸彈”可以移除或“炸燬”一個“被阻擋的單元格”中的方塊,但這會讓你損失一些分數(減去一些分數)。

C#

// start change
private string GetSymbolFromUser()
{
    string Symbol = "";
    while (!AllowedSymbols.Contains(Symbol) && Symbol != "bomb")
    {
        Console.Write("Enter symbol or 'bomb' to blow up an @: ");
        Symbol = Console.ReadLine();
    }
    return Symbol;
}
// end change

public virtual int AttemptPuzzle()

// start change
string Symbol = GetSymbolFromUser();
if (Symbol == "bomb" && Score >= 10)
{
    int i = (GridSize - Row) * GridSize + Column  1;
    Grid[i] = new Cell(CurrentCell.GetSymbolsNotAllowed);
    Score -= 10;
}
else if (Symbol == "bomb" && Score < 10)
{
    Console.WriteLine("You do not have sufficient score to use this move");
}
else
{
    SymbolsLeft -= 1;
    Cell CurrentCell = GetCell(Row, Column);
    if (CurrentCell.CheckSymbolAllowed(Symbol))
    {
        CurrentCell.ChangeSymbolInCell(Symbol);
        int AmountToAddToScore = CheckForMatchWithPattern(Row, Column);
        if (AmountToAddToScore > 0)
        {
            Score += AmountToAddToScore;
        }
    }
    if (SymbolsLeft == 0)
    {
        Finished = true;
    }
}
// end change
// start change (in class Cell)
public Cell(List<string> _symbolsNotAllowed)
{
    Symbol = "";
    SymbolsNotAllowed = _symbolsNotAllowed;
}

public List<string> GetSymbolsNotAllowed
{
    get { return SymbolsNotAllowed; }
}
// end change


Delphi/Pascal


Java

在列表中新增另一個符號 B 以在過程中識別它。

allowedSymbols.add("B");

並在更新迴圈(attemptPuzzle)中為“B”符號新增一個條件。

public int attemptPuzzle() {
        boolean finished = false;
        while (!finished) {
            displayPuzzle();
            Console.writeLine("Current score: " + score);
            int row = -1;
            boolean valid = false;
            while (!valid) {
                Console.write("Enter row number: ");
                try {
                    row = Integer.parseInt(Console.readLine());
                    valid = true;
                } catch (Exception e) {
                }
            }
            int column = -1;
            valid = false;
            while (!valid) {
                Console.write("Enter column number: ");
                try {
                    column = Integer.parseInt(Console.readLine());
                    valid = true;
                } catch (Exception e) {
                }
            }
            String symbol = getSymbolFromUser();
            Cell currentCell = getCell(row, column); // this was moved up for the validation below
            if(symbol.equals("B") && currentCell.getClass() == BlockedCell.class && score > 2) { // check if the symbol is "B", the target is a BlockedCell and the player has enough score to sacrifice
                grid.set((gridSize - row) * gridSize + column - 1, new Cell()); // set an empty cell to the position (indexing can be found in getCell() method)
                score -= 3; // change the score
            } else if (symbol.equals("B")){
                System.out.println("Cannot blow an empty block or you have not enough score to use the command.");
                continue; // start a new iteration BEFORE symbolsLeft is decremented (no move was made)
            }
            symbolsLeft -= 1;
            if (currentCell.checkSymbolAllowed(symbol)) {
                currentCell.changeSymbolInCell(symbol);
                int amountToAddToScore = checkForMatchWithPattern(row, column);
                if (amountToAddToScore > 0) {
                    score += amountToAddToScore;
                }
            }
            if (symbolsLeft == 0) {
                finished = true;
            }
        }
        Console.writeLine();
        displayPuzzle();
        Console.writeLine();
        return score;
    }


Python

這添加了一個新的符號“B”,它只能在被阻擋的瓷磚上播放。

# Add to the init of Puzzle
self.__AllowedSymbols.append("B")

def AttemptPuzzle(self):
    Finished = False
    while not Finished:
        self.DisplayPuzzle()
        print("Current score: " + str(self.__Score))
        Row = -1
        Valid = False
        while not Valid:
            try:
                Row = int(input("Enter row number: "))
                Valid = True
            except:
                pass
        Column = -1
        Valid = False
        while not Valid:
            try:
                Column = int(input("Enter column number: "))
                Valid = True
            except:
                pass
        Symbol = self.__GetSymbolFromUser()
        self.__SymbolsLeft -= 1
        CurrentCell = self.__GetCell(Row, Column)

        # CHANGES HERE
        if Symbol == "B" and type(CurrentCell) == BlockedCell:
            Index = (self.__GridSize - Row) * self.__GridSize + Column - 1
            self.__Grid[Index] = Cell()  # Change Blocked Cell to regular Cell so the cell is "open"
            self.__Score -= 3

        elif CurrentCell.CheckSymbolAllowed(Symbol) and Symbol != "B":
            CurrentCell.ChangeSymbolInCell(Symbol)
            AmountToAddToScore = self.CheckforMatchWithPattern(Row, Column)
            if AmountToAddToScore > 0:
                self.__Score += AmountToAddToScore

        if self.__SymbolsLeft == 0:
            Finished = True
    print()
    self.DisplayPuzzle()
    print()
    return self.__Score


VB.NET

      ‘’in Function AttemptPuzzle()            
     '' start change
                Dim Symbol As String = GetSymbolFromUser()
                Dim CurrentCell As Cell = GetCell(Row, Column)
                If ((Symbol = "bomb") And (Score >= 10)) Then
                    Dim i As Integer = ((GridSize - Row) * GridSize + Column) - 1
                    Grid(i) = New Cell
                    Score -= 10
                ElseIf ((Symbol = "bomb") And (Score < 10)) Then
                    Console.WriteLine("You do not have suffiecient score to use this move")

                Else
                    SymbolsLeft -= 1

                    If CurrentCell.CheckSymbolAllowed(Symbol) Then
                        CurrentCell.ChangeSymbolInCell(Symbol)
                        Dim AmountToAddToScore As Integer = CheckForMatchWithPattern(Row, Column)
                        If AmountToAddToScore > 0 Then
                            Score += AmountToAddToScore
                        End If
                    End If
                    If SymbolsLeft = 0 Then
                        Finished = True
                    End If
                End If
                ''end change

Private Function GetSymbolFromUser() As String

    Dim Symbol As String = ""
    ''start change
    While ((Not AllowedSymbols.Contains(Symbol)) And (Not Symbol = "bomb"))
        '' end change
        Console.Write("Enter symbol or 'bomb' to blow up an @: ")
        Symbol = (Console.ReadLine())
    End While

    Return Symbol
End Function


問題 4 - 新增額外的符號/字母 [3 分]

[編輯 | 編輯原始碼]

新增額外的字母/符號,例如 L 或 O 或 U 或 V 或 C 或 H 或 I。

C#

這裡的程式碼將允許你獲得 10 分,因為在網格中建立了一個 L 形狀。
Pattern LPattern = new Pattern("L", "L***LLLL*");
AllowedPatterns.Add(LPattern);
AllowedSymbols.Add("L");


Delphi/Pascal


Java

如果你仔細觀察,你會發現模式識別呈螺旋狀

0_1_2

7_8_3

6_5_4

所以我們需要以相同的方式對映我們的新字母

"L" 的示例

L_*_*

L_*_*

L_L_L

接下來,只需按照模式建立字串即可。

// ...other patterns
Pattern lPattern = new Pattern("L", "L***LLLL*");
allowedPatterns.add(lPattern);
allowedSymbols.add("L");


Python

模式檢查的運作方式是順時針方向。這是順序。

1 2 3
8 9 4
7 6 5

因此,Q 的模式是 QQ**Q**QQ,如果你按照這個順序放置符號,就會得到正確的模式。

# Edit Puzzle().init()
class Puzzle():
    def __init__(self, *args):
        LPattern = Pattern("L", "L***LLLL*")
        self.__AllowedPatterns.append(LPattern)
        self.__AllowedSymbols.append("L")


VB.NET

這允許使用者建立一個 L 形圖案,從而獲得 10 分。

           Dim LPattern As Pattern = New Pattern("L", "L***LLLL*")
           AllowedPatterns.Add(LPattern)
           AllowedSymbols.Add("L")


問題 5 - 儲存當前遊戲(狀態)[5 分]

[編輯 | 編輯原始碼]

儲存遊戲的當前狀態(檔案處理)/寫入文字檔案。

C#

public virtual int AttemptPuzzle()
{
    bool Finished = false;
    while (!Finished)
    {
        DisplayPuzzle();
        Console.WriteLine("Current score: " + Score);
        bool Valid = false;
        int Row = -1;
        while (!Valid)
        {
            Console.Write("Enter row number: ");
            try
            {
                Row = Convert.ToInt32(Console.ReadLine());
                Valid = true;
            }
            catch
            {
            }
        }
        int Column = -1;
        Valid = false;
        while (!Valid)
        {
            Console.Write("Enter column number: ");
            try
            {
                Column = Convert.ToInt32(Console.ReadLine());
                Valid = true;
            }
            catch
            {
            }
        }
        string Symbol = GetSymbolFromUser();
        SymbolsLeft -= 1
        Cell CurrentCell = GetCell(Row, Column);
        if (CurrentCell.CheckSymbolAllowed(Symbol))
        {
            SymbolsLeft -= 1;
            CurrentCell.ChangeSymbolInCell(Symbol);
            int AmountToAddToScore = CheckForMatchWithPattern(Row, Column);
            if (AmountToAddToScore > 0)
            {
                Score += AmountToAddToScore;
            }
        }
        if (SymbolsLeft == 0)
        {
            Finished = true;
        }
        //New code for question 5 including calling new SavePuzzle() method:
        Console.WriteLine("Do you wish to save your puzzle and exit? (Y for yes)");
        if (Console.ReadLine().ToUpper() == "Y")
        {
            Console.WriteLine("What would you like to save your puzzle as?");
            string file = Console.ReadLine();
            SavePuzzle(file);
            Console.WriteLine("Puzzle Successfully Saved.");
            break;
        }
        //end of code for question 5
    }
    Console.WriteLine();
    DisplayPuzzle();
    Console.WriteLine();
    return Score;

//new SavePuzzle() method:
private void SavePuzzle(string filename)
{
    filename = filename + ".txt";
    using (StreamWriter sw = new StreamWriter(filename))
    {
        sw.WriteLine(AllowedSymbols.Count);
        foreach (var symbol in AllowedSymbols)
        {
            sw.WriteLine(symbol);
        }
        sw.WriteLine(AllowedPatterns.Count);
        foreach (var pattern in AllowedPatterns)
        {
            sw.WriteLine(pattern.GetPatternSymbol() + "," + pattern.GetPatternSequence());
        }
        sw.WriteLine(GridSize);

        foreach (Cell C in Grid)
        {
            List<string> notAllowedSymbol = C.returnNotAllowedSymbols();
            try
            {
                sw.WriteLine(C.GetSymbol() + "," + notAllowedSymbol[0]);
            }
            catch
            {
                sw.WriteLine(C.GetSymbol() + ",");
            }
        }
        sw.WriteLine(Score);
        sw.WriteLine(SymbolsLeft);
    }
}

// new returnNotAllowedSymbol() method in Pattern class 
public virtual List<string> returnNotAllowedSymbols()
{
    return SymbolsNotAllowed;
}


Delphi/Pascal


Java

}

   private void savePuzzle(String filename){
       try {
           FileWriter myWriter = new FileWriter(filename);
           myWriter.write(""+allowedSymbols.size()+"\n");
           for (String s:allowedSymbols){
               myWriter.write(s+"\n");
           }
           myWriter.write(""+allowedPatterns.size()+"\n");
           for (Pattern p:allowedPatterns){
               myWriter.write(p.getPatternSequence().charAt(0)+","+p.getPatternSequence()+"\n");
           }
           myWriter.write(""+gridSize+"\n");
           for (Cell c:grid){
             String toWrite=""+c.getSymbol()+",";
             for(String s:allowedSymbols){
                 if (!c.checkSymbolAllowed(s)){
                     toWrite=toWrite+s;
                 }
             }              
             myWriter.write(toWrite+"\n");
           }
           myWriter.write(score+"\n");
           myWriter.write(symbolsLeft+"\n");
           myWriter.close();
       } catch (Exception e) {
           Console.writeLine("Puzzle not saved");
       }
   }
// And changes in attemptPuzzle

           Console.writeLine("Do you wish to save and quit the game y/n?: ");
           String quit = Console.readLine();
           if (quit.equals("y")){
               Console.writeLine("Please enter a filename with a .txt extension: ");
               String fname=Console.readLine();
               savePuzzle(fname);
               finished = true;
           }


Python

Some of the get methods have to be added manually in each class.

class Puzzle:
    def __save_puzzle(self, filename):
        with open(filename, 'w') as f:
            f.write(f"{len(self.__AllowedSymbols)}\n")
            for i in self.__AllowedSymbols:
                f.write(f"{i}\n")
            f.write(f"{len(self.__AllowedPatterns)}\n")
            for i in self.__AllowedPatterns:
                f.write(f"{i.GetSymbol()},{i.GetPatternSequence()}\n")
            f.write(f"{self.__GridSize}\n")
            for cell in self.__Grid:
                symbol = cell.GetSymbol()
                f.write(f"{symbol if symbol != '-' else ''},{','.join(cell.GetNotAllowedSymbols())}\n")

            f.write(f"{self.__Score}\n")
            f.write(f"{self.__SymbolsLeft}\n")


VB.NET

Sub SaveGame()

           Console.WriteLine("Enter filename")
           Dim filename As String = Console.ReadLine
           filename = filename & ".txt"
           Dim SR As New StreamWriter(filename)
           'this is the number of symbols
           SR.WriteLine(AllowedSymbols.Count)
           'this loops through the different symbols
           For i As Integer = 0 To AllowedSymbols.Count - 1
               SR.WriteLine(AllowedSymbols(i))
           Next
           'this is the number of patterns
           SR.WriteLine(AllowedPatterns.Count)
           'displays the different patterns
           For j As Integer = 0 To AllowedPatterns.Count - 1
               SR.WriteLine(AllowedSymbols(j) & "," & AllowedPatterns(j).GetPatternSequence)
           Next
           'this is the gridsize
           SR.WriteLine(GridSize)
           'this writes out the grid
           For a As Integer = 0 To Grid.Count - 1
               SR.WriteLine(Grid(a).GetSymbol() & Grid(a).returnNotAllowedList)
           Next
           'this is the current score
           SR.WriteLine(Score)
           'this is the number of symbols left
           SR.WriteLine(SymbolsLeft)
           SR.Close()
       End Sub


'清理版本(上面的版本有一些問題)

       Public Overridable Function AttemptPuzzle() As Integer
           Dim Finished As Boolean = False
           While Not Finished
               DisplayPuzzle()
               Console.WriteLine("Current score: " & Score)
               Dim Valid As Boolean = False
               Dim Row As Integer = -1
               While Not Valid
                   Console.Write("Enter row number: ")
                   Try
                       Row = Console.ReadLine()
                       Valid = True
                   Catch
                   End Try
               End While
               Dim Column As Integer = -1
               Valid = False
               While Not Valid
                   Console.Write("Enter column number: ")
                   Try
                       Column = Console.ReadLine()
                       Valid = True
                   Catch
                   End Try
               End While
               Dim Symbol As String = GetSymbolFromUser()
               Dim CurrentCell As Cell = GetCell(Row, Column)
               If (Symbol = "bomb") AndAlso (Score >= 10) Then
                   Dim i As Integer = ((GridSize - Row) * GridSize + Column) - 1
                   Grid(i) = New Cell
                   Score -= 10
               ElseIf Symbol = "Bomb" AndAlso Score < 10 Then
                   Console.WriteLine("You do not have sufficient score to use this move")
               Else
                   SymbolsLeft -= 1
                   If CurrentCell.CheckSymbolAllowed(Symbol) Then
                       CurrentCell.ChangeSymbolInCell(Symbol)
                       Dim AmountToAddToScore As Integer = CheckForMatchWithPattern(Row, Column)
                       If AmountToAddToScore > 0 Then
                           Score += AmountToAddToScore
                       End If
                   End If
                   If SymbolsLeft = 0 Then
                       Finished = True
                   End If
                   Console.WriteLine("Would you like to save your puzzle and exit? (Y/N) ")
                   If UCase(Console.ReadLine()) = "Y" Then
                       Console.WriteLine("What name would you like to save your puzzle as ? ")
                       Dim new_filename As String = Console.ReadLine() + ".txt"
                       Dim error_status = SavePuzzle(new_filename)
                       If Not error_status Then
                           Console.WriteLine("Puzzle Successfully Saved. ")
                       End If
                   End If
               End If
           End While
           Console.WriteLine()
           DisplayPuzzle()
           Console.WriteLine()
           Return Score
       End Function
       Private Function SavePuzzle(filename As String) As Boolean
           Dim SR As New StreamWriter(filename)
           SR.WriteLine(AllowedSymbols.Count)
           For i As Integer = 0 To AllowedSymbols.Count - 1
               SR.WriteLine(AllowedSymbols(i))
           Next
           SR.WriteLine(AllowedPatterns.Count)
           For j As Integer = 0 To AllowedPatterns.Count - 1
               SR.WriteLine(AllowedSymbols(j) & "," & AllowedPatterns(j).GetPatternSequence)
           Next
           SR.WriteLine(GridSize)
           For t = 0 To Grid.Count - 1
               Dim notAllowedSymbol As String
               ' Check if returnNotAllowedList is empty
               If Grid(t).returnNotAllowedList.Count > 0 Then
                   notAllowedSymbol = Grid(t).returnNotAllowedList(0)
               Else
                   notAllowedSymbol = ""
               End If
               SR.WriteLine(Grid(t).GetSymbol & "," & notAllowedSymbol)
           Next
           SR.WriteLine(Score)
           SR.WriteLine(SymbolsLeft)
           SR.Close()
           Return True
       End Function

Cell 類

       Public Function returnNotAllowedList() As List(Of String)
           Return SymbolsNotAllowed
       End Function

另一種方法 --> 最好不要修改 Cell 類(除非要求)。我也使用了字串連線,因為它更容易在考試壓力下記住,而且更容易理解/除錯。

AttemptPuzzle 方法

 Public Overridable Function AttemptPuzzle() As Integer
     Dim Finished As Boolean = False
     While Not Finished
         DisplayPuzzle()
         Console.WriteLine("Current score: " & Score)
         Dim Valid As Boolean = False
         Dim Row As Integer = -1
         While Not Valid
             Console.Write("Enter row number: ")
             Try ' CHANGES START FROM HERE
                 Dim inp1 = Console.ReadLine()
                 If (inp1 = "SAVEGAME") Then
                     SaveGame()
                     Valid = False
                 Else
                     Row = Int32.Parse(inp1)
                     Valid = True
                 End If
             Catch ' CHANGE ENDS HERE
             End Try
         End While
         Dim Column As Integer = -1
         Valid = False
         While Not Valid
             Console.Write("Enter column number: ")
             Try ' CHANGES START FROM HERE
                 Dim inp1 = Console.ReadLine()
                 If (inp1 = "SAVEGAME") Then
                     SaveGame()
                     Valid = False
                 Else
                     Column = Int32.Parse(inp1)
                     Valid = True
                 End If
             Catch ' CHANGE ENDS HERE
             End Try
         End While
         Dim Symbol As String = GetSymbolFromUser()
         SymbolsLeft -= 1
         Dim CurrentCell As Cell = GetCell(Row, Column)
         If CurrentCell.CheckSymbolAllowed(Symbol) Then
             CurrentCell.ChangeSymbolInCell(Symbol)
             Dim AmountToAddToScore As Integer = CheckForMatchWithPattern(Row, Column)
             If AmountToAddToScore > 0 Then
                 Score += AmountToAddToScore
             End If
         End If
         If SymbolsLeft = 0 Then
             Finished = True
         End If
     End While
     Console.WriteLine()
     DisplayPuzzle()
     Console.WriteLine()
     Return Score
 End Function

SaveGame 方法

Private Sub SaveGame()
    Dim alreadyExists As Boolean = True ' start by making your variables
    Dim savePath As String = String.Empty
    Dim fileContent As String = String.Empty
    While alreadyExists ' make a loop until you get valid input
        Console.Write("Enter a name:")
        savePath = Console.ReadLine()
        If File.Exists(savePath + ".txt") Then ' see if it exists
            alreadyExists = True
            Console.WriteLine("Please enter a file name that is not taken already!")
        Else
            alreadyExists = False
        End If
    End While ' We are basically constructing a string that we will then make as a text file, you can StreamReader or StringBuilder but I personally perfer this as its more easier to debug. Use the text files provided and LoadPuzzle method for help
    fileContent = fileContent & (AllowedSymbols.Count.ToString() + Environment.NewLine) ' symbols allowed
    For Each sym In AllowedSymbols
        fileContent = fileContent & (sym + Environment.NewLine) ' add the allowed symbols one by one
    Next
    fileContent = fileContent & (AllowedPatterns.Count.ToString() + Environment.NewLine) ' patterns allowed
    For Each pat In AllowedPatterns
        fileContent = fileContent & (findSymbol(pat.GetPatternSequence().ToString()).ToString() + "," + pat.GetPatternSequence().ToString() + Environment.NewLine) ' Get the Symbol and then the pattern split by ,
    Next
    fileContent = fileContent & (GridSize.ToString() + Environment.NewLine) ' gridsize
    For Each item In Grid ' we export all the cells into the text file
        Dim symbol = item.GetSymbol ' see if its an empty cell or normal/blocked cell
        Dim notAllowed As String = String.Empty
        For Each sym In AllowedSymbols ' checks for the not allowed symbol, would be nice for AQA to make a function for us
            If (Not item.CheckSymbolAllowed(sym)) Then
                notAllowed = sym
                Exit For ' you will get the last symbol if you don't add this
            End If
        Next
        If (symbol = "-") Then ' comma only plus the not allowed symbol
            fileContent = fileContent & ("," + notAllowed.ToString() + Environment.NewLine)
        Else ' the symbol comma plus the not allowed symbol
            fileContent = fileContent & (symbol.ToString() + "," + notAllowed.ToString() + Environment.NewLine)
        End If
    Next
    fileContent = fileContent & (Score.ToString() + Environment.NewLine) ' score
    fileContent = fileContent & (SymbolsLeft.ToString() + Environment.NewLine) ' how many left
    fileContent.TrimEnd() ' bug that creates a random new line is fixed here
    File.WriteAllText(savePath + ".txt", fileContent) ' create txt
End Sub

findSymbol 方法

Function findSymbol(str As String) ' Not all patterns might start with their symbol, this is a failsafe
    For Each strs In str
        If (strs <> "*") Then
            Return strs
        End If
    Next
End Function


問題 6 - 旋轉字母/符號 [9 分]

[編輯 | 編輯原始碼]

對“旋轉”的符號/字母進行評分(得分較低?)。

C#

旋轉字母獲得 5 分,而不是 10 分。

 public virtual int CheckForMatchWithPattern(int Row, int Column)
 {
     for (var StartRow = Row + 2; StartRow >= Row; StartRow--)
     {
         for (var StartColumn = Column - 2; StartColumn <= Column; StartColumn++)
         {
             try
             {
                 string PatternString = "";
                 PatternString += GetCell(StartRow, StartColumn).GetSymbol();
                 PatternString += GetCell(StartRow, StartColumn + 1).GetSymbol();
                 PatternString += GetCell(StartRow, StartColumn + 2).GetSymbol();
                 PatternString += GetCell(StartRow - 1, StartColumn + 2).GetSymbol();
                 PatternString += GetCell(StartRow - 2, StartColumn + 2).GetSymbol();
                 PatternString += GetCell(StartRow - 2, StartColumn + 1).GetSymbol();
                 PatternString += GetCell(StartRow - 2, StartColumn).GetSymbol();
                 PatternString += GetCell(StartRow - 1, StartColumn).GetSymbol();
                 PatternString += GetCell(StartRow - 1, StartColumn + 1).GetSymbol();

                 for (int i = 0; i < 4; i++)
                 {
                     foreach (var P in AllowedPatterns)
                     {
                         string CurrentSymbol = GetCell(Row, Column).GetSymbol();
                         if (P.MatchesPattern(PatternString, CurrentSymbol))
                         {
                             GetCell(StartRow, StartColumn).AddToNotAllowedSymbols(CurrentSymbol);
                             GetCell(StartRow, StartColumn + 1).AddToNotAllowedSymbols(CurrentSymbol);
                             GetCell(StartRow, StartColumn + 2).AddToNotAllowedSymbols(CurrentSymbol);
                             GetCell(StartRow - 1, StartColumn + 2).AddToNotAllowedSymbols(CurrentSymbol);
                             GetCell(StartRow - 2, StartColumn + 2).AddToNotAllowedSymbols(CurrentSymbol);
                             GetCell(StartRow - 2, StartColumn + 1).AddToNotAllowedSymbols(CurrentSymbol);
                             GetCell(StartRow - 2, StartColumn).AddToNotAllowedSymbols(CurrentSymbol);
                             GetCell(StartRow - 1, StartColumn).AddToNotAllowedSymbols(CurrentSymbol);
                             GetCell(StartRow - 1, StartColumn + 1).AddToNotAllowedSymbols(CurrentSymbol);
                             
                             if (i == 0)
                             {
                                 return 10;
                             }
                             else
                             {
                                 return 5;
                             }
                         }
                     }

                     PatternString = PatternString.Substring(2, 6) + PatternString.Substring(0, 2) + PatternString[8];
                 }
             }
             catch
             {
             }
         }
     }
     return 0;
 }


Delphi/Pascal


Java

public int CheckforMatchWithPattern(int Row, int Column) {
    for (int StartRow = Row + 2; StartRow > Row - 1; StartRow--) {
        for (int StartColumn = Column - 2; StartColumn < Column + 1; StartColumn++) {
            try {
                String PatternString = "";
                PatternString += this.__GetCell(StartRow, StartColumn).GetSymbol();
                PatternString += this.__GetCell(StartRow, StartColumn + 1).GetSymbol();
                PatternString += this.__GetCell(StartRow, StartColumn + 2).GetSymbol();
                PatternString += this.__GetCell(StartRow - 1, StartColumn + 2).GetSymbol();
                PatternString += this.__GetCell(StartRow - 2, StartColumn + 2).GetSymbol();
                PatternString += this.__GetCell(StartRow - 2, StartColumn + 1).GetSymbol();
                PatternString += this.__GetCell(StartRow - 2, StartColumn).GetSymbol();
                PatternString += this.__GetCell(StartRow - 1, StartColumn).GetSymbol();
                PatternString += this.__GetCell(StartRow - 1, StartColumn + 1).GetSymbol();
                String LeftRotation = PatternString.substring(6, 8) + PatternString.substring(0, 6) + PatternString.substring(8);
                String RightRotation = PatternString.substring(2, 7) + PatternString.substring(0, 2) + PatternString.substring(8);
                String DownRotation = PatternString.substring(4, 8) + PatternString.substring(0, 4) + PatternString.substring(8);
                String[] Rotations = {PatternString, LeftRotation, RightRotation, DownRotation};
                for (Pattern P : this.__AllowedPatterns) {
                    for (String rotation : Rotations) {
                        char CurrentSymbol = this.__GetCell(Row, Column).GetSymbol();
                        if (P.MatchesPattern(rotation, CurrentSymbol)) {
                            this.__GetCell(StartRow, StartColumn).AddToNotAllowedSymbols(CurrentSymbol);
                            this.__GetCell(StartRow, StartColumn + 1).AddToNotAllowedSymbols(CurrentSymbol);
                            this.__GetCell(StartRow, StartColumn + 2).AddToNotAllowedSymbols(CurrentSymbol);
                            this.__GetCell(StartRow - 1, StartColumn + 2).AddToNotAllowedSymbols(CurrentSymbol);
                            this.__GetCell(StartRow - 2, StartColumn + 2).AddToNotAllowedSymbols(CurrentSymbol);
                            this.__GetCell(StartRow - 2, StartColumn + 1).AddToNotAllowedSymbols(CurrentSymbol);
                            this.__GetCell(StartRow - 2, StartColumn).AddToNotAllowedSymbols(CurrentSymbol);
                            this.__GetCell(StartRow - 1, StartColumn).AddToNotAllowedSymbols(CurrentSymbol);
                            this.__GetCell(StartRow - 1, StartColumn + 1).AddToNotAllowedSymbols(CurrentSymbol);
                            return 10;
                        }
                    }
                }
            } catch (Exception e) {
                // Handle exception
            }
        }
    }
    return 0;
}


Python

    def CheckforMatchWithPattern(self, Row, Column):
        for StartRow in range(Row + 2, Row - 1, -1):
            for StartColumn in range(Column - 2, Column + 1):
                try:
                    PatternString = ""
                    PatternString += self.__GetCell(StartRow, StartColumn).GetSymbol()
                    PatternString += self.__GetCell(StartRow, StartColumn + 1).GetSymbol()
                    PatternString += self.__GetCell(StartRow, StartColumn + 2).GetSymbol()
                    PatternString += self.__GetCell(StartRow - 1, StartColumn + 2).GetSymbol()
                    PatternString += self.__GetCell(StartRow - 2, StartColumn + 2).GetSymbol()
                    PatternString += self.__GetCell(StartRow - 2, StartColumn + 1).GetSymbol()
                    PatternString += self.__GetCell(StartRow - 2, StartColumn).GetSymbol()
                    PatternString += self.__GetCell(StartRow - 1, StartColumn).GetSymbol()
                    PatternString += self.__GetCell(StartRow - 1, StartColumn + 1).GetSymbol()
                    LeftRotation = PatternString[6:8] + PatternString[:6]+PatternString[8]
                    RightRotation = PatternString[2:8] + PatternString[0:2] + PatternString[8]
                    DownRotation = PatternString[4:8] + PatternString[:4] + PatternString[8]
                    Rotations = [PatternString, LeftRotation, RightRotation, DownRotation]
                    for P in self.__AllowedPatterns:
                        for rotation in Rotations:
                            CurrentSymbol = self.__GetCell(Row, Column).GetSymbol()
                            if P.MatchesPattern(rotation, CurrentSymbol):
                                self.__GetCell(StartRow, StartColumn).AddToNotAllowedSymbols(CurrentSymbol)
                                self.__GetCell(StartRow, StartColumn + 1).AddToNotAllowedSymbols(CurrentSymbol)
                                self.__GetCell(StartRow, StartColumn + 2).AddToNotAllowedSymbols(CurrentSymbol)
                                self.__GetCell(StartRow - 1, StartColumn + 2).AddToNotAllowedSymbols(CurrentSymbol)
                                self.__GetCell(StartRow - 2, StartColumn + 2).AddToNotAllowedSymbols(CurrentSymbol)
                                self.__GetCell(StartRow - 2, StartColumn + 1).AddToNotAllowedSymbols(CurrentSymbol)
                                self.__GetCell(StartRow - 2, StartColumn).AddToNotAllowedSymbols(CurrentSymbol)
                                self.__GetCell(StartRow - 1, StartColumn).AddToNotAllowedSymbols(CurrentSymbol)
                                self.__GetCell(StartRow - 1, StartColumn + 1).AddToNotAllowedSymbols(CurrentSymbol)
                                return 10
                except:
                    pass
        return 0


VB.NET

        Public Overridable Function CheckForMatchWithPattern(Row As Integer, Column As Integer) As Integer
            For StartRow = Row + 2 To Row Step -1
                For StartColumn = Column - 2 To Column
                    Try
                        Dim PatternString As String = ""
                        PatternString &= GetCell(StartRow, StartColumn).GetSymbol()
                        PatternString &= GetCell(StartRow, StartColumn + 1).GetSymbol()
                        PatternString &= GetCell(StartRow, StartColumn + 2).GetSymbol()
                        PatternString &= GetCell(StartRow - 1, StartColumn + 2).GetSymbol()
                        PatternString &= GetCell(StartRow - 2, StartColumn + 2).GetSymbol()
                        PatternString &= GetCell(StartRow - 2, StartColumn + 1).GetSymbol()
                        PatternString &= GetCell(StartRow - 2, StartColumn).GetSymbol()
                        PatternString &= GetCell(StartRow - 1, StartColumn).GetSymbol()
                        PatternString &= GetCell(StartRow - 1, StartColumn + 1).GetSymbol()
                        For Each P In AllowedPatterns
                            Dim CurrentSymbol As String = GetCell(Row, Column).GetSymbol()
                            If P.MatchesPattern(PatternString, CurrentSymbol) Then
                                GetCell(StartRow, StartColumn).AddToNotAllowedSymbols(CurrentSymbol)
                                GetCell(StartRow, StartColumn + 1).AddToNotAllowedSymbols(CurrentSymbol)
                                GetCell(StartRow, StartColumn + 2).AddToNotAllowedSymbols(CurrentSymbol)
                                GetCell(StartRow - 1, StartColumn + 2).AddToNotAllowedSymbols(CurrentSymbol)
                                GetCell(StartRow - 2, StartColumn + 2).AddToNotAllowedSymbols(CurrentSymbol)
                                GetCell(StartRow - 2, StartColumn + 1).AddToNotAllowedSymbols(CurrentSymbol)
                                GetCell(StartRow - 2, StartColumn).AddToNotAllowedSymbols(CurrentSymbol)
                                GetCell(StartRow - 1, StartColumn).AddToNotAllowedSymbols(CurrentSymbol)
                                GetCell(StartRow - 1, StartColumn + 1).AddToNotAllowedSymbols(CurrentSymbol)
                                Return 10
                            End If

                            Dim angles = New Integer() {90, 180, 270}
                            For Each i As Integer In angles
                                If P.MatchesPatternRotated(PatternString, CurrentSymbol, i) Then
                                    GetCell(StartRow, StartColumn).AddToNotAllowedSymbols(CurrentSymbol)
                                    GetCell(StartRow, StartColumn + 1).AddToNotAllowedSymbols(CurrentSymbol)
                                    GetCell(StartRow, StartColumn + 2).AddToNotAllowedSymbols(CurrentSymbol)
                                    GetCell(StartRow - 1, StartColumn + 2).AddToNotAllowedSymbols(CurrentSymbol)
                                    GetCell(StartRow - 2, StartColumn + 2).AddToNotAllowedSymbols(CurrentSymbol)
                                    GetCell(StartRow - 2, StartColumn + 1).AddToNotAllowedSymbols(CurrentSymbol)
                                    GetCell(StartRow - 2, StartColumn).AddToNotAllowedSymbols(CurrentSymbol)
                                    GetCell(StartRow - 1, StartColumn).AddToNotAllowedSymbols(CurrentSymbol)
                                    GetCell(StartRow - 1, StartColumn + 1).AddToNotAllowedSymbols(CurrentSymbol)
                                    Return 15
                                End If
                            Next
                        Next
                    Catch
                    End Try
                Next
            Next
            Return 0
        End Function

        Public Function MatchesPatternRotated(PatternString As String, SymbolPlaced As String, Rotation As Integer) As Boolean
            If (SymbolPlaced <> Symbol) Then
                Return False
            End If
            Dim RotatedSequence As String = ""

            Select Case Rotation
                Case 90
                    RotatedSequence = GetPatternSequence().Substring(6, 2) + GetPatternSequence().Substring(0, 6) + GetPatternSequence.Substring(8, 1)
                    'Case 180
                    '... with substring 44 04 81...>
            End Select
            For count = 0 To PatternSequence.Length - 1
                If RotatedSequence(count).ToString() = SymbolPlaced And PatternString(count).ToString() <> Symbol Then
                    Return False
                End If
            Next
            Return True
        End Function


問題 7 - 遊戲難度設定 [12 分]

[編輯 | 編輯原始碼]

提供“遊戲難度”設定以更改遊戲難度(帶有更多阻塞單元)。

(重要 --> 可能比 11 分問題得分低,例如 4 分問題)

C#

public Puzzle(int Size, int StartSymbols)
{
    Score = 0;
    SymbolsLeft = StartSymbols;
    GridSize = Size;
    Grid = new List<Cell>();

    // new code for question 5

    int notBlockedChance;
    Console.WriteLine("Would you like the difficulty to be easy (E), medium(M), hard(H) or extremely hard (EH)?");
    string difficulty = Console.ReadLine();
    if (difficulty.ToUpper() == "EH")
    {
        notBlockedChance = 50; //these values are just an example and can be modified
    }
    else if (difficulty.ToUpper() == "H")
    {
        notBlockedChance = 60;
    }
    else if (difficulty.ToUpper() == "M")
    {
        notBlockedChance = 75;
    }
    else
    {
        notBlockedChance = 90;
    }

    for (var Count = 1; Count <= GridSize * GridSize; Count++)
    {
        Cell C;


        if (Rng.Next(1, 101) < notBlockedChance)
        //end of new code for question 5
        {
            C = new Cell();
        }
        else
        {
            C = new BlockedCell();
        }
        Grid.Add(C);
    }
    AllowedPatterns = new List<Pattern>();
    AllowedSymbols = new List<string>();
    Pattern QPattern = new Pattern("Q", "QQ**Q**QQ");
    AllowedPatterns.Add(QPattern);
    AllowedSymbols.Add("Q");
    Pattern XPattern = new Pattern("X", "X*X*X*X*X");
    AllowedPatterns.Add(XPattern);
    AllowedSymbols.Add("X");
    Pattern TPattern = new Pattern("T", "TTT**T**T");
    AllowedPatterns.Add(TPattern);
    AllowedSymbols.Add("T");


}


Delphi/Pascal


Java

public class PuzzleSP {
    public static void main(String[] args) {
        String again = "y";
        int score;
        while (again.equals("y")) {
            Console.write("Press Enter to start a standard puzzle or enter name of file to load: ");
            String filename = Console.readLine();
            Puzzle myPuzzle;
            if (filename.length() > 0) {
                myPuzzle = new Puzzle(filename + ".txt");
            } else {
            	
            	//start of altered code
            	
            	Console.writeLine("enter a difficulty (1-3 easy to hard): ");
            	int dif = Integer.parseInt(Console.readLine());
            	if(dif < 1 || dif > 3) {
            		dif = 2;
            	}
                myPuzzle = new Puzzle(8, (int)(8 * 8 * 0.6), dif);
                
                //end of altered code
            }
            score = myPuzzle.attemptPuzzle();
            Console.writeLine("Puzzle finished. Your score was: " + score);
            Console.write("Do another puzzle? ");
            again = Console.readLine().toLowerCase();
        }
        Console.readLine();
    }
}


    public Puzzle(int size, int startSymbols, int difficulty) {  //add difficulty setting
        score = 0;
        symbolsLeft = startSymbols;
        gridSize = size;
        grid = new ArrayList<>();
        for (int count = 1; count < gridSize * gridSize + 1; count++) {
            Cell c;
            int num = 0;
            
            //start of altered code
            
            if(difficulty == 1) {
            	num = 90;
            }
            else if(difficulty == 2) {
            	num = 70;
            }
            else if(difficulty == 3) {
            	num = 50;
            }
            
            //the lower num is, the more difficult the game will be.
            
            if (getRandomInt(1, 101) < num) {
                c = new Cell();
            } else {
                c = new BlockedCell();
            }
            grid.add(c);
            
            //end of altered code            
        }


Python

class Puzzle():
    def __init__(self, *args):
        if len(args) == 1:
            self.__Score = 0
            self.__SymbolsLeft = 0
            self.__GridSize = 0
            self.__Grid = []
            self.__AllowedPatterns = []
            self.__AllowedSymbols = []
            self.__LoadPuzzle(args[0])
        else:
            self.__Score = 0
            self.__SymbolsLeft = args[1]
            self.__GridSize = args[0]
            self.__Grid = []
            print("1: Easy, 2: Normal, 3: Hard")
            difficulty = ""
            while not (difficulty == "1" or difficulty == "2" or difficulty == "3") or not difficulty.isdigit():
                difficulty = input("Enter a difficulty")
            difficulty = int(difficulty)
            difficulties  = {1:95 , 2:80 , 3:65} #modify these values to change difficulties
            for Count in range(1, self.__GridSize * self.__GridSize + 1):
                if random.randrange(1, 101) < difficulties[difficulty]:
                    C = Cell()
                else:
                    C = BlockedCell()
                self.__Grid.append(C)
            self.__AllowedPatterns = []
            self.__AllowedSymbols = []
            QPattern = Pattern("Q", "QQ**Q**QQ")
            self.__AllowedPatterns.append(QPattern)
            self.__AllowedSymbols.append("Q")
            XPattern = Pattern("X", "X*X*X*X*X")
            self.__AllowedPatterns.append(XPattern)
            self.__AllowedSymbols.append("X")
            TPattern = Pattern("T", "TTT**T**T")
            self.__AllowedPatterns.append(TPattern)
            self.__AllowedSymbols.append("T")

## OR
###Adds ability for users to create new puzzle with custom gridsize and Difficulty ###(increase percentile of grid that is blocked, up to 90%)

def Main():
    Again = "y"
    Score = 0
    while Again == "y":
        Filename = input("Press Enter to start a standard puzzle or enter name of file to load: ")
        if len(Filename) > 0:
            MyPuzzle = Puzzle(Filename + ".txt")
        else:
            GrS = 0
            diff = 0
            while GrS < 3 or GrS > 16:
                GrS = int(input("Input Desired Gridsize (i.e. 5 = 5x5 grid)"))
            while diff <= 0 or diff > 9:
                diff = int(input("Input Desired Difficulty 1-9"))
            diff = diff/10
            diff = 1-diff
            MyPuzzle = Puzzle(GrS, int(GrS * GrS * diff))
        Score = MyPuzzle.AttemptPuzzle()
        print("Puzzle finished. Your score was: " + str(Score))
        Again = input("Do another puzzle? ").lower() # add (y/n)


VB.NET

Difficulty based on number of moves available

Sub Main()

       Dim Again As String = "y"
       Dim Score As Integer
       While Again = "y"
           Console.Write("Press Enter to start a standard puzzle or enter name of file to load: ")
           Dim Filename As String = Console.ReadLine()
           'ADDED CODE - checks that the filename entered has a file existing in the DEBUG folder
           Dim fileExists As Boolean = False
           Dim FullFilename As String = Filename & ".txt"
           If FileIO.FileSystem.FileExists(FullFilename) Then
               fileExists = True
           End If
           'AMENDED CODE - the if statement changed to use the boolean value above instead of
           'using the text length
           Dim MyPuzzle As Puzzle
           If fileExists Then
               MyPuzzle = New Puzzle(Filename & ".txt")
           Else
               'ADDED CODE
               Dim Dif As Integer
               Do
                   Console.WriteLine("Enter a difficulty rating from 1-9")
                   Dif = Console.ReadLine
               Loop Until Dif >= 1 And Dif < 10
               'AMENDED CODE - difficulty rating affects the numbner of moves available
               MyPuzzle = New Puzzle(8, Int(8 * 8 * (1 - (0.1 * Dif))))
           End If


           Score = MyPuzzle.AttemptPuzzle()
           Console.WriteLine("Puzzle finished. Your score was: " & Score)
           Console.Write("Do another puzzle? ")
           Again = Console.ReadLine().ToLower()
       End While
       Console.ReadLine()
   End Sub
  -> Other Implementation (could be interpreted many ways):
    Class Puzzle
        Private Score As Integer
        Private SymbolsLeft As Integer
        Private GridSize As Integer
        Private Grid As List(Of Cell)
        Private AllowedPatterns As List(Of Pattern)
        Private AllowedSymbols As List(Of String)

        Sub New(Filename As String)
            Grid = New List(Of Cell)
            AllowedPatterns = New List(Of Pattern)
            AllowedSymbols = New List(Of String)
            LoadPuzzle(Filename)
        End Sub

        Sub New(Size As Integer, StartSymbols As Integer)
            Score = 0
            SymbolsLeft = StartSymbols
            GridSize = Size
            Grid = New List(Of Cell)

            'START CHANGE HERE
            Dim difficulty As Integer = -1
            While difficulty < 1 OrElse difficulty > 9
                Console.WriteLine("Enter a difficulty rating from 1-9")
                difficulty = Console.ReadLine()
            End While

            For Count = 1 To GridSize * GridSize
                Dim C As Cell
                If Rng.Next(1, 101) < (10 * (10 - difficulty)) Then
                    C = New Cell()
                Else
                    C = New BlockedCell()
                End If
                Grid.Add(C)
            Next
            'STOP CHANGE HERE

            AllowedPatterns = New List(Of Pattern)
            AllowedSymbols = New List(Of String)
            Dim QPattern As Pattern = New Pattern("Q", "QQ**Q**QQ")
            AllowedPatterns.Add(QPattern)
            AllowedSymbols.Add("Q")
            Dim XPattern As Pattern = New Pattern("X", "X*X*X*X*X")
            AllowedPatterns.Add(XPattern)
            AllowedSymbols.Add("X")
            Dim TPattern As Pattern = New Pattern("T", "TTT**T**T")
            AllowedPatterns.Add(TPattern)
            AllowedSymbols.Add("T")
        End Sub


問題 8 - 修復放置符號錯誤 [9 分]

[編輯 | 編輯原始碼]

當你嘗試將符號放置在無效單元格中時,它仍然計入已放置符號的數量。

C#

public virtual int AttemptPuzzle()
{
    bool Finished = false;
    while (!Finished)
    {
        DisplayPuzzle();
        Console.WriteLine("Current score: " + Score);
        bool Valid = false;
        int Row = -1;
        while (!Valid)
        {
            Console.Write("Enter row number: ");
            try
            {
                Row = Convert.ToInt32(Console.ReadLine());
                Valid = true;
            }
            catch
            {
            }
        }
        int Column = -1;
        Valid = false;
        while (!Valid)
        {
            Console.Write("Enter column number: ");
            try
            {
                Column = Convert.ToInt32(Console.ReadLine());
                Valid = true;
            }
            catch
            {
            }
        }
        string Symbol = GetSymbolFromUser();
        //SymbolsLeft -= 1; => moved inside the IF statement
        Cell CurrentCell = GetCell(Row, Column);
        if (CurrentCell.CheckSymbolAllowed(Symbol))
        {
            SymbolsLeft -= 1; //moved inside if statement to fix error
            CurrentCell.ChangeSymbolInCell(Symbol);
            int AmountToAddToScore = CheckForMatchWithPattern(Row, Column);
            if (AmountToAddToScore > 0)
            {
                Score += AmountToAddToScore;
            }
        }
        if (SymbolsLeft == 0)
        {
            Finished = true;
        }

    }
    Console.WriteLine();
    DisplayPuzzle();
    Console.WriteLine();
    return Score;
}


Delphi/Pascal


Java


Python

    def AttemptPuzzle(self):
        Finished = False
        while not Finished:
            self.DisplayPuzzle()
            print("Current score: " + str(self.__Score))
            Row = -1
            Valid = False
            while not Valid:
                try:
                    Row = int(input("Enter row number: "))
                    Valid = True
                except:
                    pass
            Column = -1
            Valid = False
            while not Valid:
                try:
                    Column = int(input("Enter column number: "))
                    Valid = True
                except:
                    pass
            Symbol = self.__GetSymbolFromUser()
            # self.__SymbolsLeft -= 1 moving this line inside of the if statement
            CurrentCell = self.__GetCell(Row, Column)
            if CurrentCell.CheckSymbolAllowed(Symbol) and CurrentCell.IsEmpty()  == True: # added to make sure that the cell is empty as well before adding to that cell 
                self.__SymbolsLeft -= 1 # moved into the if statement
                CurrentCell.ChangeSymbolInCell(Symbol)
                AmountToAddToScore = self.CheckforMatchWithPattern(Row, Column)
                if AmountToAddToScore > 0:
                    self.__Score += AmountToAddToScore
            if self.__SymbolsLeft == 0:
                Finished = True
        print()
        self.DisplayPuzzle()
        print()
        return self.__Score


VB.NET

          Public Overridable Function AttemptPuzzle() As Integer
            Dim Finished As Boolean = False
            While Not Finished
                DisplayPuzzle()
                Console.WriteLine("Current score: " & Score)
                Dim Valid As Boolean = False
                Dim Row As Integer = -1
                While Not Valid
                    Console.Write("Enter row number: ")
                    Try
                        Row = Console.ReadLine()
                        Valid = True
                    Catch
                    End Try
                End While
                Dim Column As Integer = -1
                Valid = False
                While Not Valid
                    Console.Write("Enter column number: ")
                    Try
                        Column = Console.ReadLine()
                        Valid = True
                    Catch
                    End Try
                End While
                Dim Symbol As String = GetSymbolFromUser()
                'START CHANGE
                'SymbolsLeft -= 1 -> moved from this old place
                Dim CurrentCell As Cell = GetCell(Row, Column)
                If CurrentCell.CheckSymbolAllowed(Symbol) Then
                    SymbolsLeft -= 1 'to here, inside the if statement to only substract ammount of symbol left if it was not placed on a blocked cell
                    CurrentCell.ChangeSymbolInCell(Symbol)
                    Dim AmountToAddToScore As Integer = CheckForMatchWithPattern(Row, Column)
                    If AmountToAddToScore > 0 Then
                        Score += AmountToAddToScore
                    End If
                End If
                'END CHANGE
                If SymbolsLeft = 0 Then
                    Finished = True
                End If
            End While
            Console.WriteLine()
            DisplayPuzzle()
            Console.WriteLine()
            Return Score
        End Function


問題 9 - 建立要匯入的新謎題檔案 [5 分]

[編輯 | 編輯原始碼]

建立一個新的謎題檔案,供使用者匯入程式碼中玩。

C#

## annotated puzzle file, so parameters can be altered as needed

4  #number of accepted symbols
Q  
T
X
O  #new symbols can be added here, like so
4  #number of accepted patterns
Q,QQ**Q**QQ
X,X*X*X*X*X
T,TTT**T**T
O,OOOOOOOO*   #new patterns can be added here (in proper format), like so
5  #grid size (if size = x, grid is x by x). number of entries (below) should match grid size (5 * 5 = 25 in this case)
Q,Q   #First symbol is symbol on board, second symbol is symbols not allowed on that grid
Q,Q
@,Q
,
,
Q,Q
Q,Q
,Q  #eg denotes an empty space, but symbol Q is not allowed
,
,
,
X,Q
Q,Q
X,
,
,
,
X,
,
,
,
X,
,
,
,
10  #starting score
1   #number of moves


Delphi/Pascal


Java


Python

## annotated puzzle file, so parameters can be altered as needed

4  #number of accepted symbols
Q  
T
X
O  #new symbols can be added here, like so
4  #number of accepted patterns
Q,QQ**Q**QQ
X,X*X*X*X*X
T,TTT**T**T
O,OOOOOOOO*   #new patterns can be added here (in proper format), like so
5  #grid size (if size = x, grid is x by x). number of entries (below) should match grid size (5 * 5 = 25 in this case)
Q,Q   #First symbol is symbol on board, second symbol is symbols not allowed on that grid
Q,Q
@,Q
,
,
Q,Q
Q,Q
,Q  #eg denotes an empty space, but symbol Q is not allowed
,
,
,
X,Q
Q,Q
X,
,
,
,
X,
,
,
,
X,
,
,
,
10  #starting score
1   #number of moves


VB.NET


問題 10 - 能夠撤銷操作 [10 分]

[編輯 | 編輯原始碼]

更改attemptPuzzle子程式,以便在迴圈中檢查symbolsLeft是否等於零之前,詢問使用者是否要撤銷其最後一步。警告他們,這將使他們損失 3 分。

如果玩家選擇撤銷

a.      將grid恢復到其原始狀態

b.      確保symbolsLeft具有正確的值

c.      確保score恢復到其原始值減去 3 分的撤銷懲罰

d. 確保對單元格的symbolsNotAllowed列表所做的任何更改都按要求撤銷

C#

        while (!Valid)
        {
            Console.Write("Enter column number: ");
            try
            {
                Column = Convert.ToInt32(Console.ReadLine());
                Valid = true;
            }
            catch
            {
            }
        }
        string Symbol = GetSymbolFromUser();
        SymbolsLeft -= 1;

        // change - required in case we need to undo
        int previousScore = Score;

        // this is where the game is updated
        Cell CurrentCell = GetCell(Row, Column);
        if (CurrentCell.CheckSymbolAllowed(Symbol))
        {
            CurrentCell.ChangeSymbolInCell(Symbol);
            int AmountToAddToScore = CheckForMatchWithPattern(Row, Column);
            if (AmountToAddToScore > 0)
            {
                Score += AmountToAddToScore;
            }
        }

        // changed code in AttemptPuzzle here
        DisplayPuzzle();
        Console.WriteLine("Current score: " + Score);

        Console.Write("Do you want to undo (cost 3 points)? y/n: ");
        string answer = Console.ReadLine();

        if (answer == "y" || answer == "Y")
        {
            // undo
            Cell currentCell = GetCell(Row, Column);
            currentCell.RemoveSymbol(Symbol);
            Score = previousScore - 3;
            SymbolsLeft += 1;
        }
        // end change

        if (SymbolsLeft == 0)
        {
            Finished = true;
        }



    }
    Console.WriteLine();
    DisplayPuzzle();
    Console.WriteLine();


    return Score;
}

// added to cell class so that the symbol can be removed if an
// undo is required
public virtual void RemoveSymbol(string SymbolToRemove)
{
    Symbol = "";
    SymbolsNotAllowed.Remove(SymbolToRemove);
}


Delphi/Pascal


Java

//Add two atributes in puzzle to store the start position of the last pattern matched
class Puzzle {

    private int score;
    private int symbolsLeft;
    private int gridSize;
    private List<Cell> grid;
    private List<Pattern> allowedPatterns;
    private List<String> allowedSymbols;
    private static Random rng = new Random();

    private int patternStartRow;
    private int patternStartColumn;

// Add a subroutine to the cell class to allow removal from the notAllowedSymbol list

    public void removeLastNotAllowedSymbols() {
        int size = symbolsNotAllowed.size();
        if (size > 0) {
            symbolsNotAllowed.remove(size - 1);
        }
    }

// Alter checkForMatchWithPattern to store the start row and column of any successfully matched pattern
//...

  if (p.matchesPattern(patternString, currentSymbol)) {
           patternStartRow = startRow;
           patternStartColumn = startColumn;
//...etc

//The altered attemptPuzzle subroutine
    public int attemptPuzzle() {
        boolean finished = false;
        while (!finished) {
            displayPuzzle();
            Console.writeLine("Current score: " + score);
            int row = -1;
            boolean valid = false;
            while (!valid) {
                Console.write("Enter row number: ");
                try {
                    row = Integer.parseInt(Console.readLine());
                    valid = true;
                } catch (Exception e) {
                }
            }
            int column = -1;
            valid = false;
            while (!valid) {
                Console.write("Enter column number: ");
                try {
                    column = Integer.parseInt(Console.readLine());
                    valid = true;
                } catch (Exception e) {
                }
            }

            //Set up variables to store the current game state in
            // case of an UNDO
            int undoScore = score;
            int undoSymbolsLeft = symbolsLeft;
            String undoSymbol = getCell(row, column).getSymbol();

            String symbol = getSymbolFromUser();
            symbolsLeft -= 1;
            Cell currentCell = getCell(row, column);
            if (currentCell.checkSymbolAllowed(symbol)) {
                currentCell.changeSymbolInCell(symbol);
                int amountToAddToScore = checkForMatchWithPattern(row, column);
                if (amountToAddToScore > 0) {
                    score += amountToAddToScore;
                }
            }

            //Prompt the user if they wish to undo
            Console.println(" Do you wish to undo your last move? It will cost you 3 points (y/n): ");
            String choice = Console.readLine();
            if (choice.equals("y")) {
                if (score != undoScore) { //A pattern has been matched
                    //The symbolsNotAllowed list may have changed for some cells - the current symbol needs 
                    //                              removing from the end of each list
                    getCell(patternStartRow, patternStartColumn).removeLastNotAllowedSymbols();
                    getCell(patternStartRow, patternStartColumn + 1).removeLastNotAllowedSymbols();
                    getCell(patternStartRow, patternStartColumn + 2).removeLastNotAllowedSymbols();
                    getCell(patternStartRow - 1, patternStartColumn + 2).removeLastNotAllowedSymbols();
                    getCell(patternStartRow - 2, patternStartColumn + 2).removeLastNotAllowedSymbols();
                    getCell(patternStartRow - 2, patternStartColumn + 1).removeLastNotAllowedSymbols();
                    getCell(patternStartRow - 2, patternStartColumn).removeLastNotAllowedSymbols();
                    getCell(patternStartRow - 1, patternStartColumn).removeLastNotAllowedSymbols();
                    getCell(patternStartRow - 1, patternStartColumn + 1).removeLastNotAllowedSymbols();
                }
                score = undoScore - 3;
                symbolsLeft = undoSymbolsLeft;
                currentCell.changeSymbolInCell(undoSymbol);
            }

            if (symbolsLeft == 0) {
                finished = true;
            }
        }
        Console.writeLine();
        displayPuzzle();
        Console.writeLine();
        return score;
    }


Python

    def AttemptPuzzle(self):
        Finished = False
        while not Finished:
            self.DisplayPuzzle()
            print("Current score: " + str(self.__Score))
            Row = -1
            Valid = False
            while not Valid:
                try:
                    Row = int(input("Enter row number: "))
                    if Row in range(1, self.__GridSize+1):
                        Valid = True
                except:
                    pass
            Column = -1
            Valid = False
            while not Valid:
                try:
                    Column = int(input("Enter column number: "))
                    if Column in range(1, self.__GridSize+1):
                        Valid = True
                except:
                    pass

            # CHANGES START HERE
            Symbol = self.__GetSymbolFromUser()
            undo_symbolsleft = self.__SymbolsLeft
            self.__SymbolsLeft -= 1
            CurrentCell = self.__GetCell(Row, Column)
            undo_cellsymbol = CurrentCell.GetSymbol()
            undo_score = self.__Score
            if CurrentCell.CheckSymbolAllowed(Symbol):
                CurrentCell.ChangeSymbolInCell(Symbol)
                AmountToAddToScore = self.CheckforMatchWithPattern(Row, Column)
                if AmountToAddToScore > 0:
                    self.__Score += AmountToAddToScore

            undo = input('Would you like to undo your move? You will lose 3 points. Y/N: ')
            if undo.upper() == 'Y':
                self.__Score = undo_score - 3
                self.__SymbolsLeft = undo_symbolsleft
                CurrentCell.ChangeSymbolInCell(undo_cellsymbol)
            # CHANGES END HERE

            if self.__SymbolsLeft == 0:
                Finished = True
        print()
        self.DisplayPuzzle()
        print()
        return self.__Score
    def AttemptPuzzle(self):
        Finished = False
        while not Finished:
            self.DisplayPuzzle()
            print("Current score: " + str(self.__Score))
            Row = -1
            Valid = False
            while not Valid:
                try:
                    Row = int(input("Enter row number: "))
                    Valid = True
                except:
                    pass
            Column = -1
            Valid = False
            while not Valid:
                try:
                    Column = int(input("Enter column number: "))
                    Valid = True
                except:
                    pass
            Symbol = self.__GetSymbolFromUser()
            CurrentCell = self.__GetCell(Row, Column)
            UndoList = self.SaveForUndo(Symbol, CurrentCell, Row, Column) # Changed
            if CurrentCell.CheckSymbolAllowed(Symbol):
                self.__SymbolsLeft -= 1 # Changed
                CurrentCell.ChangeSymbolInCell(Symbol)
                AmountToAddToScore = self.CheckforMatchWithPattern(Row, Column)
                if AmountToAddToScore > 0:
                    self.__Score += AmountToAddToScore
            print() # Changed
            self.DisplayPuzzle() # Changed
            print() # Changed
            Choice = input("Would you like to undo last move? (Y/N) ").lower() # Changed
            if Choice.lower() == "y": # Changed
                self.__SymbolsLeft = int(UndoList[0]) # Changed
                CurrentCell._Symbol = UndoList[2] # Changed
                self.__Score = int(UndoList[3]) - 3 # Changed
                for n in range(0, (len(self.__Grid)-1)): # Changed
                    if UndoList[1] in self.__Grid[n]._Cell__SymbolsNotAllowed: # Changed
                        self.__Grid[n].RemoveFromNotAllowedSymbols(UndoList[1]) # Changed
            if self.__SymbolsLeft == 0:
                Finished = True

#Added methods used in edited AttemptPuzzle

def SaveForUndo(self,Symbol, Cell, Row, Column):
        List = []
        List.append(str(self.__SymbolsLeft))
        List.append(str(Symbol))
        List.append(str(Cell._Symbol))
        List.append(str(self.__Score))
        for n in range(0, len(self.__Grid)):
            List.append(self.__Grid[n]._Cell__SymbolsNotAllowed)
        return List

def RemoveFromNotAllowedSymbols(self, SymbolToRemove):
    self.__SymbolsNotAllowed.remove(SymbolToRemove)


VB.NET

          Public Overridable Function AttemptPuzzle() As Integer
            Dim Finished As Boolean = False
            Dim CurrentCell As Cell
            Dim Symbol As String
            Dim previous_score As Integer
            While Not Finished
                DisplayPuzzle()
                Console.WriteLine("Current score: " & Score)
                Dim Valid As Boolean = False
                Dim Row As Integer = -1
                While Not Valid
                    Console.Write("Enter row number: ")
                    Try
                        Row = Console.ReadLine()
                        Valid = True
                    Catch
                    End Try
                End While
                Dim Column As Integer = -1
                Valid = False
                While Not Valid
                    Console.Write("Enter column number: ")
                    Try
                        Column = Console.ReadLine()
                        Valid = True
                    Catch
                    End Try
                End While
                Symbol = GetSymbolFromUser()
                SymbolsLeft -= 1

                'FIRST CHANGE HERE
                previous_score = Score

                CurrentCell = GetCell(Row, Column)
                If CurrentCell.CheckSymbolAllowed(Symbol) Then
                    CurrentCell.ChangeSymbolInCell(Symbol)
                    Dim AmountToAddToScore As Integer = CheckForMatchWithPattern(Row, Column)
                    If AmountToAddToScore > 0 Then
                        Score += AmountToAddToScore
                    End If
                End If

                'SECOND CHANGE HERE
                If previous_score >= 3 Then
                    Console.WriteLine("Current score: " & Score)
                    Console.WriteLine()
                    DisplayPuzzle()
                    Console.WriteLine()
                    Console.WriteLine("Do you want to undo the last change (cost 3 points)? (Y/N) ")
                    Dim answer_input As Char = UCase(Console.ReadLine())
                    If answer_input = "Y" Then
                        CurrentCell.RemoveSymbol(Symbol)
                        Score = previous_score - 3
                        SymbolsLeft += 1
                    End If
                End If
                'UNTIL HERE

                If SymbolsLeft = 0 Then
                    Finished = True
                End If
            End While
            Console.WriteLine()
            DisplayPuzzle()
            Console.WriteLine()


            Return Score
        End Function

    Class Cell
        Protected Symbol As String
        Private SymbolsNotAllowed As List(Of String)

        Sub New()
            Symbol = ""
            SymbolsNotAllowed = New List(Of String)
        End Sub

        'LAST CHANGE HERE
        Public Sub RemoveSymbol(Symbol_to_remove As String)
            Symbol = ""
            SymbolsNotAllowed.Remove(Symbol_to_remove)
        End Sub
        ' END OF CHANGE

...


問題 11 - 行和列條目的驗證 [5 分]

[編輯 | 編輯原始碼]

問題描述:驗證行和列編號條目,僅允許網格大小範圍內的數字。

C#

public virtual int AttemptPuzzle()
{
    bool Finished = false;
    while (!Finished)
    {
        DisplayPuzzle();
        Console.WriteLine("Current score: " + Score);
        bool Valid = false;
        int Row = -1;
        while (!Valid)
        {
            Console.Write("Enter row number: ");
            try
            {
                Row = Convert.ToInt32(Console.ReadLine());
                // change to validate row
                if (Row > 0 && Row <= GridSize)
                {
                    Valid = true;
                }
            }
            catch
            {
            }
        }
        int Column = -1;
        Valid = false;
        while (!Valid)
        {
            Console.Write("Enter column number: ");
            try
            {
                Column = Convert.ToInt32(Console.ReadLine());
                // validate column
                if (Column > 0 && Column <= GridSize)
                {
                    Valid = true;
                }

            }
            catch
            {
            }
        }


Delphi/Pascal


Java

    public int attemptPuzzle() {
        boolean finished = false;
        while (!finished) {
            displayPuzzle();
            Console.writeLine("Current score: " + score);
            int row = -1;
            boolean valid = false;
            while (!valid) {
                Console.write("Enter row number: ");
                try {
                    row = Integer.parseInt(Console.readLine());
                    if(row>=1&&row<=gridSize){ //new check
                        valid = true; 
                    }
                } catch (Exception e) {
                }
            }
            int column = -1;
            valid = false;
            while (!valid) {
                Console.write("Enter column number: ");
                try {
                    column = Integer.parseInt(Console.readLine());
                    if (column>=1&&column<=gridSize){ //new check
                        valid = true;
                    }
                } catch (Exception e) {
                }
            }
            String symbol = getSymbolFromUser();
            symbolsLeft -= 1;
//etc....


Python

def AttemptPuzzle(self):
        Finished = False
        while not Finished:
            self.DisplayPuzzle()
            print("Current score: " + str(self.__Score))
            Row = -1
            Valid = False
            while not Valid:
                Row = int(input("Enter row number: "))
                if Row > self.__GridSize or Row <= 0:
                    print("Invalid Row number\nPlease try again\n")
                    continue
                else:
                    Valid = True
            Column = -1
            Valid = False
            while not Valid:
                Column = int(input("Enter column number: "))
                if Column > self.__GridSize or Column <= 0:
                    print("Invalid Column number\nPlease try again\n")
                    continue
                else:
                    Valid = True
            Symbol = self.__GetSymbolFromUser()
            self.__SymbolsLeft -= 1
            CurrentCell = self.__GetCell(Row, Column)
            if CurrentCell.CheckSymbolAllowed(Symbol):
                CurrentCell.ChangeSymbolInCell(Symbol)
                AmountToAddToScore = self.CheckforMatchWithPattern(Row, Column)
                if AmountToAddToScore > 0:
                    self.__Score += AmountToAddToScore
            if self.__SymbolsLeft == 0:
                Finished = True
        print()
        self.DisplayPuzzle()
        print()
        return self.__Score


VB.NET

          Public Overridable Function AttemptPuzzle() As Integer
            Dim Finished As Boolean = False
            While Not Finished
                DisplayPuzzle()
                Console.WriteLine("Current score: " & Score)
                Dim Valid As Boolean = False
                Dim Row As Integer = -1
                While Not Valid
                    Console.Write("Enter row number: ")
                    'CHANGE HERE
                    Try
                        Row = Console.ReadLine()
                        If Row > 0 AndAlso Row <= GridSize Then
                            Valid = True
                        End If
                    Catch
                        'END CHANGE
                    End Try
                End While
                Dim Column As Integer = -1
                Valid = False
                While Not Valid
                    Console.Write("Enter column number: ")
                    'CHANGE HERE
                    Try
                        Column = Console.ReadLine()
                        If Column > 0 AndAlso Column <= GridSize Then
                            Valid = True
                        End If
                    Catch
                        'END CHANGE
                    End Try
                End While
                Dim Symbol As String = GetSymbolFromUser()
                SymbolsLeft -= 1
                Dim CurrentCell As Cell = GetCell(Row, Column)
                If CurrentCell.CheckSymbolAllowed(Symbol) Then
                    CurrentCell.ChangeSymbolInCell(Symbol)
                    Dim AmountToAddToScore As Integer = CheckForMatchWithPattern(Row, Column)
                    If AmountToAddToScore > 0 Then
                        Score += AmountToAddToScore
                    End If
                End If
                If SymbolsLeft = 0 Then
                    Finished = True
                End If
            End While
            Console.WriteLine()
            DisplayPuzzle()
            Console.WriteLine()
            Return Score
        End Function

問題 12 - 為什麼 UpdateCell() 為空且從未呼叫?

[編輯 | 編輯原始碼]

問題描述:目前,UpdateCell() 方法包含“pass”,並且在程式中的任何位置都沒有呼叫。這幾乎肯定是一個問題,否則他們為什麼要包含它呢?這可能與炸彈的想法有關,其中阻塞單元被炸燬,然後呼叫 UpdateCell() 將此阻塞單元修改為普通單元格。請建議此方法的其他用途。它可能用於將模式中的阻塞單元更改為普通單元格以完成模式。


UpdateCell() 可用於解鎖 3*3 網格,如果模式被破壞,則允許你替換符號。這還需要在模式被破壞後降低分數。

C#

GetCell() 沒有邏輯錯誤,以下摘錄將證明這一點

public virtual int AttemptPuzzle()
{
    bool Finished = false;
    while (!Finished)
    {
        DisplayPuzzle();

        // row
        for (int row = 8; row >= 1; row--)
        {
            for (int col = 1; col <= 8; col++)
            {
                Cell cell = GetCell(row, col);
                Console.Write(cell.GetSymbol() + " : ");
            }
            Console.Write(Environment.NewLine);
        }
但是,如果輸入了超出網格的行和列值,則會發生錯誤。請參閱問題 12 的解決方案以解決此問題。


Delphi/Pascal


Java


Python


VB.NET


問題 13 - 實現萬用字元 *

[編輯 | 編輯原始碼]

實現一個特殊的字元 *,它是萬用字元。萬用字元可以用來表示任何字元,以便用同一個單元格進行多次匹配。在遊戲開始時,給玩家 3 個隨機位置的萬用字元。

a) 修改標準 Puzzle 建構函式(不是載入遊戲建構函式)以呼叫 ChangeSymbolInCell,將 3 個隨機單元格傳遞給 * 作為新符號。請注意,阻塞單元格不能更改為萬用字元單元格,因此你需要新增程式碼以確保隨機選擇的單元格不是阻塞單元格。

b) 在 Cell 類中,修改方法。ChangeSymbolInCell 使得萬用字元單元格在設定後永遠不會從 * 更改其符號。在同一個類中,修改方法 CheckSymbolAllowed,使得萬用字元單元格始終返回 true。

c) 修改 Pattern 類中的 MatchesPattern 方法以允許新的萬用字元 * 正確操作。

d) 測試萬用字元是否可以在兩個不同的模式中成功匹配。

C#

class Puzzle
{
    // add property to Puzzle to give 3 wildcards
    private int NumWildcards = 3;


// ensure GetSymbolFromUser will accept wildcard
private string GetSymbolFromUser()
{
    string Symbol = "";
    // take into account the wildcard symbol
    while (!AllowedSymbols.Contains(Symbol) && Symbol != "*" && NumWildcards > 0)
    {
        Console.Write("Enter symbol: ");
        Symbol = Console.ReadLine();
    }

    // only allow three wildcards
    if (Symbol == "*")
    {
        NumWildcards--;
    }

    return Symbol;
}

// modify Matches Pattern
public virtual bool MatchesPattern(string PatternString, string SymbolPlaced)
{
    // ensure that wildcards are taken into account
    if (SymbolPlaced != Symbol && SymbolPlaced != "*")
    {
        return false;
    }
    for (var Count = 0; Count < PatternSequence.Length; Count++)
    {
        // ignore wildcard symbols as these all count
        if (PatternString[Count] == '*')
        {
            continue;
        }

        if (PatternSequence[Count].ToString() == Symbol && PatternString[Count].ToString() != Symbol)
        {
            return false;
        }
    }
    return true;
}


Delphi/Pascal


Java

//after the grid is initialised in puzzle:
        int gridLength = grid.size();
        for (int i=0;i<3;i++){
            //Get random cell
            int randcell = getRandomInt(0,gridLength-1);
            if (!grid.get(randcell).getSymbol().equals("@")){
                grid.get(randcell).changeSymbolInCell("*");
            }            
        }

// From Cell class: 
 public void changeSymbolInCell(String newSymbol) {
        if (!symbol.equals("*")){
            symbol = newSymbol;
        }
   }

 public boolean checkSymbolAllowed(String symbolToCheck) {
        if (!symbol.equals("*")){
            for (String item : symbolsNotAllowed) {
                if (item.equals(symbolToCheck)) {
                return false;
                }
            }
        }
        return true;                
    }

   //Pattern class

public boolean matchesPattern(String patternString, String symbolPlaced) {
        Console.println("This pattern sequence: "+patternSequence+ "Passed in PatternString: "+patternString+ "Symbol:"+ symbolPlaced);
        if (!symbolPlaced.equals(symbol)) {
            return false;
        } else {
            for (int count = 0; count < patternSequence.length(); count++) {
                if (patternSequence.charAt(count) == symbol.charAt(0) && patternString.charAt(count) != symbol.charAt(0)) {
                    if (patternString.charAt(count)!='*'){ //only return false if not a wildcard
                        return false;
                    }
                }
            }
        }
        return true;
    }


Python

更改編號 1

while self.__wildcards_left > 0

   SymbolGridCheck = self.__Grid[random.randint(0, len(self.__Grid))]
   if SymbolGridCheck.GetSymbol() != "W":
       SymbolGridCheck.ChangeSymbolInCell("W")
       self.__wildcards_left -= 1

更改編號 2

def MatchesPattern(self, PatternString, SymbolPlaced)

       if self.__Symbol == "W":
           ...
       elif SymbolPlaced != self.__Symbol:
           return False
       for Count in range(0, len(self.__PatternSequence)):
           try:
               if self.__PatternSequence[Count] == self.__Symbol and PatternString[Count] == "W":
                   ...
               elif self.__PatternSequence[Count] == self.__Symbol and PatternString[Count] != self.__Symbol:
                   return False
           except Exception as ex:
               print(f"EXCEPTION in MatchesPattern: {ex}")
       return True

更改編號 3

def ChangeSymbolInCell(self, NewSymbol)

       if self._Symbol == "W":
           ...
       else:
           self._Symbol = NewSymbol

def CheckSymbolAllowed(self, SymbolToCheck)

       for Item in self.__SymbolsNotAllowed:
           if Item == "W":
               ...
           elif Item == SymbolToCheck:
               return False
       return True
由 Sami Albizreh


VB.NET


問題 14 - 程式允許使用者替換已放置的符號 [9 分]

[編輯 | 編輯原始碼]

使用者可以替換已放置的符號和模式,並且不會失去分數(可以透過阻止他們替換來修復,或者讓他們失去被替換模式的分數)。

C#


Delphi/Pascal


Java


Python

    def AttemptPuzzle(self):
        Finished = False
        while not Finished:
            self.DisplayPuzzle()
            print("Current score: " + str(self.__Score))
            Row = -1
            Valid = False
            while not Valid:
                try:
                    Row = int(input("Enter row number: "))
                    Valid = True
                except:
                    pass
            Column = -1
            Valid = False
            while not Valid:
                try:
                    Column = int(input("Enter column number: "))
                    Valid = True
                except:
                    pass
            Symbol = self.__GetSymbolFromUser()
            self.__SymbolsLeft -= 1
            CurrentCell = self.__GetCell(Row, Column)
            if CurrentCell.CheckSymbolAllowed(Symbol) and CurrentCell.GetSymbol() == "-": #And added to check that the cell is empty so that cells cannot be placed on top of each other
                CurrentCell.ChangeSymbolInCell(Symbol)
                AmountToAddToScore = self.CheckforMatchWithPattern(Row, Column)
                if AmountToAddToScore > 0:
                    self.__Score += AmountToAddToScore
            if self.__SymbolsLeft == 0:
                Finished = True
        print()
        self.DisplayPuzzle()
        print()
        return self.__Score


VB.NET


問題 15 - 程式允許使用者建立自己的模式和符號 [6 分]

[編輯 | 編輯原始碼]

問題描述

1) 要求使用者建立自己的符號

2) 要求與符號關聯的模式

3) 為使用者輸出一個空的網格,以便使用者可以輸入任何座標來建立自己的模式

4) 確保程式可以驗證新符號和模式

編輯:這將涉及更改文字檔案或建立新文字檔案 - AQA 從未告訴學生做任何與文字檔案相關的事情。

C#


Delphi/Pascal


Java


Python

# Change to the AttemptPuzzle function 
    def AttemptPuzzle(self):
        Finished = False
        while not Finished:
            self.DisplayPuzzle()
            print("Current score: " + str(self.__Score))
            # Change
            CreatePattern = input('Would you like to make your own pattern? (y/n)\n').lower()
            if CreatePattern == 'y':
                self.makeNewPattern()
            # End


# Creation of new function in the Pattern class
# Change
    def makeNewPattern(self): # function is used to create new 3x3 patterns
        symbolAllowed = False
        while symbolAllowed != True:
            newSymbol = input('Please enter a symbol you would like to add to the game:\n').upper()
            if len(newSymbol) == 1: # making sure the length of the symbol entered is 1
                symbolAllowed = True
            else:
                pass
        patternAllowed = False
        while patternAllowed != True:
            newPattern = input('Please enter the new pattern (3x3):\n').upper()
            new = True
            for i in newPattern:
                if i != f'{newSymbol}' and i != '*': # the code checks if the pattern only contains * and the symbol chosen
                    new = False
            if len(newPattern) != 9: # making sure a 3x3 pattern is chosen
                new = False
            if new == True:
                patternAllowed = True
        patternName = Pattern(f'{newSymbol}',f'{newPattern}')
        print(patternName.GetPatternSequence())
        self.__AllowedPatterns.append(patternName)
        self.__AllowedSymbols.append(newSymbol) 
        # code above is the same as in the __init__() section and adds the new patterns to the allowed patterns list
        print('Would you like to make another pattern? (y/n)\n')
        choice = input().lower()
        if choice == 'y':
            self.makeNewPattern()
    # End


VB.NET


問題 16 - 製作難度等級程式

[編輯 | 編輯原始碼]

問題描述

1) 該程式可以儲存每場比賽的記錄,包括分數、剩餘符號數量、完成時間和原始的空網格。

2) 使用這些資訊製作一個難度等級排行榜,以便使用者可以檢視他們的等級並選擇他們想要玩的遊戲。

C#


Delphi/Pascal


Java


Python


VB.NET


問題 19 - 高階萬用字元 [13 分]

[編輯 | 編輯原始碼]

此問題涉及 Puzzle 類。要向遊戲中新增一個新的萬用字元選項。當玩家使用此選項時,他們將有機會透過覆蓋現有符號來完成模式,從而形成該模式。萬用字元在一場比賽中只能使用一次。

任務 1

在每個回合開始之前,為使用者新增一個新的選項。應該詢問使用者“是否要使用萬用字元(Y/N)”?如果使用者回答“Y”,則行、列和符號將照常獲取,然後呼叫新的方法 ApplyWildcard,並且在後續回合中不再顯示使用萬用字元的提示。如果使用者回答“N”,則謎題照常繼續。

任務 2

建立一個名為 ApplyWildcard 的新方法,該方法將以行、列和符號作為引數,並執行以下操作

1. 確定在給定傳遞給它的行、列和符號的情況下,模式是否可以在 3x3 中完成。

a) 如果可以建立模式,則應使用 Cell 類中的 UpdateCell() 方法更新模式中的單元格,併為移動新增 5 分。

b) 如果無法建立模式,則應向用戶顯示訊息“抱歉,萬用字元不適用於此單元格 - 您沒有剩餘的萬用字元”。

C#


Delphi/Pascal


Java


Python

class Puzzle():
    def __init__(self, *args):
        if len(args) == 1:
            self.__Score = 0
            self.__SymbolsLeft = 0
            self.__GridSize = 0
            self.__Grid = []
            self.__AllowedPatterns = []
            self.__AllowedSymbols = []
            self.__LoadPuzzle(args[0])
            # Change 
            self.__WildCard = False
            # End
        else:
            self.__Score = 0
            self.__SymbolsLeft = args[1]
            self.__GridSize = args[0]
            self.__Grid = []
            # Change
            self.__WildCard = False
            # End
            for Count in range(1, self.__GridSize * self.__GridSize + 1):
                if random.randrange(1, 101) < 90:
                    C = Cell()
                else:
                    C = BlockedCell()
                self.__Grid.append(C)
            self.__AllowedPatterns = []
            self.__AllowedSymbols = []
            QPattern = Pattern("Q", "QQ**Q**QQ")
            self.__AllowedPatterns.append(QPattern)
            self.__AllowedSymbols.append("Q")
            XPattern = Pattern("X", "X*X*X*X*X")
            self.__AllowedPatterns.append(XPattern)
            self.__AllowedSymbols.append("X")
            TPattern = Pattern("T", "TTT**T**T")
            self.__AllowedPatterns.append(TPattern)
            self.__AllowedSymbols.append("T")


# Altercation of attempt puzzle class to ask the user if they would like to use their wildcard
    def AttemptPuzzle(self):
        Finished = False
        while not Finished:
            self.DisplayPuzzle()
            print("Current score: " + str(self.__Score))
            # Change
            wild = False
            if self.__WildCard == False:
                useWildCard = input('Would you like to use your wildcard (Y/N)?\n').upper()
                if useWildCard == 'Y':
                    self.__WildCard = True
                    wild = True
            Row = -1
            Valid = False
            while not Valid:
                try:
                    Row = int(input("Enter row number: "))
                    Valid = True
                except:
                    pass
            Column = -1
            Valid = False
            while not Valid:
                try:
                    Column = int(input("Enter column number: "))
                    Valid = True
                except:
                    pass
            Symbol = self.__GetSymbolFromUser()
            self.__SymbolsLeft -= 1
            if wild == False:
                CurrentCell = self.__GetCell(Row, Column)
                if CurrentCell.CheckSymbolAllowed(Symbol):
                    CurrentCell.ChangeSymbolInCell(Symbol)
                    AmountToAddToScore = self.CheckforMatchWithPattern(Row, Column)
                    if AmountToAddToScore > 0:
                        self.__Score += AmountToAddToScore
            elif wild == True:
                AmountToAddToScore = self.ApplyWildCard(Row,Column,Symbol)
                if AmountToAddToScore > 0:
                    self.__Score += AmountToAddToScore
            # End
            if self.__SymbolsLeft == 0:
                Finished = True
        print()
        self.DisplayPuzzle()
        print()
        return self.__Score


# Change - new function created to check if the symbol added is allowed and will create a new symbol
    def ApplyWildCard(self, Row, Column, Symbol):
        # Assuming the wildcard cannot be placed on a blocked cell as does not state
        currentCell = self.__GetCell(Row,Column)
        if currentCell.GetSymbol() != BlockedCell():
            currentCell.ChangeSymbolInCell(Symbol)

        for StartRow in range(Row + 2, Row - 1, -1):
            for StartColumn in range(Column - 2, Column + 1):
                try:
                    PatternString = ""
                    PatternString += self.__GetCell(StartRow, StartColumn).GetSymbol()
                    PatternString += self.__GetCell(StartRow, StartColumn + 1).GetSymbol()
                    PatternString += self.__GetCell(StartRow, StartColumn + 2).GetSymbol()
                    PatternString += self.__GetCell(StartRow - 1, StartColumn + 2).GetSymbol()
                    PatternString += self.__GetCell(StartRow - 2, StartColumn + 2).GetSymbol()
                    PatternString += self.__GetCell(StartRow - 2, StartColumn + 1).GetSymbol()
                    PatternString += self.__GetCell(StartRow - 2, StartColumn).GetSymbol()
                    PatternString += self.__GetCell(StartRow - 1, StartColumn).GetSymbol()
                    PatternString += self.__GetCell(StartRow - 1, StartColumn + 1).GetSymbol()
                    print(PatternString)
                    for P in self.__AllowedPatterns:
                        CurrentSymbol = self.__GetCell(Row, Column).GetSymbol()
                        if P.MatchesPattern(PatternString, CurrentSymbol):
                            self.__GetCell(StartRow, StartColumn).AddToNotAllowedSymbols(CurrentSymbol)
                            self.__GetCell(StartRow, StartColumn + 1).AddToNotAllowedSymbols(CurrentSymbol)
                            self.__GetCell(StartRow, StartColumn + 2).AddToNotAllowedSymbols(CurrentSymbol)
                            self.__GetCell(StartRow - 1, StartColumn + 2).AddToNotAllowedSymbols(CurrentSymbol)
                            self.__GetCell(StartRow - 2, StartColumn + 2).AddToNotAllowedSymbols(CurrentSymbol)
                            self.__GetCell(StartRow - 2, StartColumn + 1).AddToNotAllowedSymbols(CurrentSymbol)
                            self.__GetCell(StartRow - 2, StartColumn).AddToNotAllowedSymbols(CurrentSymbol)
                            self.__GetCell(StartRow - 1, StartColumn).AddToNotAllowedSymbols(CurrentSymbol)
                            self.__GetCell(StartRow - 1, StartColumn + 1).AddToNotAllowedSymbols(CurrentSymbol)
                            print('Your wildcard has worked')
                            return 5
                except:
                    pass
        print('Sorry the wildcard does not work for this cell - you have no wildcards left')
        return 0
    # End


問題 20 - 打亂所有被遮蔽的單元格 [9 分]

[編輯 | 編輯原始碼]

實現一個功能,允許使用者打亂被遮蔽的單元格。

  • 新的被遮蔽單元格不能與它們之前的位置相同。
  • 它們不能與匹配的模式或放置的符號重疊。

Python

def AttemptPuzzle(self):
        #Start of Change
        Finished = False
        while not Finished:
            self.DisplayPuzzle()
            if input("Do you want to reshuffle all the blocked cells?[y/n]: ").lower() == 'y':
                self.ReShuffleBlockedCells()
                self.DisplayPuzzle()
        #End of Change

def ReShuffleBlockedCells(self): #I've done this by creating a new method in the Puzzle class
        indexstore = []
        for i, cell in enumerate(self.__Grid):
            if isinstance(cell, BlockedCell):
                indexstore.append(i)

        for num in indexstore:
            checker = True
            while checker:
                a = random.randint(1, (self.__GridSize**2)-1)
                if a not in indexstore:
                    if self.__Grid[a].IsEmpty():
                        checker = False
            self.__Grid[num] = Cell() 
            self.__Grid[a] = BlockedCell()

問題 21 - 挑戰選項 - 使用者必須放置的字母將被隨機生成,如果使用者成功完成則獲得積分,否則將失去積分(10 分)。

華夏公益教科書