A-level 计算机科学/AQA/试卷 1/程序框架/AS2022
AQA 计算机科学 9x9 游戏
这是针对 AQA AS 计算机科学规范。
这是可以就一些问题可能是什么以及如何解决它们提出建议的地方。
请尊重他人,不要破坏或篡改页面,因为这会影响学生备考。
在此详细描述问题
C#
//Edit starts line 284
if (row == 0)
{
Console.WriteLine("Invalid input for Row");
inputError = true;
}
if (column == 0)
{
Console.WriteLine("Invalid input for Column");
inputError = true;
}
C# (Dylan 的解决方案)
//Edit starts line 275
if(row == 0 || column == 0)
{
inputError = true;
}
Delphi/Pascal
Java
Python
#Edit starts at row 169 to 172!
if Row == 0 or Column == 0:
InputError = True
Python (Filip 的解决方案)
def SolvePuzzle(PuzzleGrid, Puzzle, Answer):
DisplayGrid(PuzzleGrid)
if PuzzleGrid[0][0] != 'X':
print("No puzzle loaded")
else:
print("Enter row column digit: ")
print("(Press Enter to stop)")
CellInfo = input()
while CellInfo != EMPTY_STRING:
InputError = False
########START########
if CellInfo[0] == str(0) or CellInfo[1] == str(0):
InputError = True
########END########
if len(CellInfo) != 3:
InputError = True
VB.NET
在此详细描述问题
C#
int count = 0;
for (int row = 1; row <= GRID_SIZE; row++)
{
for (int column = 1; column <= GRID_SIZE; column++)
{
if (puzzleGrid[row, column] == SPACE)
{
count++;
}
}
}
Console.WriteLine("number of grid spaces remaining " + count);
Delphi/Pascal
Java
Python
def SolvePuzzle(PuzzleGrid, Puzzle, Answer, Taken): #Instantiate variable taken as 28 in NumberPuzzle shown below
DisplayGrid(PuzzleGrid)
if PuzzleGrid[0][0] != 'X':
print("No puzzle loaded")
else:
print("Enter row column digit: ")
print("(Press Enter to stop)")
CellInfo = input()
while CellInfo != EMPTY_STRING:
InputError = False
if len(CellInfo) != 3:
InputError = True
else:
Digit = CellInfo[2]
try:
Row = int(CellInfo[0])
except:
InputError = True
try:
Column = int(CellInfo[1])
except:
InputError = True
if (Digit < '1' or Digit > '9'):
InputError = True
if InputError:
print("Invalid input")
else:
PuzzleGrid[Row][Column] = Digit
Answer[2] = str(int(Answer[2]) + 1)
Answer[int(Answer[2]) + 2] = CellInfo
DisplayGrid(PuzzleGrid)
grids = len(Puzzle)
Taken += 1
grids -= Taken
print("Number of spaces remaining:", grids, "/81")
print("Enter row column digit: ")
print("(Press Enter to stop)")
CellInfo = input()
return PuzzleGrid, Answer, Taken
def NumberPuzzle():
Taken = 28
Finished = False
...
elif MenuOption == 'S':
PuzzleGrid, Answer, Taken = SolvePuzzle(PuzzleGrid, Puzzle, Answer, Taken)
...
Python (更简单的解决方案)
def CheckNumberOfCellsLeft(PuzzleGrid):
"""
Iterate through the PuzzleGrid data structure, starting from PuzzleGrid[1].
Count how many empty spaces there are.
Do not consider the first row and column. They are empty in order for PuzzleGrid to be indexed as though the indices are directly translated into english.
"""
Count = 0
for i in range(1, len(PuzzleGrid)):
for j in range(1, 10):
if PuzzleGrid[i][j] == SPACE:
Count += 1
return Count
def CheckSolution(PuzzleGrid, Answer, Solution):
ErrorCount = 0
Solved = False
Correct = True
Incomplete = False
# New line:
NumOfCellsLeft = CheckNumberOfCellsLeft(PuzzleGrid)
for Row in range(1, GRID_SIZE + 1):
for Column in range(1, GRID_SIZE + 1):
# --snipped--
if not Correct:
print(f"You have made {ErrorCount} error(s)")
elif Incomplete:
print("So far so good, carry on")
elif Correct:
Solved = True
# New line:
print(f"You have {NumOfCellsLeft} cells left to fill.")
return ErrorCount, Solved
VB.NET
在此描述问题
C#
else
{
if(puzzleGrid[row, column] == SPACE)
{
puzzleGrid[row, column] = digit;
answer[2] = (Convert.ToInt32(answer[2]) + 1).ToString();
answer[Convert.ToInt32(answer[2]) + 2] = cellInfo;
DisplayGrid(puzzleGrid);
}
else
{
Console.WriteLine("location already contains number");
}
}
Console.WriteLine("Enter row column digit: ");
Console.WriteLine("(Press Enter to stop)");
cellInfo = Console.ReadLine();
Delphi/Pascal
Java
Python
def SolvePuzzle(PuzzleGrid, Puzzle, Answer):
DisplayGrid(PuzzleGrid)
print(PuzzleGrid)
if PuzzleGrid[0][0] != 'X':
print("No puzzle loaded")
else:
print("Enter row column digit: ")
print("(Press Enter to stop)")
CellInfo = input()
while CellInfo != EMPTY_STRING:
InputError = False
if len(CellInfo) != 3:
InputError = True
else:
Digit = CellInfo[2]
try:
Row = int(CellInfo[0])
except:
InputError = True
try:
Column = int(CellInfo[1])
except:
InputError = True
if (Digit < '1' or Digit > '9'):
InputError = True
if InputError:
print("Invalid input")
if Row < 1 or Row > 9 or Column < 1 or Column > 9:
print ("Invalid input")
#Edits Start Here
else:
if PuzzleGrid[Row][Column] == SPACE:
PuzzleGrid[Row][Column] = Digit
Answer[2] = str(int(Answer[2]) + 1)
Answer[int(Answer[2]) + 2] = CellInfo
DisplayGrid(PuzzleGrid)
else:
First_Time(PuzzleGrid, Answer, Puzzle, Row, Column)
#We Split This Up While Testing But This Can Also Be Done Within The First Else
return PuzzleGrid, Answer
def First_Time(PuzzleGrid, Answer, Puzzle, Row, Column):
if PuzzleGrid[0][0] == 'X':
PuzzleGrid2 = PuzzleGrid
PuzzleGrid[0][0] = 'Y'
return Check_Empty(PuzzleGrid, Answer, Puzzle, Row, Column)
def Check_Empty(PuzzleGrid, Answer, Puzzle, Row, Column):
if PuzzleGrid[Row][Column] == SPACE:
PuzzleGrid[Row][Column] = Digit
Answer[2] = str(int(Answer[2]) + 1)
Answer[int(Answer[2]) + 2] = CellInfo
DisplayGrid(PuzzleGrid)
else:
print ('ERROR SPOT ALREADY TAKEN')
SolvePuzzle(PuzzleGrid, Puzzle, Answer)
print("Enter row column digit: ")
print("(Press Enter to stop)")
CellInfo = input()
return PuzzleGrid, Answer
Python (替代解决方案)
def SolvePuzzle(PuzzleGrid, Puzzle, Answer):
"""
Added features:
ability to remove a number (original cells cannot removed)
cells cannot be overwritten
"""
DisplayGrid(PuzzleGrid)
if PuzzleGrid[0][0] != 'X':
print("No puzzle loaded")
else:
print("Enter row column digit: ")
print("(Press Enter to stop, R to remove a number)")
CellInfo = input()
while CellInfo != EMPTY_STRING:
InputError = False
# new lines:
if CellInfo == "R":
toRemove = True
CellInfo = input("Enter row column digit: ")
else:
toRemove = False
# original cells (stated in Puzzle) should not be removed
if CellInfo in Puzzle:
toRemove = False
InputError = True
if len(CellInfo) != 3:
InputError = True
else:
Digit = CellInfo[2]
try:
Row = int(CellInfo[0])
except:
InputError = True
try:
Column = int(CellInfo[1])
except:
InputError = True
if (Digit < '1' or Digit > '9'):
InputError = True
# new lines:
# does not allow cells to be overwitten
if InputError == False and toRemove == False and PuzzleGrid[Row][Column] != SPACE:
InputError = True
print("Spot taken by a digit.")
if InputError:
print("Invalid input")
# new lines for removal of a cell's digit
# toRemove is only True if the user enters R and if the chosen cell is not part of the original given set of digits which are stored in the Puzzle data structure
elif toRemove:
PuzzleGrid[Row][Column] = SPACE
DisplayGrid(PuzzleGrid)
else:
PuzzleGrid[Row][Column] = Digit
Answer[2] = str(int(Answer[2]) + 1)
Answer[int(Answer[2]) + 2] = CellInfo
DisplayGrid(PuzzleGrid)
print("Enter row column digit: ")
print("(Press Enter to stop, R to remove a number)")
CellInfo = input()
return PuzzleGrid, Answer
VB.NET
在此描述问题
C#
while (puzzle[count] != EMPTY_STRING)
{
if (puzzle[count].Substring(0, 2) == check)
{
fail = true;
}
count++;
}
if(fail == false)
{
puzzleGrid[row, column] = digit;
answer[2] = (Convert.ToInt32(answer[2]) + 1).ToString();
answer[Convert.ToInt32(answer[2]) + 2] = cellInfo;
DisplayGrid(puzzleGrid);
}
else
{
Console.WriteLine("cannot edit original value");
}
Delphi/Pascal
Java
Python
##============================================================
def LockStartNumbers(Puzzle, Row, Column, InputError):
PuzzleV2 = []
for ele in Puzzle:
if ele.strip():
PuzzleV2.append(ele)
for i in range(len(PuzzleV2)):
if int(PuzzleV2[i][0]) == int(Row) and int(PuzzleV2[i][1]) == int(Column):
InputError = True
Row = 0
Column = 0
return Puzzle, Row, Column, InputError
##============================================================
def SolvePuzzle(PuzzleGrid, Puzzle, Answer):
DisplayGrid(PuzzleGrid)
if PuzzleGrid[0][0] != 'X':
print("No puzzle loaded")
else:
print("Enter row column digit: ")
print("(Press Enter to stop)")
CellInfo = input()
while CellInfo != EMPTY_STRING:
InputError = False
if len(CellInfo) != 3:
InputError = True
else:
Digit = CellInfo[2]
try:
Row = int(CellInfo[0])
except:
InputError = True
try:
Column = int(CellInfo[1])
except:
InputError = True
if (Digit < '1' or Digit > '9'):
InputError = True
#===============================================================
Puzzle, Row, Column, InputError = LockStartNumbers(Puzzle, Row, Column, InputError)
#===============================================================
VB.NET
在此描述问题
C#
Delphi/Pascal
Java
Python
def SolvePuzzle(PuzzleGrid, Puzzle, Answer):
DisplayGrid(PuzzleGrid)
if PuzzleGrid[0][0] != 'X':
print("No puzzle loaded")
else:
print("Enter row column digit: ")
print("(Press Enter to stop)")
CellInfo = input()
while CellInfo != EMPTY_STRING:
InputError = False
############## New code here ################
for coords in Puzzle:
InputError = True if coords[:2] == CellInfo[:2] else InputError
############### End ###################
if len(CellInfo) != 3:
InputError = True
else:
Digit = CellInfo[2]
VB.NET
在此描述问题
C#
Delphi/Pascal
Java
Python
VB.NET
在此描述问题
C#
private static void SolvePuzzle(char[,] puzzleGrid, string[] puzzle, string[] answer)
{
int row = 0, column = 0;
char digit = ' ';
DisplayGrid(puzzleGrid);
if (puzzleGrid[0, 0] != 'X')
{
Console.WriteLine("No puzzle loaded");
}
else
{
Console.WriteLine("Enter row column digit: ");
Console.WriteLine("(Press Enter to stop)");
string cellInfo = Console.ReadLine();
while (cellInfo != EMPTY_STRING)
{
bool inputError = false;
//new code
foreach (var coords in puzzle)
{
if (coords[2] == cellInfo[2])
{
inputError = true;
}
}
//end of new code
if (cellInfo.Length != 3)
{
inputError = true;
}
Delphi/Pascal
Java
Python
def SolvePuzzle(PuzzleGrid, Puzzle, Answer):
DisplayGrid(PuzzleGrid)
if PuzzleGrid[0][0] != 'X':
print("No puzzle loaded")
else:
print("Enter row column digit: ")
print("(Press Enter to stop)")
CellInfo = input()
while CellInfo != EMPTY_STRING:
InputError = False
############## New code here ################
for coords in Puzzle:
if coords[:2] == CellInfo[:2]:
InputError = True
############### End ###################
if len(CellInfo) != 3:
InputError = True
else:
Digit = CellInfo[2]
VB.NET
在此描述问题
C#
Delphi/Pascal
Java
Python
VB.NET
询问用户是否要覆盖他们的保存,以防止他们意外覆盖文件。
C#
private static void KeepPuzzle(char[,] puzzleGrid, string[] answer)
{
if (puzzleGrid[0, 0] != 'X')
{
Console.WriteLine("No puzzle loaded");
}
else
{
if (Convert.ToInt32(answer[2].ToString()) > 0)
{
string puzzleName = answer[0];
using (StreamWriter fileOut = new StreamWriter(puzzleName + "P.txt"))
{
// new code
Console.WriteLine("Do you want to overwrite the existing puzzle? {y/n)? ");
string question = Console.ReadLine();
if (question == "N" || question == "n")
{
Console.WriteLine("The file has not been saved");
return;
}
// end of new code
for (int line = 0; line < Convert.ToInt32(answer[2].ToString()) + 3; line++)
{
fileOut.WriteLine(answer[line]);
}
}
}
else
{
Console.WriteLine("No answers to keep");
}
}
}
Delphi/Pascal
Java
Python
^^
from os.path import exists
def KeepPuzzle(PuzzleGrid, Answer, PuzzleName):
if PuzzleGrid[0][0] != 'X':
print("No puzzle loaded")
else:
if int(Answer[2]) > 0:
############NEW CODE############
if exists(f"{PuzzleName}P.txt"):
question = input("Do you want to overwrite the existing puzzle? {y/n)? ")
if question == "N" or question == "n":
print("The file has not been saved")
return
############NEW CODE############
PuzzleName = Answer[0]
FileOut = open(f"{PuzzleName}P.txt", 'w')
for Line in range(int(Answer[2]) + 3):
FileOut.write(Answer[Line])
FileOut.write('\n')
FileOut.close()
else:
print("No answers to keep")
VB.NET
在此描述问题
C#
Delphi/Pascal
Java
Python
VB.NET
检查输入的数字是否已存在于该行、该列或该坐标中
[ACH]
C#
private static void SolvePuzzle(char[,] puzzleGrid, string[] puzzle, string[] answer)
{
int row = 0, column = 0;
char digit = ' ';
DisplayGrid(puzzleGrid);
if (puzzleGrid[0, 0] != 'X')
{
Console.WriteLine("No puzzle loaded");
}
else
{
Console.WriteLine("Enter row column digit: ");
Console.WriteLine("(Press Enter to stop)");
string cellInfo = Console.ReadLine();
while (cellInfo != EMPTY_STRING)
{
bool inputError = false;
if (cellInfo.Length != 3)
{
inputError = true;
}
else
{
digit = cellInfo[2];
try
{
row = Convert.ToInt32(cellInfo[0].ToString());
}
catch (Exception)
{
inputError = true;
}
try
{
column = Convert.ToInt32(cellInfo[1].ToString());
}
catch (Exception)
{
inputError = true;
}
if (digit < '1' || digit > '9')
{
inputError = true;
}
}
// Call CheckValidMove() To see if we are allowed to add the number in the spot provided
if (CheckValidMove(row, column, digit, puzzleGrid) == false)
{
inputError = true;
}
// End of Added Section
if (inputError)
{
Console.WriteLine("Invalid input");
}
else
{
puzzleGrid[row, column] = digit;
answer[2] = (Convert.ToInt32(answer[2]) + 1).ToString();
answer[Convert.ToInt32(answer[2]) + 2] = cellInfo;
DisplayGrid(puzzleGrid);
}
Console.WriteLine("Enter row column digit: ");
Console.WriteLine("(Press Enter to stop)");
cellInfo = Console.ReadLine();
}
}
}
/* Check for Valid move
* Check to see if the number we are entering already exists in the Row / Column / Grid
* row, columm, digit are determined during the solvepuzzle method. PuzzleGrid is passed by reference as it's an array.
* Note When checking the Grid we rely upon the fact that c# does integer division by default when using 2 integers
*/
private static bool CheckValidMove(int row, int col, char digit, char[,] puzzleGrid)
{
bool valid = true;
// Check Row
for (int i=1; i<= 9; i++ )
{
if (puzzleGrid[row, i] == digit)
{
valid = false;
Console.WriteLine("{0} already exists in that row", digit);
}
}
// Check Column
for (int i = 1; i <= 9; i++)
{
if (puzzleGrid[i, col] == digit)
{
valid = false;
Console.WriteLine("{0} already exists in that column", digit);
}
}
// Check Grid
int rowstart = (row-1) / 3; // Division of ints gives integer division. e.g. 4/3 = 1
int colstart = (col-1) / 3;
for (int i=0; i<3; i++)
{
for (int j=0; j<3; j++)
{
if (puzzleGrid[rowstart*3 + i, colstart*3 + j] == digit)
{
valid = false;
Console.WriteLine("{0} already exists in that box", digit);
}
}
}
return valid;
}
Bradleys 代码 ☺
Python
def SolvePuzzle(PuzzleGrid, Puzzle, Answer):
DisplayGrid(PuzzleGrid)
if PuzzleGrid[0][0] != 'X':
print("No puzzle loaded")
else:
print("Enter row column digit: ")
print("(Press Enter to stop)")
CellInfo = input()
while CellInfo != EMPTY_STRING:
InputError = False
if len(CellInfo) != 3:
InputError = True
else:
Digit = CellInfo[2]
try:
Row = int(CellInfo[0])
except:
InputError = True
try:
Column = int(CellInfo[1])
except:
InputError = True
if (Digit < '1' or Digit > '9'):
InputError = True
#==============Entered Function==============#
if CheckIfEntered(PuzzleGrid, Row, Column, Digit):
InputError = True
if InputError:
print("Invalid input")
else:
PuzzleGrid[Row][Column] = Digit
Answer[2] = str(int(Answer[2]) + 1)
Answer[int(Answer[2]) + 2] = CellInfo
DisplayGrid(PuzzleGrid)
print("Enter row column digit: ")
print("(Press Enter to stop)")
CellInfo = input()
return PuzzleGrid, Answer
#==============Function==============#
def CheckIfEntered(PuzzleGrid, Row, Column, Digit):
if PuzzleGrid[Row][Column] == Digit:
return True
在此描述问题
C#
private static void CheckSolution(char[,] puzzleGrid, string[] answer, string[] solution, ref int errorCount, ref bool solved, ref int correctCount, string[] puzzle)
{
bool correct = true, incomplete = false;
char entry;
string rowColDigit;
int count = 3;
errorCount = 0;
correctCount = 0;
solved = false;
for (int row = 1; row <= GRID_SIZE; row++)
{
for (int column = 1; column <= GRID_SIZE; column++)
{
entry = puzzleGrid[row, column];
rowColDigit = row.ToString() + column.ToString() + entry.ToString();
Console.WriteLine(rowColDigit);
if (entry == SPACE)
{
incomplete = true;
}
// new code starts
if ((entry == solution[row][column]) && (rowColDigit == answer[count]))
{
correctCount++;
Console.WriteLine(correctCount);
if (count < 28)
{
count++;
}
}
// new code ends
if (!((entry == solution[row][column]) || (entry == SPACE)))
{
correct = false;
errorCount++;
Console.WriteLine($"You have made an error in row {row} column {column}");
}
}
}
if (!correct)
{
Console.WriteLine($"You have made {errorCount} error(s)");
//
Console.WriteLine("You have got {0} coordinates correct", correctCount);
}
else if (incomplete)
{
Console.WriteLine("So far so good, carry on");
}
else if (correct)
{
solved = true;
}
}
private static void CalculateScore(string[] answer, int errorCount, int correctCount)
{
answer[1] = (Convert.ToInt32(answer[1]) - errorCount + correctCount).ToString();
// add correctCount to the score value
}
Delphi/Pascal
Java
Python
VB.NET
在此描述问题
C#
Delphi/Pascal
Java
Python
VB.NET
在此描述问题
C#
Delphi/Pascal
Java
Python
大 H
def RevealItem(coordinate, flaggedLocations, puzzleGrid, solution):
grids = {("11", "12", "13", "21", "22", "23", "31", "32", "33"): 0,
("14", "15", "16", "24", "25", "26", "34", "35", "36"): 1,
("17", "18", "19", "27", "28", "29", "37", "38", "39"): 2,
("41", "42", "43", "51", "52", "53", "61", "62", "63"): 3,
("44", "45", "46", "54", "55", "56", "64", "65", "66"): 4,
("47", "48", "49", "57", "58", "59", "67", "68", "69"): 5,
("71", "72", "73", "81", "82", "83", "91", "92", "93"): 6,
("74", "75", "76", "84", "85", "86", "94", "95", "96"): 7,
("77", "78", "79", "87", "88", "89", "97", "98", "99"): 8}
row, col = coordinate[0], coordinate[1]
# find what grid the user has asked for given a key by looping through every key and checking if it is in the corresponding tuple
for key in grids:
if coordinate in key:
if grids[key] in flaggedLocations:
print("You have already done a hint in that grid you daft egg! Honestly...")
return puzzleGrid, flaggedLocations
flaggedLocations.append(grids[key])
break
puzzleGrid[int(row)][int(col)] = solution[int(row)][int(col)]
print("Revealed a hint ooooh!")
return puzzleGrid, flaggedLocations
# called in "NumberPuzzle"
coordinate = str(input("Coordinate: "))
PuzzleGrid, flaggedLocations = RevealItem(coordinate, flaggedLocations, PuzzleGrid, Solution)
VB.NET
可以帮助理解代码结构,对于回答 B 部分问题很有用。