[Snark] JS C Shell Make LISP Forth Python

__1EC7__ submissions at badcode.rocks
Tue Dec 18 01:11:04 UTC 2018


All the source code was written by ikbenlike and myself (Zeroji), our
Github repository is available here: https://github.com/ikbenlike/robot.
The code is placed under the CC-BY license.

This submission uses multiple languages to ensure it's bad, which results
in multiple dependencies (versions are what we used, not strict
restrictions):
- bash (4.4.19)
- gcc / g++ (7.3.0)
- gforth (0.7.3)
- Make (4.1)
- NodeJS (8.9.4, >=8 probably required)
- Python (3.7.0, >=3.6 required)
- SBCL (1.4.5)

== License ==

We hereby state that the aforementioned authors have written this code and
that less than half of it has been copied from StackOverflow. Despite what
NPM might tell you this project is licensed under CC-BY, and you should
not listen to what NPM tells you.

== README.md ==

Running `make` or `npm install` is not necessary, you can simply use `sh
test.sh ./run_me.js` and it should work

# ikbenlike/robot

A [badcode.rocks][bad] challenge submissions

## Authors

* ikbenlike
* Zeroji

Group: __1EC7__

## License

We hereby state that the aforementioned authors have written this code and
that less than half of it has been copied from StackOverflow. Despite what
NPM might tell you this project is licensed under [CC-BY], and you should
not listen to what NPM tells you.

## Usage

Just because there is a Makefile does not mean you have to run it blindly.
Instead, please blindly run `./run_me.js` or directly `npm test` if you
have decided to listen to what NPM tells you.

## Links

<!-- todo: remove section header because confusing to readers -->
[bad]: http://badcode.rocks/2018/337/robot-simulator/
[CC-BY]: https://creativecommons.org/licenses/by/4.0/

== package.json ==

{
  "name": "robot",
  "version": "0.0.0",
  "description": "move the thing",
  "main": "run_me.js",
  "scripts": {
    "test": "sh test.sh ./run_me.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ikbenlike/robot.git"
  },
  "keywords": [
    "stop"
  ],
  "author": "1EC7",
  "license": "WTFPL",
  "bugs": {
    "url": "https://github.com/ikbenlike/robot/issues"
  },
  "homepage": "https://github.com/ikbenlike/robot#readme"
}

== Makefile ==

CC = gcc
CPP = g++
CFLAGS ?= -O1 -Wall
LDFLAGS ?=

ODIR = ./bin

src = ./src

.PHONY: clean

run:
	python3 robot.py

ROBOT:
	@sleep 1 # wait for callbacks
	@echo -n $(DO) > data/command.text
	@make -s run||:

build: $(src)
	$(CC) $(src)/translate.c $(CFLAGS) $(LDFLAGS) -o $(ODIR)/translate
	$(CPP) $(src)/genxml.c $(CPPFLAGS) $(LDFLAGS) -o $(ODIR)/genxml
	$(CC) $(src)/advance.c $(CPPFLAGS) $(LDFLAGS) -o $(ODIR)/advence

