from gint import *
from casioplot import *
from time import *
from micropython import *
from random import *

opt_level(3)

start=time()

def iskeydown(key):
  clearevents()
  return keydown(key)

BLACK=(0,0,0)

player="""       ##       
      #  #      
     # ## #     
    # #  # #    
 # # ##  ## # # 
# # # #  # # # #
# # ######## # #
# #          # #
# #          # #
#              #
# #   #  #  ## #
## # #  # # # ##
####  # ### # ##
## # #  # # # ##
#              #
 ############## """

def drawplayer(px,py):
  for dy in range(16):
    for dx in range(16):
      if player[dy*17+dx]=='#':
        set_pixel(px+dx,py+dy,BLACK)

c = '1'

while c != '0' and c != 'n':
  print("Tirez sur les octets")
  print("qui tombent du ciel")
  print("pour eliminer tous")
  print("les bugs de ce")
  print("programme. Mais")
  print("plus vous corrigez")
  print("plus c'est bogue !")
  input("EXE pour jouer >")
  lasers=[]
  bytes=[]
  x=64
  y=48
  pc=0
  f=100

  while not iskeydown(KEY_EXIT):
    clear_screen()
    if iskeydown(KEY_UP) and y>0:
      y-=1
    if iskeydown(KEY_DOWN) and y<63:
      y+=1
    if iskeydown(KEY_LEFT) and x>0:
      x-=4
    if iskeydown(KEY_RIGHT) and x<127:
      x+=4
    if iskeydown(KEY_SHIFT):
      lasers.append([x,y-8])
    p=0
    dell=[]
    for i in lasers:
      for n in range(i[1]-8,i[1]):
        set_pixel(i[0],n,BLACK)
      i[1]-=4
      if i[1] < 0: dell.append(p)
      p+=1
    for i in dell: lasers.pop(i)
    i=0
    drawplayer(x-8,y-8)
    draw_string(1,1,"pc="+hex(pc),BLACK,"small")
    if randint(1,f)==1:
      bytes.append([randint(0,115),-7,randint(0,255)])
      if f>10: f-=4
      if f<10: f=10
    i=0
    exit=0
    while i<len(bytes):
      draw_string(bytes[i][0],bytes[i][1],hex(bytes[i][2]),BLACK,"small")
      bytes[i][1]+=1
      tx=bytes[i][0]
      ty=bytes[i][1]
      n=0
      delb = 0
      while n<len(lasers):
        dx=lasers[n][0]
        dy=lasers[n][1]
        if dx>tx and dx<tx+11 and dy>ty and dy<ty+8:
          lasers.pop(n)
          n-=1
          delb = 1
          break
        n+=1
      if bytes[i][1]>63:
        exit=1
        break
      if delb:
        bytes.pop(i)
        i-=1
      i+=1
    if exit:
      break
    start=time()
    show_screen()
    pc+=1
  print("GAME OVER\npc="+hex(pc))
  c = input("Continuer [Y=1/n=0] >").lower().strip()
