Feb-19-2021, 06:13 AM
i want to create a small block to be a 'laser' and fire it from the canvas image im using as a ship. i've already created a list to append to and a ttl for the laser i even created the Laser class, but getting it to appear is not working like i thought it should.
with laser.lasers.append() ive tried .append(self), .append(Laser) , .append(Laser(p[0],p[1],dx,dy)) i just dont know how to get it rolling.
with laser.lasers.append() ive tried .append(self), .append(Laser) , .append(Laser(p[0],p[1],dx,dy)) i just dont know how to get it rolling.
from tkinter import * from PIL import ImageTk,Image import time window_height = 400 window_width = 720 r =Tk() canvas=Canvas(r,width=window_width, height=window_height) bg=PhotoImage(file="./nightsky.png") bg1= canvas.create_image(0,0,anchor=NW,image=bg) canvas.pack() class Laser: lasers = [] def __init__(self,x,y,xv,yv): self.id = canvas.create_rectangle(10,10,24,24, fill = "red") self.lasers.append(self) self.ttl = 100 self.speed = 5 self.dx = 1 self.dy = 0 def update(self,dx,dy): if self.ttl == 0: canvas.delete(self.id) self.lasers.remove(self) return self.ttl =-1 canvas.move(self.id, x*self.speed, y*self.speed) class ship: def __init__(self,x,y,xv,yv): self.x = x self.y = y self.img = PhotoImage(file="./8bitship.png") self.id = canvas.create_image(0,0,anchor=NW,image=self.img) self.dx = 1 self.dy = 0 self.img_width = self.img.width() self.img_height = self.img.height() self.xv = 0 self.yv = 0 def move(self,x,y): p = canvas.coords(self.id) print(p) if p[0] <= 0 : x = 1 if p[0] + self.img_width > window_width : x = -1 if p[1] <=0 : y = 1 if p[1] + self.img_height > window_height : y = -1 canvas.move(self.id,x,y) def fire(self,x,y,xv,yv): p = canvas.coords(self.id) print("fire") Laser.lasers.append(Laser) mship = ship(0,0,0,0) r.bind("<Right>", lambda e: mship.move(x=8,y=0)) r.bind("<Left>",lambda e: mship.move(x=-8,y=0)) r.bind("<Up>",lambda e: mship.move(x=0,y=-8)) r.bind("<Down>", lambda e: mship.move(x=0,y=8)) r.bind("<space>", lambda e: mship.fire(0,0,0,0)) for laser in Laser.lasers: laser.update() r.update() r.mainloop() time.sleep(0.05) r.update() r.mainloop()