Jump to content

A-level Computing/AQA/Paper 1/Skeleton program/AS2020

From Wikibooks, open books for an open world

This is the AQA Computer Science Paper 1 discussion page, please do not vandalise the page as students use this for revision. Be sensible. Respect the page.


Possible questions based on the current ASCII Art scenario:

Change Display Error sub routine to allow "codes"

[edit | edit source]

Change the display error subroutine to allow text error messages to replaced by codes. For extensions you may add alternative or new error codes.

Python:

def DisplayError(ErrorMessage_code):
  Error_messages = ["Image Data Error", "File not found error", "unknown error"]
  print("Error: ", Error_messages[ErrorMessage_code])


def LoadFile(Grid, Header):
  FileFound = False
  FileTypeOK = False
  FileName = input("Enter filename to load: ")
  try:
    FileIn = open(FileName + ".txt", 'r')
    FileFound = True
    HeaderLine = FileIn.readline()
    Fields = HeaderLine.split(',')
    Header.Title = Fields[0]
    Header.Width = int(Fields[1])
    Header.Height = int(Fields[2])
    Header.FileType = Fields[3]
    Header.FileType = Header.FileType[0]
    if Header.FileType == 'A':  
      Grid = LoadAsciiImage(FileIn, Grid, Header)
      FileTypeOK = True
    elif Header.FileType == 'G': 
      Grid = LoadGreyScaleImage(FileIn, Grid, Header)
      FileTypeOK = True
    FileIn.close()
    if not FileTypeOK:
      '''DisplayError(2)'''
    else:
      DisplayImage(Grid, Header)
  except:
    if not FileFound:
      '''DisplayError(2)'''
    else:
      '''DisplayError(2)'''
  return Grid, Header


Java:

  void displayError(int errorcode) {
        String[] errors = new String[] {"Image Data Error","Unknown File Type","File not found", "Unknown Error"};
        Console.writeLine("Error: " + errors[errorcode]);
    }

void loadFile(String[][] grid, FileHeader header) {
        boolean fileFound = false;
        boolean fileTypeOK = false;
        Console.write("Enter filename to load: ");
        String fileName = Console.readLine();
        try {
            BufferedReader fileIn = new BufferedReader(new FileReader(fileName + ".txt"));
            fileFound = true;
            String headerLine = fileIn.readLine();
            String[] fields = headerLine.split(",");
            header.title = fields[0];
            header.width = Integer.parseInt(fields[1]);
            header.height = Integer.parseInt(fields[2]);
            header.fileType = fields[3];
            header.fileType = header.fileType.charAt(0) + "";
            if (header.fileType.equals("A")) { 
                loadAsciiImage(fileIn, grid, header);
                fileTypeOK = true;
            } else if ( header.fileType.equals("G")){
                loadGreyScaleImage(fileIn, grid, header);
                fileTypeOK = true;
            }
            fileIn.close();
            if (!fileTypeOK) {
                displayError(1); /// error code
            } else {
                displayImage(grid, header);
            }
        } catch (IOException e) {
            if (!fileFound) {
                displayError(1);  // error code
            } else {
                displayError(2);  // error code
            }
        }
    }


Give the option to enlarge image

[edit | edit source]

Add another menu option to scale up an image as specified by the user.

Python:

def enlarge (Grid, Header):

  scale = int(input('Please enter scale 2 and above'))

  NewGrid = [['' for Column in range(Header.Width*scale)] for Row in range(Header.Height * scale)]

  for Row in range(Header.Height):
    for count1 in range(scale):
      for Column in range(Header.Width):
        for count2 in range(scale):
          NewGrid[(Row*scale)+count1][(Column*scale)+count2] = Grid[Row][Column]


  Header.Width = Header.Width * scale
  Header.Height = Header.Height * scale
  return NewGrid, Header

def DisplayMenu():
  print()
  print("Main Menu")
  print("=========")
  print("L - Load graphics file") 
  print("D - Display image")
  print("E - Edit image")
  print("S - Save image")
  print("C - Scale file")
  print("X - Exit program") 
  print()

