How to write a C Program Function to read instructions from the file and obey them in C Programming Language ?
This C Program function to read instructions from the file and obey them.
Solution:
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- #include "display.h"
- typedef unsigned char byte;
- int getopcode(byte b){
- return ((b >> 6) & 0x3);
- }
- int getoperand(byte b, bool s){
- if(s && (b >> 5) & 1){
- return (-32) + (b & 0x1F);
- } else {
- return (b & 0x3F);
- }
- }
- struct state {
- int x;
- int y;
- int pen;
- };
- struct state DX(struct state s, int dx, display *d){
- if (s.pen == 1) line(d, s.x, s.y, s.x + dx, s.y);
- s.x = s.x + dx;
- return s;
- }
- struct state DY(struct state s, int dy, display *d){
- if (s.pen == 1) line(d, s.x, s.y, s.x, s.y + dy);
- s.y = s.y + dy;
- return s;
- }
- struct state DT(struct state s, int t, display *d){
- pause(d, t);
- return s;
- }
- struct state PEN(struct state s){
- if(s.pen == 1){
- s.pen = 0;
- } else {
- s.pen = 1;
- }
- return s;
- }
- void interpet(FILE *in, display *d) {
- struct state s = { 0, 0, 0 };
- byte b;
- bool sign = true;
- b = fgetc(in);
- while(! feof(in)) {
- int opcode = getopcode(b);
- printf("%d %d\n",opcode, operand);
- if (opcode == 0) s = DX(s, getoperand(b, sign), d);
- if (opcode == 1) s = DY(s, getoperand(b, sign), d);
- if (opcode == 2){
- sign = false;
- s = DT(s, getoperand(b, sign), d);
- }
- if (opcode == 3) s = PEN(s);
- b = fgetc(in);
- }
- }
- // TODO: upgrade this function to read instructions from the file and obey them
- void run(char *filename, bool testing) {
- FILE *in = fopen(filename, "rb");
- if (in == NULL) {
- printf("Can't open %s\n", filename);
- exit(1);
- }
- display *d = newDisplay(filename, 200, 200, testing);
- interpet(in, d);
- end(d);
- fclose(in);
- if (testing) printf("Sketch %s OK\n", filename);
- }