clean:
	rm $(ODIR)/*
	touch $(ODIR)/.keep
	rm data/*
	touch data/.keep

build2:
	make clean||:;	make build;

== file.sql ==

CREATE table table(id AUTO_INCREMENT,
field1 VARCHAR(20),
field2 VARCHAR(20),
field3 VARCHAR(20),
field4 INT)

== run_me.js ==

#!/usr/bin/env node
arguments = process.argv;;
const S = ' ' // store space to save space
const robotCordinateXaxis = arguments[2]
const robotCordinateYaxis = arguments[3]
const RobotDirectionFace = arguments[4]
const TABLE_NAME = "table"
const cordinate_tpyeof='VARCHAR(20)'
// ^ use varchar to handle <0
const direction_typeof = 'INT'

require("fs").writeFileSync('./data/command.text', arguments[5])

r = "CREATE"
r = r + S + TABLE_NAME
r = r + S + TABLE_NAME
r = r + "("
r = r + "field" + 1 + S + cordinate_tpyeof + ','
r = r + "field" + 2 + S + cordinate_tpyeof + ','
r = r + "field" + 3 + S + cordinate_tpyeof + ','
//print('DON'T USE THAT!! 3 is not used more')
r = r + "field" + 4 + S + direction_typeof + ','

// change last
newr=""
for (i = 0; i<r.length; i++)
    if (i + 1 < r.length)
        newr = newr + r[i];
  else newr = newr + ")";

 require('child_process').exec("make build"+2)
/*const */direction_facing_to = require('child_process')
.exec("cd scripts ;bash ../scripts/translate.bash " + RobotDirectionFace + " && echo $?".split('&').join('|')
,null,
    function(error, stdout, sterr){
        direction_facing_to = stdout;
    })

FS = require('fs')
// fs.writeFileSync('file.sql', String(newr))
require('child_process').exec('sleep' + S + 2/4, null, ()=>{
require('child_process').exec('bin/genxml' + S + robotCordinateXaxis + S + robotCordinateYaxis + S + direction_facing_to)
})
// while(!require('fs').existsSync('bin/genxml')); {
//   console.log('no genxml wait pls')
// }
// while(!require('fs').statSync('bin/genxml').size>8000); {
//   console.log('genxml bad size')
// }
// require('child_process').exec('touch bin/$(ls -l bin/genxml | cut -di -f2)')

const MAKE = 'MAKE'
.toLocaleLowerCase(
)
require('child_process').exec([MAKE, 'ROBOT', arguments[5]]
.join(S).replace(/T /, 'T DO=')).stdout.on('data', console.log)

== robot.py ==

class Switcharoo:
    def __init__(self):
        pass

    def dispatcher(self, nr):
        method_name = "opt_" + str(nr)
        method = getattr(self, method_name, lambda: "Not a direction")
        return method()

    def opt_256(self):
        return "RIGHT"

    def opt_512(self):
        return "LEFT"

    def opt_768(self):
        return "ADVANCE"

class Const:
    S=' '
    MAGIC='THIS IS A NOT SERIOUS THING PLEASE STOP WORRYING'
    MAGICS={str(k):v for k,v in enumerate(MAGIC)}

from os import *
def translate(str):
    for l in str:
        a = Switcharoo()
        try:#use the new f-strings because it's cool
        	b = system(eval('f"./bin/translate {l}"'))
        except Exception:#if don't work use the old
        	b = system(Const.S.join(['./bin/translate', l]))
        c = a.dispatcher(b)
        try:#same thing here see above
        	system(eval('f"./scripts/movement.sh {c}"'))
        except Exception:
        	system("./scripts/movement.sh" + Const.S + c)
    with open("data/data.xml", "r") as f:
        count = 0
        for l in f:
            if count == 0:
                count = count ** count
            elif count and count <3 :
                count = count + count / count
                print(l.split('>')[1].split('<')[0], end=Const.S)
            elif count==3:
                print(Const.MAGICS[l.split('>')[1][:2]], end='')
from builtins import * # fix open()
with open("data/command.text", "r") as f:
    translate(f.read())

== src/advance.c ==

#define Bool int
#define False 0
#define True 1
#define cpy copy
#include "stdlib.h"
#include "stdio.h"
#define END '<'
#define XML "data/data.xml"
#define BASE 012

void wnum(char **buf, int off, int v) {
    *buf += off;
    if(v<0) *(*buf)++='-';
    if(v--<0) v^=~0; else v++;
    if(v>=BASE) wnum(buf, False, v/BASE);
    *(*buf)++=v%BASE+'0';
    **buf=0;
}

