#to proccess bad apple into minecraft commont

import numpy as np
from PIL import Image
import matplotlib.pyplot as plot
import cv2
from random import random

cap = cv2.VideoCapture("bad apple.mp4")
totalframe = cap.get(cv2.CAP_PROP_FRAME_COUNT)
#adr = "answers"
#cap.set(cv2.CAP_PROP_POS_FRAMES, 199)

def get_translate(x, y, i):
	ori_x = -11 - 6 * i
	ori_y = 75 #int(input('commond block position y:'))
	ori_z = -70 #int(input('commond block position z:'))

	off_y = - ((y-1)//2) * 6 - (y + 1)%2 - 2

	if y%2 == 1:
		off_z = -2 * x - 1
		off_x = 0
	else:
		off_z = -2 * x
		off_x = -1

	return 'setblock '+str(ori_x+off_x)+' '+str(ori_y+off_y)+\
					' '+str(ori_z+off_z)+' air\n'

i = 0
while True:
	for r in range(6):
		success, frame = cap.read()
		if not success:
			break
	if not success:
		break
	elif i != 0:
		with open(adr, 'a') as f:
			f.write("say frame "+str(i)+" set success!\n")
			f.write("function answers:frame"+str(i+1))
	
	i += 1

	frame = np.array(frame)
	lines = ''
	adr = 'answers/frame'+str(i)+'.mcfunction'

	#pre-process
	fra = np.array(Image.fromarray(np.uint8(frame)).convert('1'))
	frame = np.zeros((608, 912))
	frame[:, 51:861] = fra

	#cut
	pixel = np.zeros((24, 36))
	for x in range(24):
		for y in range(36):
			addup = np.sum(frame[x*25:(x+1)*25, y*25:(y+1)*25])
			if addup < 300:
				pixel[x, y] = 0
			elif addup > 325:
				pixel[x, y] = 1
				lines += (get_translate(y+1, x+1, i))
			elif random() < 0.5:
				lines += (get_translate(y+1, x+1, i))
	print(str(i*6/totalframe*100)+"%")

	with open(adr, 'w') as f:
		f.write(lines)