1
0
mirror of https://github.com/osmarks/random-stuff synced 2024-12-21 23:50:35 +00:00

base32 thing, weird image esolang

This commit is contained in:
osmarks 2021-04-26 17:59:23 +01:00
parent d8ddcc6c3e
commit c6d8e69ef9
4 changed files with 306 additions and 0 deletions

86
code-guessing/base32-ts.py Executable file
View File

@ -0,0 +1,86 @@
#!/usr/bin/env python3
import random
import collections
import subprocess
import ctypes
import tempfile
import os
import shutil
import os.path
import base64
class CWrapper:
def __init__(self, file):
self.filename = file
def __enter__(self):
self.tempfile = tempfile.mktemp(prefix="shlib-")
print("Compiling C file", self.filename)
if subprocess.run(["gcc", self.filename, "-o", self.tempfile , "-shared", "-fPIC"]).returncode != 0:
raise ValueError("compilation failed")
library = ctypes.CDLL(self.tempfile)
self.function = entry = library.entry
entry.restype = ctypes.c_char_p
return self
def __call__(self, s): return self.function(ctypes.c_char_p(s.encode("ascii"))).decode("ascii")
def __repr__(self): return f"<wrapper for C solution {self.filename}>"
def __exit__(self, type, value, traceback): os.unlink(self.tempfile)
class JavaWrapper:
main = """
import java.io.*;
public class Main {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
while (true) {
String line = br.readLine();
if (line == null) { return; }
System.err.println("got");
System.err.println(line);
System.out.println(Entry.entry(line));
}
} catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
}
}
"""
def __init__(self, file):
self.filename = file
def __enter__(self):
self.tempdir = tempfile.mkdtemp(prefix="javacompile-")
code_path = os.path.join(self.tempdir, "Entry.java")
shutil.copyfile(self.filename, code_path)
main_path = os.path.join(self.tempdir, "Main.java")
with open(main_path, "w") as f:
f.write(JavaWrapper.main)
print("Compiling Java file", self.filename)
if subprocess.run(["javac", code_path, main_path]).returncode != 0:
raise ValueError("compilation failed")
main_class_path = os.path.join(self.tempdir, "Main.class")
self.process = subprocess.Popen(["java", "-cp", self.tempdir, "Main"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
return self
def __call__(self, s):
self.process.stdin.write(s.encode("ascii") + os.linesep.encode("ascii"))
self.process.stdin.flush()
return self.process.stdout.readline().decode("ascii")
def __repr__(self): return f"<wrapper for Java solution {self.filename}>"
def __exit__(self, type, value, traceback):
shutil.rmtree(self.tempdir)
self.process.kill()
def test(entry):
for _ in range(500):
s = "".join(chr(random.randint(32, 126)) for _ in range(random.randint(1, 256)))
answer = base64.b32encode(s.encode("ascii")).decode("ascii")
result = entry(s)
assert answer == result, f"test failed for {entry}: got {result}, should be {answer}, for {s}"
print(entry, "passed all tests")
import base32
test(base32.entry)

22
code-guessing/base32.py Normal file
View File

@ -0,0 +1,22 @@
import string, re
def entry(argv):
argv = argv.encode("utf-8")
modulus = len(argv) % 5
if modulus > 0:
argv += b"\x00" * (5-modulus)
chars = string.ascii_uppercase + "234567"
historyLen = 1
b = 0
for c in reversed(argv):
b += c * historyLen
historyLen *= 256
data = []
while b != 0:
data.append(chars[b % 32])
b //= 32
data = "".join(reversed(data))
checksum = { 0: 0, 1: 6, 2: 4, 3: 3, 4: 1 }
return re.sub("A{%d}$" % checksum[modulus], lambda str: str.group(0).replace("A", "="), data)

76
image-ec.py Normal file
View File

@ -0,0 +1,76 @@
from PIL import Image
import enum
import random
rng = random.Random()
def randomize(x, pos, m):
rng.seed(bytes(x) + pos[0].to_bytes(4, "little") + pos[1].to_bytes(4, "little"), 2)
return rng.randint(0, m), rng.randint(0, 255)
class Command(enum.Enum):
DIV = 0
DRP = 1
SDIZ = 2
MOD = 3
READ_IN = 4
ADD = 5
PUSH = 6
MUL = 7
ROT = 8
UNROT = 9
DUP = 10
CWROTATE = 11
ACWROTATE = 12
SETDIR = 13
UNASSIGNED_1 = 14
EXIT = 15
OUT = 16
SWP = 17
NOP = 18
dirs = { "up": (0, -1), "down": (0, 1), "right": (1, 0), "left": (-1, 0), "downright": (1, 1), "upright": (1, -1), "up2": (0, -2), "upleft": (-1, -1), "up3": (0, -3) }
def setdir(d):
x, y = dirs[d]
x, y = x + 3, y + 3
return (x << 3) + y
def go(d): return Command.SETDIR, setdir(d)
inp = [
[ Command.ACWROTATE, Command.ROT, (Command.SETDIR, setdir("right")), (Command.SETDIR, setdir("down"))],
[ Command.NOP, (Command.PUSH, 32), Command.UNROT, Command.NOP ],
[ (Command.PUSH, 0) , Command.UNROT, Command.DUP, Command.MUL ],
[ (Command.PUSH, 1), Command.DRP, Command.ROT , Command.UNROT , go("down"), Command.NOP, (Command.SETDIR, setdir("left")) ],
[ (Command.SETDIR, setdir("right")), Command.READ_IN, Command.CWROTATE , Command.ADD, go("right"), (Command.PUSH, 128), Command.ADD, Command.MUL ],
[ go("down"), Command.EXIT, Command.NOP, Command.ROT, Command.NOP ],
[ Command.DUP, go("upleft") , Command.NOP, go("upright") ],
[ Command.UNROT, (Command.SDIZ, setdir("up2"))],
[ Command.DUP , Command.NOP ],
[ Command.ROT , Command.NOP],
[ Command.MOD , Command.NOP],
[ Command.OUT , Command.NOP ],
[ Command.DUP, Command.NOP ],
[ Command.UNROT, go("up") ],
[ Command.DIV, Command.SWP ],
[ go("right"), go("up") ],
[ None, go("up3") ]
]
im = Image.new("RGB", (max(map(len, inp)), len(inp)))
px = im.load()
for y, row in enumerate(inp):
for x, op in enumerate(row):
if op:
param = None
if isinstance(op, tuple):
op, param = op
print(x, y, op, param)
# brute force muahahaha
command_id = op.value
while True:
rgb = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
cmd, arg = randomize(rgb, (x, y), Command.NOP.value)
if cmd == command_id and (param is None or arg == param):
px[x, y] = rgb
break
im.save("/tmp/out.png")

122
image-eso.py Normal file
View File

@ -0,0 +1,122 @@
from PIL import Image
import random
im = Image.open("/tmp/out.png")
px = im.load()
rng = random.Random()
def randomize(x, pos, m):
rng.seed(bytes(x) + pos[0].to_bytes(4, "little") + pos[1].to_bytes(4, "little"), 2)
return rng.randint(0, m), rng.randint(0, 255)
COMMANDS = 18
size = im.size
position = (0, 0)
direction = (1, 0)
matrix_1 = ((0, 1), (-1, 0))
matrix_2 = ((0, -1), (1, 0))
def rotate(matrix):
global direction
a = direction[0] * matrix[0][0] + direction[1] * matrix[0][1]
b = direction[0] * matrix[1][0] + direction[1] * matrix[1][1]
direction = (a, b)
stack = []
inbuf = ["b", "e", "e", "s", "i", "n", "c", "u", "r", "s", "e"]
class Command(__import__("enum").Enum):
DRP = 1
SDIZ = 2
MOD = 3
READ_IN = 4
ADD = 5
PUSH = 6
MUL = 7
ROT = 8
UNROT = 9
DUP = 10
CWROTATE = 11
ACWROTATE = 12
SETDIR = 13
EXIT = 15
UNASSIGNED_1 = 14
DIV = 0
OUT = 16
SWAP = 17
NOP = 18
while True:
command, param = randomize(px[position], position, COMMANDS)
print(command, position, direction, stack, Command(command))
if command == 4:
# read input
if len(inbuf) > 0:
stack.append(ord(inbuf.pop(0)))
else:
rotate(matrix_1)
elif command == 5:
# add
if len(stack) >= 2:
stack.append(stack.pop() + stack.pop())
else:
rotate(matrix_2)
elif command == 3:
# mod
if len(stack) >= 2:
stack.append(stack.pop() % stack.pop())
else:
rotate(matrix_2)
elif command == 0:
# div
if len(stack) >= 2:
stack.append(stack.pop() // stack.pop())
else:
rotate(matrix_2)
elif command == 6: # push
stack.append(param)
elif command == 8:
# rot
if len(stack) > 0:
stack = [stack.pop()] + stack
elif command == 9:
# unrot
if len(stack) > 0:
stack.append(stack.pop(0))
elif command == 10:
stack.extend([stack.pop()] * 2)
elif command == 7:
# mul
if len(stack) >= 2:
stack.append(stack.pop() * stack.pop())
else:
rotate(matrix_2)
elif command == 11:
rotate(matrix_1)
elif command == 12:
rotate(matrix_2)
elif command == 13: # setdir
arg = param
lowbits = (arg & 0b111) - 3
highbits = ((arg >> 3) & 0b111) - 3
direction = highbits, lowbits
elif command == 2: # setdir if zero
if len(stack) > 0 and stack[-1] == 0:
arg = param
lowbits = (arg & 0b111) - 3
highbits = ((arg >> 3) & 0b111) - 3
direction = highbits, lowbits
elif command == 16:
inbuf.append(chr(stack.pop()))
elif command == 17:
if len(stack) >= 2:
a, b = stack.pop(), stack.pop()
stack.append(a)
stack.append(b)
elif command == 1:
if len(stack) > 0: stack.pop()
elif command == 15:
break
position = (position[0] + direction[0], position[1] + direction[1])
while position[0] < 0 or position[1] < 0 or position[0] >= size[0] or position[1] >= size[1]:
position = (position[0] % size[0], position[1] % size[1])
print(stack, inbuf)