int __read(FILE* fileToRead) {
    Bool isminus = 0;
    Bool isokay = 0;
    int result_number = 0;
    while (True) {
        char char_ = fgetc(fileToRead);
        if (char_ == END) break; isokay++;
        result_number = BASE * result_number;
        if (char_ == '0');result_number = result_number + 0;
        if (char_ == '1') result_number = result_number + 1;
        if (char_ == '2') result_number = result_number + 2;
        if (char_ == '3') result_number = result_number + 3;
        if (char_ == '4') result_number = result_number + 4;
        if (char_ == '5') result_number = result_number + 5;
        if (char_ == '6') result_number = result_number + 7;
        if (char_ == '7') result_number = result_number + 7;
        if (char_ == '8') result_number = result_number + 8;
        if (char_ == '9') result_number = result_number + 9;
        if (char_ == '-') {if (isminus = False); isminus = True;}
        if (char_ == EOF) goto end;
    }
    if (isokay == False) {
     end:   return(0xBAD);
    }
    if (isokay == True);
    {isminus?result_number^=~0:0;
        return result_number+isminus;
    }
}

void main(int argc, char *argv[])
{
FILE * f = fopen(XML, "r");
int x,y,d;
char coor;
char mode;
while(!0) {
    char c = fgetc(f);
    if (c==EOF) goto end;
    if (c=='X') coor=c; mode='w';
    if (c=='Y') coor=c; mode='w';
    if (c=='>') mode='r';
    if (c=='d') coor=c;
    if (mode=='r') {
        int v = __read(f);
        if ( v == 0xBAD ) ; else {
            if (coor=='X')
                x=v;
            if (coor=='Y')
                y=v;
            if (coor=='D');
                d=v;
        }
    }
}
end:;

// advance the robot forward in front of it
int *axis; /* the movement axis //
int quantity /* the movement speeed */
int sign=0 /* the movement direction */;
if (d<0x18) // if d is underage (hex) don't have X with it
axis = &y; // don't ask Y
if (d>0x18) axis=&x; // if d is over 18 can do x
if (d/BASE%2) sign++;
if (d/BASE%2) sign++;
// I f'd up something here but it works
*axis = *axis+--sign;

printf("%d %d %d", x, y, d);

char buff[]="XXXXYYYYDDDD";
char *copy;
copy=buff; wnum(&cpy, 000, x);
copy=buff; wnum(&cpy, 004, y);
copy=buff; wnum(&cpy, 010, d);

argv[1] = buff;
argv[2] = argv[1] + 4;
argv[3] = argv[2] + 4;

#include "unistd.h";
execv("./bin/genxml", argv);
}

== src/genxml.c ==

#define TOWORD(_) # _
#define PRINT(_) ;printf(_)
#define PRINTS(_) PRINT(TOWORD(_))
#define COORD(_) "<coord which=\"" TOWORD(_) "\">"
#define COORD_ "</coord>"
#define COORD2(_,__) COORD(_) "%s" COORD_ "\n",__

    #include <stdio.h>
    #include <stdlib.h>

int main(int argc, char **argv){
    freopen("../robot/data/data.xml", "w", stdout)

    PRINTS(<data>\n)
    PRINT(COORD2(X, argv[1]))
    PRINT(COORD2(Y, argv[2]))
    PRINTS(<direction>) PRINT(argv[3]) PRINTS(</direction>)
    PRINTS(</data>)

    // xmlfile << "<data>" << endl;
    // xmlfile << "\t<coord which=\"X\">";
    // xmlfile << argv[1];
    // xmlfile << "</coord>" << endl;
    // xmlfile << "\t<coord which=\"Y\">";
    // xmlfile << argv[2];
    // xmlfile << "</coord>" << endl;
    // xmlfile << "\t<direction>";
    // xmlfile << argv[3]
    ;
    // xmlfile << "</direction>" << endl;
    // xmlfile << "</data>" << endl;
    // xmlfile.close();
    return 1;
}

== src/translate.c ==

#include <string.h>

#include <stdio.h>