def Graphics():
  Grid = [['' for Column in range(MAX_WIDTH)] for Row in range(MAX_HEIGHT)]
  Grid = ClearGrid(Grid)
  Header = FileHeader()
  ProgramEnd = False
  while not ProgramEnd:
    DisplayMenu()
    MenuOption = GetMenuOption()
    if MenuOption == 'L':
      Grid, Header = LoadFile(Grid, Header)
    elif MenuOption == 'D':
      DisplayImage(Grid, Header) 
    elif MenuOption == 'E':
      Grid = EditImage(Grid, Header) 
    elif MenuOption == 'S':    
      SaveImage(Grid, Header)
    elif MenuOption == 'C':
      print(Header.Width)
      Grid, Header = enlarge(Grid, Header)
      print (Header.Width)
    elif MenuOption == 'X':
      ProgramEnd = True
    else:
      print("You did not choose a valid menu option. Try again")
  print("You have chosen to exit the program")
  Answer = input("Do you want to save the image as a graphics file? (Y/N) ")
  if Answer == "Y" or Answer == "y":
    SaveFile(Grid, Header)


Saving Image as ASCII or Graphics

[edit | edit source]

Change the SaveFile subroutine to allow Graphics or ASCII files to be saved.

Python:

def SaveFile(Grid, Header):
  FileName = input("Enter filename: ")
  FileOut = open(FileName + ".txt", 'w')
  FileOut.write(Header.Title + ',' + str(Header.Width) + ',' + str(Header.Height) + ',' + Header.FileType + '\n')  ### added Header.FileType
  for Row in range(Header.Height):
    for Column in range(Header.Width):
      if Header.FileType == 'A':
        FileOut.write(Grid[Row][Column])
      else:
        FileOut.write(convertInteger(Grid[Row][Column])) ### created subroutine to convert "ASCII" into "INTEGER GRAPHCICS", only work if ASCII characters not changed. Use ASCII Values?
        FileOut.write('\n')

  FileOut.close()


def convertInteger(char):
  if char == '#':
    PixelValue = 32
  elif char =='&':
    PixelValue = 64
  elif char == "+":
    PixelValue = 96
  elif char == ";":
    PixelValue = 128
  elif char == ":":
    PixelValue = 160
  elif char == ",":
    PixelValue = 192
  elif char == ".":
    PixelValue = 224
  else:
    PixelValue = 255
  return PixelValue


Java:

   void saveFile(String[][] grid, FileHeader header) {
        Console.write("Enter filename: ");
        String fileName = Console.readLine();
        try {
            BufferedWriter fileOut = new BufferedWriter(new FileWriter(fileName + ".txt"));
            fileOut.write(header.title + "," + header.width + "," + header.height + "," + header.fileType + "\n");
            for (int row = 0; row < header.height; row++) {
                for (int column = 0; column < header.width; column++) {
                    if (header.fileType == "A") {
                        fileOut.write(grid[row][column]);
                    } else {
                        fileOut.write(convertInteger(grid[row][column]));
                    }
                    fileOut.write(grid[row][column]);
                }
            }
            fileOut.close();            
        } catch (IOException e) {
        }
    }

    int convertInteger(String character) {
        String characters = "#&+;,:,. ";
        int PixelValue = 32 * (characters.indexOf(character)+1);   // returns character position
        return PixelValue;
    }


Save Compressed images using RLE

[edit | edit source]

Add option to save file as a compressed ASCII image. Adds another filetype

Python:

def compressFile(Grid, Header):
  Header.FileType = "C"
  FileName = input("Enter filename: ")
  FileOut = open(FileName + ".txt", 'w')
  FileOut.write(Header.Title + ',' + str(Header.Width) + ',' + str(Header.Height) + ',' + Header.FileType + '\n')

  for Row in range(Header.Height):
    pre_char = ''
    counter = 1
    temp = ''
    for Column in range(Header.Width):
      if Grid[Row][Column] != pre_char:
        if pre_char:
          temp = temp + str(counter) + pre_char
        counter = 1
        pre_char = Grid[Row][Column]
      else:
        counter = counter + 1
    temp = temp + str(counter) + pre_char
    FileOut.write(temp)
    FileOut.write('\n')


Load Compressed Image

[edit | edit source]

In Load subroutine pickup compressed file type and load into GRID

Python:

def LoadFile(Grid, Header):
  FileFound = False
  FileTypeOK = False
  FileName = input("Enter filename to load: ")
  try:
    FileIn = open(FileName + ".txt", 'r')
    FileFound = True
    HeaderLine = FileIn.readline()
    Fields = HeaderLine.split(',')
    Header.Title = Fields[0]
    Header.Width = int(Fields[1])
    Header.Height = int(Fields[2])
    Header.FileType = Fields[3]
    Header.FileType = Header.FileType[0]
    if Header.FileType == 'A':  
      Grid = LoadAsciiImage(FileIn, Grid, Header)
      FileTypeOK = True
    elif Header.FileType == 'G': 
      Grid = LoadGreyScaleImage(FileIn, Grid, Header)
      FileTypeOK = True
    elif Header.FileType == 'C':  ### add extra filetype
      Grid = LoadCompressedFile(FileIn, Grid, Header)
      FileTypeOK = True

    FileIn.close()
    if not FileTypeOK:
      DisplayError(2)
    else:
      DisplayImage(Grid, Header)
  except:
    if not FileFound:
      DisplayError(2)
    else:
      DisplayError(2)
  return Grid, Header

def LoadCompressedFile(FileIn, Grid, Header):
  count = ''
  NextChar = 0
  for Row in range(Header.Height):
    ImageData = FileIn.readline()
    temp = ''
    column = 0
    NextChar = 0
    Grid[Row]=[]
    while column < Header.Width:
      if ImageData[NextChar].isdigit():
        count = count + ImageData[NextChar]
      else:

        Grid[Row] = Grid[Row] + ([ImageData[NextChar]] * int(count))
        column = column + int(count)
        count = ""
      NextChar = NextChar + 1


  return Grid


Validate change symbol

[edit | edit source]

In the editImage subroutine add a function to validate whether the chosen symbol to replace exists in current image. Create SymbolExist subroutine which returns a boolean values of TRUE or FALSE depending whether given symbol exists in image.

Java:

  void editImage(String[][] grid, FileHeader header) {
        displayImage(grid, header);
        String answer = EMPTY_STRING;
        while (!answer.equals("N")) {
            String symbol = EMPTY_STRING;
            String newSymbol = EMPTY_STRING;
            while (symbol.length() != 1) {
                boolean valid = false;
                while (!valid) {   /// added loop to enforce validation
                    Console.write("Enter the symbol you want to replace: ");
                    symbol = Console.readLine();
                    valid = symbol_exist(symbol, grid, header);
                    if (!valid) {
                        Console.write("Symbol doesn't exist");
                    }
                }
            }
            while (newSymbol.length() != 1) {
                Console.write("Enter the new symbol: ");
                newSymbol = Console.readLine();
            }
            for (int thisRow = 0; thisRow < header.height; thisRow++) {
                for (int thisColumn = 0; thisColumn < header.width; thisColumn++) {
                    if (grid[thisRow][thisColumn].equals(symbol)) {
                        grid[thisRow][thisColumn] = newSymbol;
                    }
                }
            }
            displayImage(grid, header);
            Console.write("Do you want to make any further changes? (Y/N) ");
            answer = Console.readLine();
        }
    }

  boolean symbol_exist(String symbol, String[][] grid, FileHeader header){
        boolean found = false;

        for (int thisRow = 0; thisRow < header.height; thisRow++) {
            for (int thisColumn = 0; thisColumn < header.width; thisColumn++) {
                if (grid[thisRow][thisColumn].equals(symbol)) {
                   found = true;
                }
            }
        }
        return found;
    }


Validate change symbol (Python)

[edit | edit source]

In the editImage subroutine add a function to validate whether the chosen symbol to replace exists in current image. Create SymbolExist subroutine which returns a boolean values of TRUE or FALSE depending whether given symbol exists in image.

Python:

def EditImage(Grid, Header):
  DisplayImage(Grid, Header)
  Answer = EMPTY_STRING
  while Answer != "N":
    Symbol = EMPTY_STRING
    NewSymbol = EMPTY_STRING
    while len(Symbol) != 1:
      Symbol = input("Enter the symbol you want to replace: ")
      valid = SymbolExist(Symbol, Grid, Header)
      if valid != True:
        Symbol = ''
        print("Symbol not found, please try again")
    while len(NewSymbol) != 1:
      NewSymbol = input("Enter the new symbol: ")
    for ThisRow in range(Header.Height):
      for ThisColumn in range(Header.Width):
        if Grid[ThisRow][ThisColumn] == Symbol:
          Grid[ThisRow][ThisColumn] = NewSymbol
    DisplayImage(Grid, Header)
    Answer = input("Do you want to make any further changes? (Y/N) ")
  return Grid


def SymbolExist(Symbol, Grid, Header):
    for ThisRow in range(Header.Height):
      for ThisColumn in range(Header.Width):
        if Grid[ThisRow][ThisColumn] == Symbol:
          return True
    return False