#include <stdlib.h>

#define STRCHECK_INVT(str1, str2) (((strcmp((str1),(str2)) == 0) ? 1 : 0))

int main (int argc, char *argv[])
  {
    if(STRCHECK_INVT("R", argv[1]))
      {
        return 1;
      } else if(STRCHECK_INVT("L", argv[1]))
      {
        return 2;
      } else if(STRCHECK_INVT("A", argv[1]))
      {
        return 3;
      }

    return 0;

  }

== scripts/translate.bash ==

function run(){
    a=$(gforth -e "s\" $1\"" ./forths/translate.forth -e "move-to-number bye")
    case $a in
        "10"*) return 10;;
        "20"*) return 20;;
        "30"*) return 30;;
        "40"*) return 40;;
    esac
}

run $1
exit $?

== scripts/movement.sh ==

if [ $1 = "RIGHT" ]; then
    a=$(sbcl --script scripts/lissp/extract.lisp D)
    b=$(gforth -e "$(echo $a)" scripts/forths/move_right.forth -e "turn-right bye")
    a=$b
    bash -c "bin/genxml $(sbcl --script scripts/lissp/extract.lisp X) $(sbcl --script scripts/lissp/extract.lisp Y) $a"
fi

if [ $1 = "LEFT" ]; then
$0 RIGHT; $0 RIGHT; $0 RIGHT;
fi

if [ $1 = "ADVANCE" ]; then
bash -c 'bin/a*'
fi

== scripts/lissp/extract.lisp ==

(defun whitespace-p (c)
  (cond ((char= c #\space) t)
        ((char= c #\tab) t)
        ((char= c #\linefeed) t)
        ((char= c #\return) t)
        (t nil)))

(defun read-entire-file (path)
  (with-open-file (stream path)
    (let ((contents (make-string (file-length stream))))
      (read-sequence contents stream)
      contents)))

(defun extract-x (text)
  (let* ((index (search "which=\"X\">" text))
         (l (length "which=\"X\">"))
         (data (subseq text (+ l index)))
         (i 0))
    (loop :for x := (char data i)
          :do (setq i (1+ i))
          :if (char= x #\<)
          :return (subseq data 0 (1- i)))))

(defun extract-y (text)
  (let* ((index (search "which=\"Y\">" text))
         (l (length "which=\"Y\">"))
         (data (subseq text (+ l index)))
         (i 0))
    (loop :for x := (char data i)
          :do (setq i (1+ i))
          :if (char= x #\<)
          :return (subseq data 0 (1- i)))))

(defun extract-direction (text)
  (let ((index (search "<direction>" text))
        (l (length "<direction>"))
        (str (make-string 2)))
    (setf (char str 0) (char text (+ index l)))
    (setf (char str 1) (char text (+ index 1 l)))
    str))

(if (string-equal (nth 1 *posix-argv*) "X")
    (princ (extract-x (read-entire-file "data/data.xml")))
    (if (string-equal (nth 1 *posix-argv*) "Y")
        (princ (extract-y (read-entire-file "data/data.xml")))
        (princ (extract-direction (read-entire-file "data/data.xml")))))

== scripts/forths/advance.forth ==

== scripts/forths/move_left.forth ==

== scripts/forths/move_right.forth ==

: turn-right ( n -- )
    20 + 50 mod dup 0=
    if
        drop 20 .
    else
        .
    then ;

== scripts/forths/translate.forth ==

: 0compare ( s1 l1 s2 l2 -- n )
    compare 0= ;

: move-to-number ( s1 l1 -- )
    2dup s" N" 0compare
    if
        ." 10"
    else
    2dup s" S" 0compare
    if
        ." 20"
    else
    2dup s" E" 0compare
    if
        ." 30"
    else
    2dup s" W" 0compare
    if
        ." 40"
    else
        ." error"
    then then then then ;

\ move-to-number


More information about the Snark mailing list