class MapRenderer: def __init__(self, config=config, **kwargs): self.config = config self.__dict__.update(kwargs) self.map = Map(**kwargs) @property def canvas_width(self): return self.map.width * self.map.block_width @property def canvas_height(self): return self.map.height * self.map.block_height def init_canvas(self, parent=None): if parent == None: parent = self.parent if hasattr(self, 'canvas'): pass else: self.canvas = Canvas(parent) self.canvas.xview_moveto(0) self.canvas.yview_moveto(0) def kill_canvas(self): if hasattr(self, 'canvas'): self.canvas.destroy() def draw(self): self.canvas.configure(width=self.canvas_width, height=self.canvas_height) for i in xrange(len(self.map.blockdata)): block_x = i % self.map.width block_y = i / self.map.width self.draw_block(block_x, block_y) def draw_block(self, block_x, block_y): # the canvas starts at 4, 4 for some reason # probably something to do with a border index, indey = 4, 4 # Draw one block (4x4 tiles) block = self.map.blockdata[block_y * self.map.width + block_x] # Ignore nonexistent blocks. if block >= len(self.map.tileset.blocks): return for j, tile in enumerate(self.map.tileset.blocks[block]): try: # Tile gfx are split in half to make vram mapping easier if tile >= 0x80: tile -= 0x20 tile_x = block_x * self.map.block_width + (j % 4) * 8 tile_y = block_y * self.map.block_height + (j / 4) * 8 self.canvas.create_image(index + tile_x, indey + tile_y, image=self.map.tileset.tiles[tile]) except: pass def crop(self, *args, **kwargs): self.map.crop(*args, **kwargs) self.draw()
class MapRenderer: def __init__(self, config=config, **kwargs): self.config = config self.__dict__.update(kwargs) self.map = Map(**kwargs) @property def canvas_width(self): return self.map.width * self.map.block_width @property def canvas_height(self): return self.map.height * self.map.block_height def init_canvas(self, parent=None): if parent == None: parent = self.parent if hasattr(self, 'canvas'): pass else: self.canvas = Canvas(parent) self.canvas.xview_moveto(0) self.canvas.yview_moveto(0) def kill_canvas(self): if hasattr(self, 'canvas'): self.canvas.destroy() def draw(self): self.canvas.configure(width=self.canvas_width, height=self.canvas_height) for i in xrange(len(self.map.blockdata)): block_x = i % self.map.width block_y = i / self.map.width self.draw_block(block_x, block_y) def draw_block(self, block_x, block_y): # the canvas starts at 4, 4 for some reason # probably something to do with a border index, indey = 4, 4 # Draw one block (4x4 tiles) block = self.map.blockdata[block_y * self.map.width + block_x] # Ignore nonexistent blocks. if block >= len(self.map.tileset.blocks): return for j, tile in enumerate(self.map.tileset.blocks[block]): try: # Tile gfx are split in half to make vram mapping easier if tile >= 0x80: tile -= 0x20 tile_x = block_x * self.map.block_width + (j % 4) * 8 tile_y = block_y * self.map.block_height + (j / 4) * 8 self.canvas.create_image(index + tile_x, indey + tile_y, image=self.map.tileset.tiles[tile]) except: pass def crop(self, *args, **kwargs): self.map.crop(*args, **kwargs) self.draw()
class bootWindow: def __init__(self, parent): logging.info("Host IP: " +get_ip()) self.screen = Canvas(parent, bg=black, height=480, width=320) self.screen.place(x=0,y=0) Testline = self.screen.create_line(160, 0, 160, 480, fill=red) Testline2 = self.screen.create_line(0, 240, 320, 240, fill=red) self.img = ImageTk.PhotoImage(Image.open("images/logo.PNG")) self.imglabel = Label(self.screen, image=self.img).place(x=160, y=150, anchor="center") self.text = self.screen.create_text(160,270 , text="Loading, Please wait...", fill=white, font=(textFont, 13)) self.p = ttk.Progressbar(self.screen, orient="horizontal", length=200, mode='determinate') self.p.place(x=160, y=300, anchor="center") # LOAD ALL THE STUFF!! parent.update() self.p.step(10) parent.update() #time.sleep(1) self.p.step(10) parent.update() #time.sleep(1) self.p.step(30) parent.update() time.sleep(1) self.screen.destroy() self.p.destroy() def hide(self): pass def show(self): pass def update(self): pass def __del__(self): pass
class bootWindow: def __init__(self, parent): logging.info("Host IP: " + get_ip()) self.screen = Canvas(parent, bg=black, height=480, width=320) self.screen.place(x=0, y=0) Testline = self.screen.create_line(160, 0, 160, 480, fill=red) Testline2 = self.screen.create_line(0, 240, 320, 240, fill=red) self.img = ImageTk.PhotoImage(Image.open("images/logo.PNG")) self.imglabel = Label(self.screen, image=self.img).place(x=160, y=150, anchor="center") self.text = self.screen.create_text(160, 270, text="Loading, Please wait...", fill=white, font=(textFont, 13)) self.p = ttk.Progressbar(self.screen, orient="horizontal", length=200, mode='determinate') self.p.place(x=160, y=300, anchor="center") # LOAD ALL THE STUFF!! parent.update() self.p.step(10) parent.update() #time.sleep(1) self.p.step(10) parent.update() #time.sleep(1) self.p.step(30) parent.update() time.sleep(1) self.screen.destroy() self.p.destroy() def hide(self): pass def show(self): pass def update(self): pass def __del__(self): pass
def destroy(self): Canvas.destroy(self) self.canvas = None
class Game: def __init__(self): self.root = Tk() self.frame1 = None self.frame2 = None self.w = None self.scoreC = None self.score = 0 self.hor = True self.upid = self.downid = self.rightid = self.leftid = 0 self.head = -1 self.time = 700 def home(self): self.frame1 = Frame(self.root, width=750, height=350, padx=250, bg="black") self.frame2 = Frame(self.root, height=250, width=750, bg="black", padx=25) self.root.wm_minsize(width=750, height=666) self.root.configure(bg="black") self.frame1.pack_propagate(0) self.frame1.update() self.frame1.configure(pady=self.frame1.cget("height") / 2.5) logo = PhotoImage(file="Game_Logo.gif") starth = Button(self.frame1, text="Hard", bg="orange", padx=25, pady=5, font=Font(family="comic sans MS", size=10), command=lambda: self.callgame(40)) startm = Button(self.frame1, text="Medium", bg="teal", padx=25, pady=5, font=Font(family="comic sans MS", size=10), command=lambda: self.callgame(60)) starte = Button(self.frame1, text="Easy", bg="orange", padx=25, pady=5, font=Font(family="comic sans MS", size=10), command=lambda: self.callgame(75)) self.frame2.pack_propagate(0) exp = """ This is a game in which the arrow keys are used to move the snake around and to get points""" exf = Font(family="comic sans MS", size=20) Label(self.frame2, image=logo, bg="black", text=exp, padx=10).pack(side="right") Label(self.frame2, fg="white", bg="black", text=exp, justify="left", font=exf).pack(side="left") starte.grid(row=0, columnspan=2) startm.grid(row=0, columnspan=2, column=4, padx=18) starth.grid(row=0, columnspan=2, column=8) head = Font(family="comic sans MS", size=30) self.H=Label(self.root, text="SNAKES", font=head, fg="orange", bg="black", pady=10) self.H.pack() self.frame2.pack(expand=True) self.frame1.pack(expand=True) self.root.mainloop() def callgame(self, time): self.time = time self.game() def calldown(self, key): if self.hor: self.w.after_cancel(self.leftid) self.w.after_cancel(self.rightid) self.down(0) def callup(self, key): if self.hor: self.w.after_cancel(self.leftid) self.w.after_cancel(self.rightid) self.up(0) def callright(self, key): if not self.hor: self.w.after_cancel(self.upid) self.w.after_cancel(self.downid) self.right(0) def callleft(self, key): if not self.hor: self.w.after_cancel(self.upid) self.w.after_cancel(self.downid) self.left(0) def game(self): self.score = 0 self.w = Canvas(self.root, width=750, height=500, relief="flat", highlightbackground="grey", highlightthickness=10) self.frame1.destroy() self.frame2.destroy() self.root.configure(width=1000, padx=10) self.root.pack_propagate(0) self.w.configure(background="black") self.w.pack(side="left") self.w.create_line(300, 250, 450, 250, width=10, fill="teal") self.scoreC = Label(self.root, text="Score\n" + str(self.score), bg="black", fg="teal", padx=25, pady=35, font=Font(family="comic sans MS", size=25)) self.head = self.w.create_line(450, 250, 455, 250, width=10, fill="white") self.scoreC.pack(side="top") self.root.bind("<Up>", self.callup) self.root.bind("<Down>", self.calldown) self.root.bind("<Right>", self.callright) self.root.bind("<Left>", self.callleft) self.createFood() self.right(0) def down(self, i): crd = self.w.coords(1) if len(crd) > 0: if crd[0] == crd[2]: if crd[1] > crd[3]: # print("inside if1") crd[1] -= 10 if crd[1] < crd[3]: # print("inside if2") crd[1] += 10 else: if crd[0] > crd[2]: crd[0] -= 10 if crd[0] < crd[2]: crd[0] += 10 crd[-1] += 10 if i == 0: crd.append(crd[-2]) crd.append(crd[-2]) crd[-3] -= 10 if crd[0] == crd[2] and crd[1] == crd[3]: crd = crd[2:] self.w.coords(1, *crd) self.w.delete(self.head) self.head = self.w.create_line(crd[-2], crd[-1], crd[-2], crd[-1] + 5, width=10, fill="orange") end = self.end() self.checkEaten() i += 1 self.hor = False if not end: self.downid = self.w.after(self.time, self.down, i) else: self.w.delete(1) self.w.delete(self.head) self.w.delete(self.food) self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25, font=Font(family="comic sans MS", size=15), command=lambda: self.callhome()) self.start.pack(side="bottom") def up(self, i): crd = self.w.coords(1) if len(crd)>0: if crd[0] == crd[2]: if crd[1] > crd[3]: # print("inside if1") crd[1] -= 10 if crd[1] < crd[3]: # print("inside if2") crd[1] += 10 else: if crd[0] > crd[2]: crd[0] -= 10 if crd[0] < crd[2]: crd[0] += 10 crd[-1] -= 10 if i == 0: crd.append(crd[-2]) crd.append(crd[-2]) crd[-3] += 10 if crd[0] == crd[2] and crd[1] == crd[3]: crd = crd[2:] self.w.coords(1, *crd) self.w.delete(self.head) self.head = self.w.create_line(crd[-2], crd[-1], crd[-2], crd[-1] - 5, width=10, fill="orange") end = self.end() self.checkEaten() i += 1 self.hor = False if not end: self.upid = self.w.after(self.time, self.up, i) else: self.w.delete(1) self.w.delete(self.head) self.w.delete(self.food) self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25, font=Font(family="comic sans MS", size=15), command=lambda: self.callhome()) self.start.pack(side="bottom") def right(self, i): crd = self.w.coords(1) if len(crd) > 0: if crd[0] == crd[2]: if crd[1] > crd[3]: # print("inside if1") crd[1] -= 10 if crd[1] < crd[3]: # print("inside if2") crd[1] += 10 else: if crd[0] > crd[2]: crd[0] -= 10 if crd[0] < crd[2]: crd[0] += 10 crd[-2] += 10 if i == 0: crd.append(crd[-2]) crd.append(crd[-2]) crd[-4] -= 10 if crd[0] == crd[2] and crd[1] == crd[3]: crd = crd[2:] self.w.coords(1, *crd) self.w.delete(self.head) self.head = self.w.create_line(crd[-2], crd[-1], crd[-2] + 5, crd[-1], width=10, fill="orange") end = self.end() self.checkEaten() i += 1 self.hor = True if not end: self.rightid = self.w.after(self.time, self.right, i) else: self.w.delete(1) self.w.delete(self.head) self.w.delete(self.food) self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25, font=Font(family="comic sans MS", size=15), command=lambda: self.callhome()) self.start.pack(side="bottom") def left(self, i): crd = self.w.coords(1) if len(crd) > 0: if crd[0] == crd[2]: if crd[1] > crd[3]: # print("inside if1") crd[1] -= 10 if crd[1] < crd[3]: # print("inside if2") crd[1] += 10 else: if crd[0] > crd[2]: crd[0] -= 10 if crd[0] < crd[2]: crd[0] += 10 crd[-2] -= 10 if i == 0: crd.append(crd[-2]) crd.append(crd[-2]) crd[-4] += 10 if crd[0] == crd[2] and crd[1] == crd[3]: crd = crd[2:] self.w.coords(1, *crd) self.w.delete(self.head) self.head = self.w.create_line(crd[-2], crd[-1], crd[-2] - 5, crd[-1], width=10, fill="orange") end = self.end() self.checkEaten() i += 1 self.hor = True if not end: self.leftid = self.w.after(self.time, self.left, i) else: self.w.delete(1) self.w.delete(self.head) self.w.delete(self.food) self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25, font=Font(family="comic sans MS", size=15), command=lambda: self.callhome()) self.start.pack(side="bottom") def createFood(self): # self.w.delete(self.food) #deleting old food. crd = self.w.coords(1) ext = [] for i in crd: ext.append(i) for j in range(-50, 50): ext.append(i + j) randx = random.randrange(20, 730) randy = random.randrange(20, 480) while randx not in ext and randy not in ext: randx = random.randrange(20, 730) randy = random.randrange(20, 480) self.food = self.w.create_line(randx, randy, randx + 12, randy, width=10, fill="yellow") def checkEaten(self): headcoords = self.w.coords(self.head) foodcoords = self.w.coords(self.food) # self.w.delete(self.food) flag = False # print(headcoords[-4]) # print(foodcoords[-4]) # print(foodcoords[-2]) if int(headcoords[-4]) in range(int(foodcoords[-4]) - 7, int(foodcoords[-2]) + 7) and int( headcoords[-3]) in range(int(foodcoords[-1]) - 10, int(foodcoords[-1] + 10)): flag = True if flag: self.grow() self.score += 10 self.scoreC.configure(text="Score\n" + str(self.score), bg="black", fg="teal", padx=25, pady=35, font=Font(family="comic sans MS", size=25)) self.w.delete(self.food) self.createFood() def grow(self): crd = self.w.coords(1) if crd[0] != crd[2]: # horizontal condition if crd[0] < crd[2]: crd[0] -= 20 else: crd[0] += 20 self.w.coords(1, *crd) else: if crd[3] < crd[1]: crd[1] += 20 else: crd[1] -= 20 self.w.coords(1, *crd) def end(self): crd = self.w.coords(1) h = self.w.coords(self.head) a = 0 while a < len(crd) - 2: if crd[a] == crd[a + 2]: if (h[0] == crd[a] and crd[a + 1] < h[1] < crd[a + 3]) or ( h[0] == crd[a] and crd[a + 1] > h[1] > crd[a + 3]): return True else: if (h[1] == crd[a + 1] and crd[a] < h[0] < crd[a + 2]) or (h[1] == crd[a + 1] and crd[a] > h[0] > crd[a + 2]): return True a += 2 if (h[0] == 0 and 0 < h[1] < 500) or (h[1] == 0 and 0 < h[0] < 750) or (h[1] == 510 and 0 < h[0] < 750) or (h[0] == 760 and 0<h[1]<500): return True return False def callhome(self): self.w.destroy() self.start.destroy() self.H.destroy() self.scoreC.destroy() self.home()
class IntroView(Frame): def __init__(self, controller, parent): # formerly init_intro_nav(): ''' using class objects for all these vars now global intro_nav, background_frame, can, button_load_game\ , button_new_game, button_quit, intro_fill_bottom\ , label_version, title_image_res\ , intro_top_padding, intro_btm_padding ''' self.controller = controller self.parent = parent self.app = self.controller.app # declare vars self.background_frame = 0 self.intro_nav = 0 self.intro_top_padding = 0 def build(self): # prev: build_intro_nav # frame setup conf = self.app.conf self.background_frame = Frame(self.parent, height=self.parent.sh, width=self.parent.sw , background=conf.window_background) self.intro_nav = Frame(self.background_frame, height=500, width=500 , background=conf.intro_background) # elements self.intro_top_padding = Canvas(self.intro_nav) self.intro_top_padding.configure(height=conf.intro_padding_height , background=conf.intro_background , highlightbackground=conf.intro_background) self.title_image_resource = Image.open(conf.title_image_path) self.title_image_res = ImageTk.PhotoImage(self.title_image_resource) self.can = Canvas(self.intro_nav, background=conf.intro_background , highlightbackground=conf.intro_background) self.can.title_image_res = self.title_image_res self.can.config(width=self.title_image_res.width(), height=self.title_image_res.height()) self.button_new_game = Button(self.intro_nav, text="New Game" , command=self.controller.event_button_new_game , bg=conf.intro_background) self.button_new_game.config(highlightbackground=conf.intro_background) self.button_load_game = Button(self.intro_nav, text="Load Game" , command=self.controller.event_button_load_game , bg=conf.intro_background) self.button_load_game.config(highlightbackground=conf.intro_background) self.button_load_game.config(state='disabled') self.button_quit = Button(self.intro_nav, text="Quit" , command=self.controller.event_button_quit , bg=conf.intro_background) self.button_quit.config(highlightbackground=conf.intro_background) self.label_version = Label(self.intro_nav, bg=conf.intro_background, text=conf.version) self.intro_btm_padding = Canvas(self.intro_nav) self.intro_btm_padding.configure(height=conf.intro_padding_height , background=conf.intro_background , highlightbackground=conf.intro_background) def hide(self): # formerly hide_intro_nav self.intro_nav.destroy() self.background_frame.destroy() self.can.destroy() self.button_load_game.destroy() self.button_new_game.destroy() self.button_quit.destroy() self.label_version.destroy() self.title_image_res.__del__() self.intro_top_padding.destroy() self.intro_btm_padding.destroy() def draw(self): # formerly draw_intro_nav() # frame setup self.intro_top_padding.pack() self.background_frame.pack(fill='both') self.intro_nav.pack(fill='both', padx=(self.parent.sw/2)-250, pady=(self.parent.sh/2)-250) self.app.debug(("Drew Intro, padding: (", (self.parent.sw/2)-250, ",", (self.parent.sh/2)-250, ")")) # elements self.can.pack(fill='both', side='top', padx=50, pady=50) self.can.create_image(2, 2, image=self.title_image_res, anchor='nw') self.button_new_game.pack(fill="x", padx=50) self.button_load_game.pack(fill="x", padx=50) self.button_quit.pack(fill="x", padx=50) self.label_version.pack(fill='y', padx=10, pady=10) self.intro_btm_padding.pack() '''
def destroy(self): Canvas.destroy(self) self.canvas = None
class Game: def __init__(self): self.root = Tk() self.frame1 = None self.frame2 = None self.w = None self.scoreC = None self.score = 0 self.hor = True self.upid = self.downid = self.rightid = self.leftid = 0 self.head = -1 self.time = 700 def home(self): self.frame1 = Frame(self.root, width=750, height=350, padx=250, bg="black") self.frame2 = Frame(self.root, height=250, width=750, bg="black", padx=25) self.root.wm_minsize(width=750, height=666) self.root.configure(bg="black") self.frame1.pack_propagate(0) self.frame1.update() self.frame1.configure(pady=self.frame1.cget("height") / 2.5) logo = PhotoImage(file="logo.gif") starth = Button(self.frame1, text="Hard", bg="orange", padx=25, pady=5, font=Font(family="comic sans MS", size=10), command=lambda: self.callgame(40)) startm = Button(self.frame1, text="Medium", bg="teal", padx=25, pady=5, font=Font(family="comic sans MS", size=10), command=lambda: self.callgame(60)) starte = Button(self.frame1, text="Easy", bg="orange", padx=25, pady=5, font=Font(family="comic sans MS", size=10), command=lambda: self.callgame(75)) self.frame2.pack_propagate(0) exp = """ This is a game in which the arrow keys are used to move the snake around and to get points""" exf = Font(family="comic sans MS", size=20) Label(self.frame2, image=logo, bg="black", text=exp, padx=10).pack(side="right") Label(self.frame2, fg="white", bg="black", text=exp, justify="left", font=exf).pack(side="left") starte.grid(row=0, columnspan=2) startm.grid(row=0, columnspan=2, column=4, padx=18) starth.grid(row=0, columnspan=2, column=8) head = Font(family="comic sans MS", size=30) self.H = Label(self.root, text="SNAKES", font=head, fg="orange", bg="black", pady=10) self.H.pack() self.frame2.pack(expand=True) self.frame1.pack(expand=True) self.root.mainloop() def callgame(self, time): self.time = time self.game() def do_after_cancel(self, a, b): if a != 0: self.w.after_cancel(a) if b != 0: self.w.after_cancel(b) def calldown(self, key): if self.hor: self.do_after_cancel(self.leftid, self.rightid) self.down(0) def callup(self, key): if self.hor: self.do_after_cancel(self.leftid, self.rightid) self.up(0) def callright(self, key): if not self.hor: self.do_after_cancel(self.upid, self.downid) self.right(0) def callleft(self, key): if not self.hor: self.do_after_cancel(self.upid, self.downid) self.left(0) def game(self): self.score = 0 self.w = Canvas(self.root, width=750, height=500, relief="flat", highlightbackground="grey", highlightthickness=10) self.frame1.destroy() self.frame2.destroy() self.root.configure(width=1000, padx=10) self.root.pack_propagate(0) self.w.configure(background="black") self.w.pack(side="left") self.w.create_line(300, 250, 450, 250, width=10, fill="teal") self.scoreC = Label(self.root, text="Score\n" + str(self.score), bg="black", fg="teal", padx=25, pady=35, font=Font(family="comic sans MS", size=25)) self.head = self.w.create_line(450, 250, 455, 250, width=10, fill="white") self.scoreC.pack(side="top") self.root.bind("<Up>", self.callup) self.root.bind("<Down>", self.calldown) self.root.bind("<Right>", self.callright) self.root.bind("<Left>", self.callleft) self.createFood() self.right(0) def down(self, i): crd = self.w.coords(1) if len(crd) > 0: if crd[0] == crd[2]: if crd[1] > crd[3]: # print("inside if1") crd[1] -= 10 if crd[1] < crd[3]: # print("inside if2") crd[1] += 10 else: if crd[0] > crd[2]: crd[0] -= 10 if crd[0] < crd[2]: crd[0] += 10 crd[-1] += 10 if i == 0: crd.append(crd[-2]) crd.append(crd[-2]) crd[-3] -= 10 if crd[0] == crd[2] and crd[1] == crd[3]: crd = crd[2:] self.w.coords(1, *crd) self.w.delete(self.head) self.head = self.w.create_line(crd[-2], crd[-1], crd[-2], crd[-1] + 5, width=10, fill="orange") end = self.end() self.checkEaten() i += 1 self.hor = False if not end: self.downid = self.w.after(self.time, self.down, i) else: self.w.delete(1) self.w.delete(self.head) self.w.delete(self.food) self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25, font=Font(family="comic sans MS", size=15), command=lambda: self.callhome()) self.start.pack(side="bottom") def up(self, i): crd = self.w.coords(1) if len(crd) > 0: if crd[0] == crd[2]: if crd[1] > crd[3]: # print("inside if1") crd[1] -= 10 if crd[1] < crd[3]: # print("inside if2") crd[1] += 10 else: if crd[0] > crd[2]: crd[0] -= 10 if crd[0] < crd[2]: crd[0] += 10 crd[-1] -= 10 if i == 0: crd.append(crd[-2]) crd.append(crd[-2]) crd[-3] += 10 if crd[0] == crd[2] and crd[1] == crd[3]: crd = crd[2:] self.w.coords(1, *crd) self.w.delete(self.head) self.head = self.w.create_line(crd[-2], crd[-1], crd[-2], crd[-1] - 5, width=10, fill="orange") end = self.end() self.checkEaten() i += 1 self.hor = False if not end: self.upid = self.w.after(self.time, self.up, i) else: self.w.delete(1) self.w.delete(self.head) self.w.delete(self.food) self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25, font=Font(family="comic sans MS", size=15), command=lambda: self.callhome()) self.start.pack(side="bottom") def right(self, i): crd = self.w.coords(1) if len(crd) > 0: if crd[0] == crd[2]: if crd[1] > crd[3]: # print("inside if1") crd[1] -= 10 if crd[1] < crd[3]: # print("inside if2") crd[1] += 10 else: if crd[0] > crd[2]: crd[0] -= 10 if crd[0] < crd[2]: crd[0] += 10 crd[-2] += 10 if i == 0: crd.append(crd[-2]) crd.append(crd[-2]) crd[-4] -= 10 if crd[0] == crd[2] and crd[1] == crd[3]: crd = crd[2:] self.w.coords(1, *crd) self.w.delete(self.head) self.head = self.w.create_line(crd[-2], crd[-1], crd[-2] + 5, crd[-1], width=10, fill="orange") end = self.end() self.checkEaten() i += 1 self.hor = True if not end: self.rightid = self.w.after(self.time, self.right, i) else: self.w.delete(1) self.w.delete(self.head) self.w.delete(self.food) self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25, font=Font(family="comic sans MS", size=15), command=lambda: self.callhome()) self.start.pack(side="bottom") def left(self, i): crd = self.w.coords(1) if len(crd) > 0: if crd[0] == crd[2]: if crd[1] > crd[3]: # print("inside if1") crd[1] -= 10 if crd[1] < crd[3]: # print("inside if2") crd[1] += 10 else: if crd[0] > crd[2]: crd[0] -= 10 if crd[0] < crd[2]: crd[0] += 10 crd[-2] -= 10 if i == 0: crd.append(crd[-2]) crd.append(crd[-2]) crd[-4] += 10 if crd[0] == crd[2] and crd[1] == crd[3]: crd = crd[2:] self.w.coords(1, *crd) self.w.delete(self.head) self.head = self.w.create_line(crd[-2], crd[-1], crd[-2] - 5, crd[-1], width=10, fill="orange") end = self.end() self.checkEaten() i += 1 self.hor = True if not end: self.leftid = self.w.after(self.time, self.left, i) else: self.w.delete(1) self.w.delete(self.head) self.w.delete(self.food) self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25, font=Font(family="comic sans MS", size=15), command=lambda: self.callhome()) self.start.pack(side="bottom") def createFood(self): # self.w.delete(self.food) #deleting old food. crd = self.w.coords(1) ext = [] for i in crd: ext.append(i) for j in range(-50, 50): ext.append(i + j) randx = random.randrange(20, 730) randy = random.randrange(20, 480) while randx not in ext and randy not in ext: randx = random.randrange(20, 730) randy = random.randrange(20, 480) self.food = self.w.create_line(randx, randy, randx + 12, randy, width=10, fill="yellow") def checkEaten(self): headcoords = self.w.coords(self.head) foodcoords = self.w.coords(self.food) # self.w.delete(self.food) flag = False # print(headcoords[-4]) # print(foodcoords[-4]) # print(foodcoords[-2]) if int(headcoords[-4]) in range( int(foodcoords[-4]) - 7, int(foodcoords[-2]) + 7) and int(headcoords[-3]) in range( int(foodcoords[-1]) - 10, int(foodcoords[-1] + 10)): flag = True if flag: self.grow() self.score += 10 self.scoreC.configure(text="Score\n" + str(self.score), bg="black", fg="teal", padx=25, pady=35, font=Font(family="comic sans MS", size=25)) self.w.delete(self.food) self.createFood() def grow(self): crd = self.w.coords(1) if crd[0] != crd[2]: # horizontal condition if crd[0] < crd[2]: crd[0] -= 20 else: crd[0] += 20 self.w.coords(1, *crd) else: if crd[3] < crd[1]: crd[1] += 20 else: crd[1] -= 20 self.w.coords(1, *crd) def end(self): crd = self.w.coords(1) h = self.w.coords(self.head) a = 0 while a < len(crd) - 2: if crd[a] == crd[a + 2]: if (h[0] == crd[a] and crd[a + 1] < h[1] < crd[a + 3]) or ( h[0] == crd[a] and crd[a + 1] > h[1] > crd[a + 3]): return True else: if (h[1] == crd[a + 1] and crd[a] < h[0] < crd[a + 2]) or ( h[1] == crd[a + 1] and crd[a] > h[0] > crd[a + 2]): return True a += 2 if (h[0] == 0 and 0 < h[1] < 500) or (h[1] == 0 and 0 < h[0] < 750) or ( h[1] == 510 and 0 < h[0] < 750) or (h[0] == 760 and 0 < h[1] < 500): return True return False def callhome(self): self.w.destroy() self.start.destroy() self.H.destroy() self.scoreC.destroy() self.home()
class Map: def __init__(self, parent, name=None, width=20, height=20, tileset_id=2, blockdata_filename=None, config=config): self.parent = parent self.name = name self.config = config self.log = logging.getLogger("{0}.{1}".format(self.__class__.__name__, id(self))) self.blockdata_filename = blockdata_filename if not self.blockdata_filename and self.name: self.blockdata_filename = os.path.join(self.config.map_dir, self.name + '.blk') elif not self.blockdata_filename: self.blockdata_filename = '' asm_filename = '' if self.name: if self.config.asm_dir is not None: asm_filename = os.path.join(self.config.asm_dir, self.name + '.asm') elif self.config.asm_path is not None: asm_filename = self.config.asm_path if os.path.exists(asm_filename): for props in [ map_header(self.name, config=self.config), second_map_header(self.name, config=self.config) ]: self.__dict__.update(props) self.asm = open(asm_filename, 'r').read() self.events = event_header(self.asm, self.name) self.scripts = script_header(self.asm, self.name) self.tileset_id = eval(self.tileset_id, self.config.constants) self.width = eval(self.width, self.config.constants) self.height = eval(self.height, self.config.constants) else: self.width = width self.height = height self.tileset_id = tileset_id if self.blockdata_filename: self.blockdata = bytearray( open(self.blockdata_filename, 'rb').read()) else: self.blockdata = [] self.tileset = Tileset(self.tileset_id, config=self.config) def init_canvas(self, parent=None): if parent == None: parent = self.parent if not hasattr(self, 'canvas'): self.canvas_width = self.width * 32 self.canvas_height = self.height * 32 self.canvas = Canvas(parent, width=self.canvas_width, height=self.canvas_height) self.canvas.xview_moveto(0) self.canvas.yview_moveto(0) def kill_canvas(self): if hasattr(self, 'canvas'): self.canvas.destroy() def crop(self, x1, y1, x2, y2): blockdata = self.blockdata start = y1 * self.width + x1 width = x2 - x1 height = y2 - y1 self.blockdata = [] for y in xrange(height): for x in xrange(width): self.blockdata += [blockdata[start + y * self.width + x]] self.blockdata = bytearray(self.blockdata) self.width = width self.height = height def draw(self): for i in xrange(len(self.blockdata)): block_x = i % self.width block_y = i / self.width self.draw_block(block_x, block_y) def draw_block(self, block_x, block_y): # the canvas starts at 4, 4 for some reason # probably something to do with a border index, indey = 4, 4 # Draw one block (4x4 tiles) block = self.blockdata[block_y * self.width + block_x] for j, tile in enumerate(self.tileset.blocks[block]): try: # Tile gfx are split in half to make vram mapping easier if tile >= 0x80: tile -= 0x20 tile_x = block_x * 32 + (j % 4) * 8 tile_y = block_y * 32 + (j / 4) * 8 self.canvas.create_image(index + tile_x, indey + tile_y, image=self.tileset.tiles[tile]) except: pass
class PigChaseHumanAgent(GuiAgent): def __init__(self, name, environment, keymap, max_episodes, max_actions, visualizer, quit): self._max_episodes = max_episodes self._max_actions = max_actions self._action_taken = 0 self._episode = 1 self._scores = [] self._rewards = [] self._episode_has_ended = False self._episode_has_started = False self._quit_event = quit super(PigChaseHumanAgent, self).__init__(name, environment, keymap, visualizer=visualizer) def _build_layout(self, root): # Left part of the GUI, first person view self._first_person_header = ttk.Label(root, text='First Person View', font=(None, 14, 'bold')) \ .grid(row=0, column=0) self._first_person_view = ttk.Label(root) self._first_person_view.grid(row=1, column=0, rowspan=10) # Right part, top self._first_person_header = ttk.Label(root, text='Symbolic View', font=(None, 14, 'bold')) \ .grid(row=0, column=1) self._symbolic_view = Canvas(root) self._symbolic_view.configure(width=ENV_BOARD_SHAPE[0]*CELL_WIDTH, height=ENV_BOARD_SHAPE[1]*CELL_WIDTH) self._symbolic_view.grid(row=1, column=1) # Bottom information self._information_panel = ttk.Label(root, text='Game stats', font=(None, 14, 'bold')) self._current_episode_lbl = ttk.Label(root, text='Episode: 0', font=(None, 12)) self._cum_reward_lbl = ttk.Label(root, text='Score: 0', font=(None, 12, 'bold')) self._last_action_lbl = ttk.Label(root, text='Previous action: None', font=(None, 12)) self._action_done_lbl = ttk.Label(root, text='Actions taken: 0', font=(None, 12)) self._action_remaining_lbl = ttk.Label(root, text='Actions remaining: 0', font=(None, 12)) self._information_panel.grid(row=2, column=1) self._current_episode_lbl.grid(row=3, column=1, sticky=W, padx=20) self._cum_reward_lbl.grid(row=4, column=1, sticky=W, padx=20) self._last_action_lbl.grid(row=5, column=1, sticky=W, padx=20) self._action_done_lbl.grid(row=6, column=1, sticky=W, padx=20) self._action_remaining_lbl.grid(row=7, column=1, sticky=W, padx=20) self._overlay = None # Main rendering callback self._pressed_binding = root.bind('<Key>', self._on_key_pressed) self._user_pressed_enter = False # UI Update callback root.after(self._tick, self._poll_frame) root.after(1000, self._on_episode_start) root.focus() def _draw_arrow(self, yaw, x, y, cell_width, colour): if yaw == 0.: x1, y1 = (x + .15) * cell_width, (y + .15) * cell_width x2, y2 = (x + .5) * cell_width, (y + .4) * cell_width x3, y3 = (x + .85) * cell_width, (y + .85) * cell_width self._symbolic_view.create_polygon(x1, y1, x2, y3, x3, y1, x2, y2, fill=colour) elif yaw == 90.: x1, y1 = (x + .15) * cell_width, (y + .15) * cell_width x2, y2 = (x + .6) * cell_width, (y + .5) * cell_width x3, y3 = (x + .85) * cell_width, (y + .85) * cell_width self._symbolic_view.create_polygon(x1, y2, x3, y1, x2, y2, x3, y3, fill=colour) elif yaw == 180.: x1, y1 = (x + .15) * cell_width, (y + .15) * cell_width x2, y2 = (x + .5) * cell_width, (y + .6) * cell_width x3, y3 = (x + .85) * cell_width, (y + .85) * cell_width self._symbolic_view.create_polygon(x1, y3, x2, y1, x3, y3, x2, y2, fill=colour) else: x1, y1 = (x + .15) * cell_width, (y + .15) * cell_width x2, y2 = (x + .4) * cell_width, (y + .5) * cell_width x3, y3 = (x + .85) * cell_width, (y + .85) * cell_width self._symbolic_view.create_polygon(x1, y3, x2, y2, x1, y1, x3, y2, fill=colour) def _poll_frame(self): """ Main callback for UI rendering. Called at regular intervals. The method will ask the environment to provide a frame if available (not None). :return: """ cell_width = CELL_WIDTH circle_radius = 10 # are we done? if self._env.done and not self._episode_has_ended: self._on_episode_end() # build symbolic view board, _ = self._env._internal_symbolic_builder.build(self._env) if board is not None: board = board.T self._symbolic_view.delete('all') # Remove all previous items from Tkinter tracking width, height = board.shape for x in range(width): for y in range(height): cell_contents = str.split(str(board[x][y]), '/') for block in cell_contents: if block == 'sand': self._symbolic_view.create_rectangle(x * cell_width, y * cell_width, (x + 1) * cell_width, (y + 1) * cell_width, outline="black", fill="orange", tags="square") elif block == 'grass': self._symbolic_view.create_rectangle(x * cell_width, y * cell_width, (x + 1) * cell_width, (y + 1) * cell_width, outline="black", fill="lawn green", tags="square") elif block == 'lapis_block': self._symbolic_view.create_rectangle(x * cell_width, y * cell_width, (x + 1) * cell_width, (y + 1) * cell_width, outline="black", fill="black", tags="square") elif block == ENV_TARGET_NAMES[0]: self._symbolic_view.create_oval((x + .5) * cell_width - circle_radius, (y + .5) * cell_width - circle_radius, (x + .5) * cell_width + circle_radius, (y + .5) * cell_width + circle_radius, fill='pink') elif block == self.name: yaw = self._env._world_obs['Yaw'] % 360 self._draw_arrow(yaw, x, y, cell_width, 'red') elif block == ENV_AGENT_NAMES[0]: # Get yaw of other agent: entities = self._env._world_obs[ENV_ENTITIES] other_agent = list( map(Entity.create, filter(lambda e: e['name'] == ENV_AGENT_NAMES[0], entities))) if len(other_agent) == 1: other_agent = other_agent.pop() yaw = other_agent.yaw % 360 self._draw_arrow(yaw, x, y, cell_width, 'blue') # display the most recent frame frame = self._env.frame if frame is not None: from PIL import ImageTk self._first_person_view.image = ImageTk.PhotoImage(image=frame) self._first_person_view.configure(image=self._first_person_view.image) self._first_person_view.update() self._first_person_view.update() # process game state (e.g., has the episode started?) if self._episode_has_started and time.time() - self._episode_start_time < 3: if not hasattr(self, "_init_overlay") or not self._init_overlay: self._create_overlay() self._init_overlay.delete("all") self._init_overlay.create_rectangle( 10, 10, 590, 290, fill="white", outline="red", width="5") self._init_overlay.create_text( 300, 80, text="Get ready to catch the pig!", font=('Helvetica', '18')) self._init_overlay.create_text( 300, 140, text=str(3 - int(time.time() - self._episode_start_time)), font=('Helvetica', '18'), fill="red") self._init_overlay.create_text( 300, 220, width=460, text="How to play: \nUse the left/right arrow keys to turn, " "forward/back to move. The pig is caught if it is " "cornered without a free block to escape to.", font=('Helvetica', '14'), fill="black") self._root.update() elif self._episode_has_ended: if not hasattr(self, "_init_overlay") or not self._init_overlay: self._create_overlay() self._init_overlay.delete("all") self._init_overlay.create_rectangle( 10, 10, 590, 290, fill="white", outline="red", width="5") self._init_overlay.create_text( 300, 80, text='Finished episode %d of %d' % (self._episode, self._max_episodes), font=('Helvetica', '18')) self._init_overlay.create_text( 300, 120, text='Score: %d' % sum(self._rewards), font=('Helvetica', '18')) if self._episode > 1: self._init_overlay.create_text( 300, 160, text='Average over %d episodes: %.2f' % (self._episode, np.mean(self._scores)), font=('Helvetica', '18')) self._init_overlay.create_text( 300, 220, width=360, text="Press RETURN to start the next episode, ESC to exit.", font=('Helvetica', '14'), fill="black") self._root.update() elif hasattr(self, "_init_overlay") and self._init_overlay: self._destroy_overlay() # trigger the next update self._root.after(self._tick, self._poll_frame) def _create_overlay(self): self._init_overlay = Canvas(self._root, borderwidth=0, highlightthickness=0, width=600, height=300, bg="gray") self._init_overlay.place(relx=0.5, rely=0.5, anchor='center') def _destroy_overlay(self): self._init_overlay.destroy() self._init_overlay = None def _on_key_pressed(self, e): """ Main callback for keyboard events :param e: :return: """ if e.keysym == 'Escape': self._quit() if e.keysym == 'Return' and self._episode_has_ended: if self._episode >= self._max_episodes: self._quit() # start the next episode self._action_taken = 0 self._rewards = [] self._episode += 1 self._env.reset() self._on_episode_start() print('Starting episode %d' % self._episode) if self._episode_has_started and time.time() - self._episode_start_time >= 3: if e.keysym in self._keymap: mapped_action = self._keymap.index(e.keysym) _, reward, done = self._env.do(mapped_action) self._action_taken += 1 self._rewards.append(reward) self._on_experiment_updated(mapped_action, reward, done) def _on_episode_start(self): self._episode_has_ended = False self._episode_has_started = True self._episode_start_time = time.time() self._on_experiment_updated(None, 0, self._env.done) def _on_episode_end(self): self._episode_has_started = False self._episode_has_ended = True self._scores.append(sum(self._rewards)) self.visualize(self._episode, 'Reward', sum(self._rewards)) def _on_experiment_updated(self, action, reward, is_done): self._current_episode_lbl.config(text='Episode: %d' % self._episode) self._cum_reward_lbl.config(text='Score: %d' % sum(self._rewards)) self._last_action_lbl.config(text='Previous action: %s' % action) self._action_done_lbl.config(text='Actions taken: {0}'.format(self._action_taken)) self._action_remaining_lbl.config(text='Actions remaining: %d' % (self._max_actions - self._action_taken)) self._first_person_view.update() def _quit(self): self._quit_event.set() self._root.quit() sys.exit()
def destroy(self): self.running = False return Canvas.destroy(self)
class LeftNavView(Canvas): def __init__(self, controller, parent): # prev: def __init__(self, main_window, player_, left_nav): self.controller = controller self.parent = parent self.app = self.parent.app self.enabled = False def build(self): if self.enabled: self.redraw() else: self.build_left_nav_menu() self.enabled = True def build_left_nav_menu(self): app = self.app main_window = self.app.main_controller.view player = self.app.game.player # global left_nav, left_canvas, left left_nav = Frame(main_window, height=main_window.sh, width=200, background=app.conf.left_nav_background) left_nav.place(x=0, y=0) # left = LeftNav(main_window, player, left_nav) self.selected_planet = player.selected_planet if isset(player.selected_ship): self.selected_ship_name = player.selected_ship.name else: self.selected_ship_name = "" self.main_window = main_window self.selected_ship_id = 0 self.planet_images = [] self.left_canvas = Canvas(left_nav) self.left_canvas.config(background=app.conf.left_nav_background, highlightthickness=0, height=main_window.sh, width=200) self.left_canvas.place(x=0, y=0) if app.conf.debug_lines == 1: self.left_canvas.create_line(0, 0, 200, main_window.sh, fill='red') self.left_canvas.create_line(200, 0, 0, main_window.sh, fill='red') # left nav values self.logo_image = Image.open(app.conf.title_image_path) self.logo_image.thumbnail([198, 48], Image.ANTIALIAS) self.logo_image_res = ImageTk.PhotoImage(self.logo_image) self.new_planet_image = self.logo_image_res self.planet_images.append(self.new_planet_image) self.label_logo = Label(self.left_canvas, image=self.logo_image_res) self.label_logo.config(background=app.conf.left_nav_background) self.label_logo.planet_image_res = self.logo_image_res # keep a reference! self.label_logo.place(anchor='n', x=100, y=0) # Resources Set row = 0 self.resources_start_y = 55 self.resources_canvas = Canvas(self.left_canvas) self.resources_canvas.config(background=app.conf.left_nav_background, width=198, highlightthickness=0, border=0) self.resources_canvas.grid_propagate(False) self.resources_canvas.place(anchor='nw', x=0, y=self.resources_start_y) self.label_resources = Label(self.resources_canvas, text="Resources:", fg=app.conf.main_text_color) self.label_resources.config(background=app.conf.left_nav_background) self.label_resources.grid(row=row, column=0, sticky='w') row += 1 self.label_planets = Label(self.resources_canvas, text="Planets:", fg=app.conf.second_text_color) self.label_planets.config(background=app.conf.left_nav_background) self.label_planets.grid(row=row, column=0, sticky='w') self.label_planets_val = Label(self.resources_canvas, text=str(len(player.owned_planets)) , fg=app.conf.second_text_color) self.label_planets_val.config(background=app.conf.left_nav_background) self.label_planets_val.grid(row=row, column=1, sticky='e') row += 1 self.label_ships = Label(self.resources_canvas, text="Ships:", fg=app.conf.second_text_color) self.label_ships.config(background=app.conf.left_nav_background) self.label_ships.grid(row=row, column=0, sticky='w') self.label_ships_val = Label(self.resources_canvas, text=len(player.ships), fg=app.conf.second_text_color) self.label_ships_val.config(background=app.conf.left_nav_background) self.label_ships_val.grid(row=row, column=1, sticky='e') row += 1 self.label_allies = Label(self.resources_canvas, text="Allies:", fg=app.conf.second_text_color) self.label_allies.config(background=app.conf.left_nav_background) self.label_allies.grid(row=row, column=0, sticky='w') self.label_allies_val = Label(self.resources_canvas, text=len(player.allies), fg=app.conf.second_text_color) self.label_allies_val.config(background=app.conf.left_nav_background) self.label_allies_val.grid(row=row, column=1, sticky='e') row += 1 self.label_enemies = Label(self.resources_canvas, text="Enemies:", fg=app.conf.second_text_color) self.label_enemies.config(background=app.conf.left_nav_background) self.label_enemies.grid(row=row, column=0, sticky='w') self.label_enemies_val = Label(self.resources_canvas, text=len(player.enemies), fg=app.conf.second_text_color) self.label_enemies_val.config(background=app.conf.left_nav_background) self.label_enemies_val.grid(row=row, column=1, sticky='e') row += 1 self.label_separator = Label(self.resources_canvas, text="", fg=app.conf.left_nav_background, width=24) self.label_separator.config(background=app.conf.left_nav_background) self.label_separator.grid(row=row, columnspan=2, sticky='e,w') # left nav buttons self.left_buttons_start_y = main_window.sh-112 if self.left_buttons_start_y < 500: self.left_buttons_start_y = 500 self.left_buttons_canvas = Canvas(self.left_canvas) self.left_buttons_canvas.config(background=app.conf.left_nav_background, height=200, width=200, highlightthickness=0, border=0) self.left_buttons_canvas.place(anchor='n', x=100, y=self.left_buttons_start_y) self.button_next_planet = Button(self.left_buttons_canvas, text="Next Planet", padx=60 , highlightbackground=app.conf.left_nav_background) self.button_next_ship = Button(self.left_buttons_canvas, text="Next Ship" , highlightbackground=app.conf.left_nav_background) self.button_home_planet = Button(self.left_buttons_canvas, text="Home Planet" , highlightbackground=app.conf.left_nav_background) self.button_end_turn = Button(self.left_buttons_canvas, text="End Turn" , highlightbackground=app.conf.left_nav_background) self.button_next_planet.bind("<Button-1>", self.controller.button_next_planet_clicked) self.button_next_ship.bind("<Button-1>", self.controller.button_next_ship_clicked) self.button_home_planet.bind("<Button-1>", self.controller.button_home_planet_clicked) self.button_end_turn.bind("<Button-1>", self.controller.button_end_turn_clicked) self.button_next_planet.grid(row=0, column=0, sticky='w,e') self.button_next_ship.grid(row=1, column=0, sticky='w,e') self.button_home_planet.grid(row=2, column=0, sticky='w,e') self.button_end_turn.grid(row=3, column=0, sticky='w,e') # Planet Info Set row = 0 self.planet_info_start_y = self.resources_start_y + 115 self.planet_info_canvas = Canvas(self.left_canvas) self.planet_info_canvas.config(background=app.conf.left_nav_background, width=198, highlightthickness=0, border=0) self.planet_info_canvas.grid_propagate(False) self.planet_info_canvas.place(anchor='nw', x=0, y=self.planet_info_start_y) self.label_planet_info = Label(self.planet_info_canvas, text="Planet Info:", fg=app.conf.main_text_color) self.label_planet_info.config(background=app.conf.left_nav_background) self.label_planet_info.grid(row=row, column=0, sticky='w') row += 1 self.label_planet_name = Label(self.planet_info_canvas, text="Name:", fg=app.conf.second_text_color) self.label_planet_name.config(background=app.conf.left_nav_background) self.label_planet_name.grid(row=row, column=0, sticky='w') self.label_planet_name_val = Label(self.planet_info_canvas, text=str(player.selected_planet.name) , fg=app.conf.second_text_color) self.label_planet_name_val.config(background=app.conf.left_nav_background) self.label_planet_name_val.grid(row=row, column=1, sticky='e') row += 1 self.label_planet_metals = Label(self.planet_info_canvas, text="Metals:", fg=app.conf.second_text_color) self.label_planet_metals.config(background=app.conf.left_nav_background) self.label_planet_metals.grid(row=row, column=0, sticky='w') self.label_planet_metals_val = Label(self.planet_info_canvas, text=str(player.selected_planet.metals) , fg=app.conf.second_text_color) self.label_planet_metals_val.config(background=app.conf.left_nav_background) self.label_planet_metals_val.grid(row=row, column=1, sticky='e') row += 1 self.label_planet_food = Label(self.planet_info_canvas, text="Food:", fg=app.conf.second_text_color) self.label_planet_food.config(background=app.conf.left_nav_background) self.label_planet_food.grid(row=row, column=0, sticky='w') self.label_planet_food_val = Label(self.planet_info_canvas, text=str(player.selected_planet.food) , fg=app.conf.second_text_color) self.label_planet_food_val.config(background=app.conf.left_nav_background) self.label_planet_food_val.grid(row=row, column=1, sticky='e') row += 1 self.label_planet_terrain = Label(self.planet_info_canvas, text="Terrain:", fg=app.conf.second_text_color) self.label_planet_terrain.config(background=app.conf.left_nav_background) self.label_planet_terrain.grid(row=row, column=0, sticky='w') self.label_planet_terrain_val = Label(self.planet_info_canvas, text=str(get_terrain(player.selected_planet.terrain)) , fg=app.conf.second_text_color) self.label_planet_terrain_val.config(background=app.conf.left_nav_background) self.label_planet_terrain_val.grid(row=row, column=1, sticky='e') row += 1 self.label_separator_p = Label(self.planet_info_canvas, text="", fg=app.conf.left_nav_background, width=24) self.label_separator_p.config(background=app.conf.left_nav_background) self.label_separator_p.grid(row=row, columnspan=2, sticky='e,w') # ship info row = 0 self.ship_select_start_y = self.planet_info_start_y + 115 self.ship_select_canvas = Canvas(self.left_canvas) self.ship_select_canvas.config(background=app.conf.left_nav_background, width=198, highlightthickness=0, border=0) self.ship_select_canvas.grid_propagate(False) self.ship_select_canvas.place(anchor='nw', x=0, y=self.ship_select_start_y) self.label_ship_select = Label(self.ship_select_canvas, text="Select Ship:", fg=app.conf.main_text_color) self.label_ship_select.config(background=app.conf.left_nav_background) self.label_ship_select.grid(row=row, column=0, sticky='w') # future implementation # if selected_ship.name != '': if isset(self.selected_ship_name): if app.conf.debug == 1: print "Showing Selected Ship (init)" current_ship = player.get_ship(self.selected_ship_name) row += 1 self.listbox_ship = Listbox(self.ship_select_canvas, width=198 , background=app.conf.alternate_left_nav_background, borderwidth=1) self.listbox_ship.config(selectmode=SINGLE) for ship in player.ships: self.listbox_ship.insert(END, ship.name) self.listbox_ship.selection_set(self.selected_ship_id) self.listbox_ship.grid(row=row, columnspan=4, sticky='w,e') self.listbox_ship.bind('<<ListboxSelect>>', self.poll_ship_list) row = 0 self.ship_info_start_y = self.ship_select_start_y + 200 self.ship_info_canvas = Canvas(self.left_canvas) self.ship_info_canvas.config(background=app.conf.left_nav_background, width=198, highlightthickness=0, border=0) self.ship_info_canvas.grid_propagate(False) self.ship_info_canvas.place(anchor='nw', x=0, y=self.ship_info_start_y) self.label_ship_info = Label(self.ship_info_canvas, text="Ship Info:", fg=app.conf.main_text_color) self.label_ship_info.config(background=app.conf.left_nav_background) self.label_ship_info.grid(row=row, column=0, sticky='w') row += 1 self.label_ship_name = Label(self.ship_info_canvas, text="Name:", fg=app.conf.second_text_color) self.label_ship_name.config(background=app.conf.left_nav_background) self.label_ship_name.grid(row=row, column=0, columnspan=2, sticky='w') self.label_ship_name_val = Label(self.ship_info_canvas, text=current_ship.name , fg=app.conf.second_text_color) self.label_ship_name_val.config(background=app.conf.left_nav_background) self.label_ship_name_val.grid(row=row, column=2, columnspan=2, sticky='e') row += 1 self.label_ship_attack = Label(self.ship_info_canvas, text="Attack:", fg=app.conf.second_text_color) self.label_ship_attack.config(background=app.conf.left_nav_background) self.label_ship_attack.grid(row=row, column=0, sticky='w') self.label_ship_attack_val = Label(self.ship_info_canvas, text=current_ship.attack , fg=app.conf.second_text_color) self.label_ship_attack_val.config(background=app.conf.left_nav_background) self.label_ship_attack_val.grid(row=row, column=1, sticky='e') self.label_ship_defense = Label(self.ship_info_canvas, text="Defense:", fg=app.conf.second_text_color) self.label_ship_defense.config(background=app.conf.left_nav_background) self.label_ship_defense.grid(row=row, column=2, sticky='w') self.label_ship_defense_val = Label(self.ship_info_canvas, text=current_ship.defense , fg=app.conf.second_text_color) self.label_ship_defense_val.config(background=app.conf.left_nav_background) self.label_ship_defense_val.grid(row=row, column=3, sticky='e') row += 1 self.label_ship_storage = Label(self.ship_info_canvas, text="Storage:", fg=app.conf.second_text_color) self.label_ship_storage.config(background=app.conf.left_nav_background) self.label_ship_storage.grid(row=row, column=0, columnspan=2, sticky='w') self.label_ship_storage_val = Label(self.ship_info_canvas, text=current_ship.storage , fg=app.conf.second_text_color) self.label_ship_storage_val.config(background=app.conf.left_nav_background) self.label_ship_storage_val.grid(row=row, column=2, columnspan=2, sticky='e') row += 1 self.label_ship_seats = Label(self.ship_info_canvas, text="Seats:", fg=app.conf.second_text_color) self.label_ship_seats.config(background=app.conf.left_nav_background) self.label_ship_seats.grid(row=row, column=0, columnspan=2, sticky='w') self.label_ship_seats_val = Label(self.ship_info_canvas, text=current_ship.seats , fg=app.conf.second_text_color) self.label_ship_seats_val.config(background=app.conf.left_nav_background) self.label_ship_seats_val.grid(row=row, column=2, columnspan=2, sticky='e') row += 1 self.label_separator_s = Label(self.ship_info_canvas, text="", fg=app.conf.left_nav_background, width=24) self.label_separator_s.config(background=app.conf.left_nav_background) self.label_separator_s.grid(row=row, columnspan=4, sticky='e,w') else: if app.conf.debug == 1: print "No Selected Ship Detected (init)" row += 1 self.listbox_ship = Listbox(self.ship_select_canvas, width=198 , background=app.conf.alternate_left_nav_background, borderwidth=1) for ship in player.ships: self.listbox_ship.insert(END, ship.name) self.listbox_ship.grid(row=row, columnspan=4, sticky='w,e') self.listbox_ship.bind('<<ListboxSelect>>', self.poll_ship_list) row += 1 self.label_ship_name = Label(self.ship_select_canvas, text="No Ship Selected", fg=app.conf.second_text_color) self.label_ship_name.config(background=app.conf.left_nav_background) self.label_ship_name.grid(row=row, columnspan=4, sticky='w') row += 1 self.label_separator_s = Label(self.ship_select_canvas, text="", fg=app.conf.left_nav_background, width=24) self.label_separator_s.config(background=app.conf.left_nav_background) self.label_separator_s.grid(row=row, columnspan=4, sticky='e,w') if app.conf.debug == 1: print "CreatedLine:", 0, " ", 0, " ", main_window.sw-200, " ", main_window.sh-200 print "CreatedLine:", main_window.sw-200, " ", 0, " ", 0, " ", main_window.sh-200 print "CurrWin0:", convert_coords_x(main_window, 0), convert_coords_y(main_window, 0) if app.conf.debug == 1: print "Displayed: left_nav,", main_window.sh, ",200" def poll_ship_list(self, event): w = event.widget index = int(w.curselection()[0]) new_ship_name = w.get(index) if isset(self.selected_ship_name): if self.selected_ship_name == "": if new_ship_name != self.selected_ship_name: self.ship_selction_has_changed(new_ship_name) self.selected_ship_name = new_ship_name self.selected_ship_id = w.curselection() if app.conf.debug == 1: print "SelectedShip:", self.selected_ship_name self.redraw(self.main_window, self.player) else: self.selected_ship_name = new_ship_name self.selected_ship_id = w.curselection() self.app.debug(("SelectedShip:", self.selected_ship_name)) self.redraw() def redraw(self): app = self.app main_window = app.main_controller.view player = app.game.player self.player = player app.debug("Redrawing Left Nav") self.label_logo.place(anchor='n', x=100, y=0) self.resources_canvas.config(background=app.conf.left_nav_background, height=main_window.sh-self.resources_start_y-202, width=198, highlightthickness=0, border=0) self.resources_canvas.place(anchor='nw', x=0, y=self.resources_start_y) row = 0 self.label_resources.grid(row=row, column=0, sticky='w') row += 1 self.label_planets.grid(row=row, column=0, sticky='w') self.label_planets_val.config(text=str(len(player.owned_planets))) self.label_planets_val.grid(row=row, column=1, sticky='e') row += 1 self.label_ships.grid(row=row, column=0, sticky='w') self.label_ships_val.config(text=len(player.ships)) self.label_ships_val.grid(row=row, column=1, sticky='e') row += 1 self.label_allies.grid(row=row, column=0, sticky='w') self.label_allies_val.config(text=len(player.allies)) self.label_allies_val.grid(row=row, column=1, sticky='e') row += 1 self.label_enemies.grid(row=row, column=0, sticky='w') self.label_enemies_val.config(text=len(player.enemies)) self.label_enemies_val.grid(row=row, column=1, sticky='e') row += 1 self.label_separator.grid(row=row, columnspan=2, sticky='e,w') # left nav buttons self.left_buttons_start_y = main_window.sh-112 if self.left_buttons_start_y < 500: self.left_buttons_start_y = 500 self.left_buttons_canvas.place(anchor='n', x=100, y=self.left_buttons_start_y) self.button_next_planet.grid(row=0, column=0, sticky='w,e') self.button_next_ship.grid(row=1, column=0, sticky='w,e') self.button_home_planet.grid(row=2, column=0, sticky='w,e') self.button_end_turn.grid(row=3, column=0, sticky='w,e') app.debug(("Left Buttons Start Y:", self.left_buttons_start_y)) # Planet Info Set row = 0 self.planet_info_start_y = self.resources_start_y + 115 self.planet_info_canvas.place(anchor='nw', x=0, y=self.planet_info_start_y) self.label_planet_info.grid(row=row, column=0, sticky='w') row += 1 self.label_planet_name.grid(row=row, column=0, sticky='w') self.label_planet_name_val.config(text=str(player.selected_planet.name)) self.label_planet_name_val.grid(row=row, column=1, sticky='e') row += 1 self.label_planet_metals.grid(row=row, column=0, sticky='w') self.label_planet_metals_val.config(text=str(player.selected_planet.metals)) self.label_planet_metals_val.grid(row=row, column=1, sticky='e') row += 1 self.label_planet_food.grid(row=row, column=0, sticky='w') self.label_planet_food_val.config(text=str(player.selected_planet.food)) self.label_planet_food_val.grid(row=row, column=1, sticky='e') row += 1 self.label_planet_terrain.grid(row=row, column=0, sticky='w') self.label_planet_terrain_val.config(text=str(get_terrain(player.selected_planet.terrain))) self.label_planet_terrain_val.grid(row=row, column=1, sticky='e') row += 1 self.label_separator_p.grid(row=row, columnspan=2, sticky='e,w') # prep for ship section if isset(self.ship_select_canvas): self.ship_select_canvas.destroy() # ship info row = 0 self.ship_select_start_y = self.planet_info_start_y + 115 self.ship_select_canvas = Canvas(self.left_canvas) self.ship_select_canvas.config(background=app.conf.left_nav_background, width=198, highlightthickness=0, border=0) self.ship_select_canvas.grid_propagate(False) self.ship_select_canvas.place(anchor='nw', x=0, y=self.ship_select_start_y) self.label_ship_select = Label(self.ship_select_canvas, text="Select Ship:", fg=app.conf.main_text_color) self.label_ship_select.config(background=app.conf.left_nav_background) self.label_ship_select.grid(row=row, column=0, sticky='w') # future implementation # if selected_ship.name != '': if self.selected_ship_name != "": app.debug("Showing Selected Ship (redraw)") current_ship = player.get_ship(self.selected_ship_name) row += 1 self.listbox_ship = Listbox(self.ship_select_canvas, width=198 , background=app.conf.alternate_left_nav_background, borderwidth=1) self.listbox_ship.config(selectmode=SINGLE) for ship in player.ships: self.listbox_ship.insert(END, ship.name) self.listbox_ship.selection_set(self.selected_ship_id) self.listbox_ship.grid(row=row, columnspan=4, sticky='w,e') self.listbox_ship.bind('<<ListboxSelect>>', self.poll_ship_list) row = 0 self.ship_info_start_y = self.ship_select_start_y + 200 self.ship_info_canvas = Canvas(self.left_canvas) self.ship_info_canvas.config(background=app.conf.left_nav_background, width=198, highlightthickness=0, border=0) self.ship_info_canvas.grid_propagate(False) self.ship_info_canvas.place(anchor='nw', x=0, y=self.ship_info_start_y) self.label_ship_info = Label(self.ship_info_canvas, text="Ship Info:", fg=app.conf.main_text_color) self.label_ship_info.config(background=app.conf.left_nav_background) self.label_ship_info.grid(row=row, column=0, sticky='w') row += 1 self.label_ship_name = Label(self.ship_info_canvas, text="Name:", fg=app.conf.second_text_color) self.label_ship_name.config(background=app.conf.left_nav_background) self.label_ship_name.grid(row=row, column=0, columnspan=2, sticky='w') self.label_ship_name_val = Label(self.ship_info_canvas, text=current_ship.name , fg=app.conf.second_text_color) self.label_ship_name_val.config(background=app.conf.left_nav_background) self.label_ship_name_val.grid(row=row, column=2, columnspan=2, sticky='e') row += 1 self.label_ship_attack = Label(self.ship_info_canvas, text="Attack:", fg=app.conf.second_text_color) self.label_ship_attack.config(background=app.conf.left_nav_background) self.label_ship_attack.grid(row=row, column=0, sticky='w') self.label_ship_attack_val = Label(self.ship_info_canvas, text=current_ship.attack , fg=app.conf.second_text_color) self.label_ship_attack_val.config(background=app.conf.left_nav_background) self.label_ship_attack_val.grid(row=row, column=1, sticky='e') self.label_ship_defense = Label(self.ship_info_canvas, text="Defense:", fg=app.conf.second_text_color) self.label_ship_defense.config(background=app.conf.left_nav_background) self.label_ship_defense.grid(row=row, column=2, sticky='w') self.label_ship_defense_val = Label(self.ship_info_canvas, text=current_ship.defense , fg=app.conf.second_text_color) self.label_ship_defense_val.config(background=app.conf.left_nav_background) self.label_ship_defense_val.grid(row=row, column=3, sticky='e') row += 1 self.label_ship_storage = Label(self.ship_info_canvas, text="Storage:", fg=app.conf.second_text_color) self.label_ship_storage.config(background=app.conf.left_nav_background) self.label_ship_storage.grid(row=row, column=0, columnspan=2, sticky='w') self.label_ship_storage_val = Label(self.ship_info_canvas, text=current_ship.storage , fg=app.conf.second_text_color) self.label_ship_storage_val.config(background=app.conf.left_nav_background) self.label_ship_storage_val.grid(row=row, column=2, columnspan=2, sticky='e') row += 1 self.label_ship_seats = Label(self.ship_info_canvas, text="Seats:", fg=app.conf.second_text_color) self.label_ship_seats.config(background=app.conf.left_nav_background) self.label_ship_seats.grid(row=row, column=0, columnspan=2, sticky='w') self.label_ship_seats_val = Label(self.ship_info_canvas, text=current_ship.seats , fg=app.conf.second_text_color) self.label_ship_seats_val.config(background=app.conf.left_nav_background) self.label_ship_seats_val.grid(row=row, column=2, columnspan=2, sticky='e') row += 1 self.label_separator_s = Label(self.ship_info_canvas, text="", fg=app.conf.left_nav_background, width=24) self.label_separator_s.config(background=app.conf.left_nav_background) self.label_separator_s.grid(row=row, columnspan=4, sticky='e,w') else: app.debug("No Selected Ship Detected (redraw)") row += 1 self.listbox_ship = Listbox(self.ship_select_canvas, width=198 , background=app.conf.alternate_left_nav_background, borderwidth=1) for ship in player.ships: self.listbox_ship.insert(END, ship.name) self.listbox_ship.grid(row=row, columnspan=2, sticky='w,e') self.listbox_ship.bind('<<ListboxSelect>>', self.poll_ship_list) row += 1 self.label_ship_name = Label(self.ship_select_canvas, text="No Ship Selected", fg=app.conf.second_text_color) self.label_ship_name.config(background=app.conf.left_nav_background) self.label_ship_name.grid(row=row, columnspan=2, sticky='w') row += 1 self.label_separator_s = Label(self.ship_select_canvas, text="", fg=app.conf.left_nav_background, width=24) self.label_separator_s.config(background=app.conf.left_nav_background) self.label_separator_s.grid(row=row, columnspan=4, sticky='e,w')
class Map: def __init__(self, parent, name=None, width=20, height=20, tileset_id=2, blockdata_filename=None, config=config): self.parent = parent self.name = name self.config = config self.log = logging.getLogger("{0}.{1}".format(self.__class__.__name__, id(self))) self.blockdata_filename = blockdata_filename if not self.blockdata_filename and self.name: self.blockdata_filename = os.path.join(self.config.map_dir, self.name + '.blk') elif not self.blockdata_filename: self.blockdata_filename = '' asm_filename = '' if self.name: if self.config.asm_dir is not None: asm_filename = os.path.join(self.config.asm_dir, self.name + '.asm') elif self.config.asm_path is not None: asm_filename = self.config.asm_path if os.path.exists(asm_filename): for props in [map_header(self.name, config=self.config), second_map_header(self.name, config=self.config)]: self.__dict__.update(props) self.asm = open(asm_filename, 'r').read() self.events = event_header(self.asm, self.name) self.scripts = script_header(self.asm, self.name) self.tileset_id = eval(self.tileset_id, self.config.constants) self.width = eval(self.width, self.config.constants) self.height = eval(self.height, self.config.constants) else: self.width = width self.height = height self.tileset_id = tileset_id if self.blockdata_filename: self.blockdata = bytearray(open(self.blockdata_filename, 'rb').read()) else: self.blockdata = [] self.tileset = Tileset(self.tileset_id, config=self.config) def init_canvas(self, parent=None): if parent == None: parent = self.parent if not hasattr(self, 'canvas'): self.canvas_width = self.width * 32 self.canvas_height = self.height * 32 self.canvas = Canvas(parent, width=self.canvas_width, height=self.canvas_height) self.canvas.xview_moveto(0) self.canvas.yview_moveto(0) def kill_canvas(self): if hasattr(self, 'canvas'): self.canvas.destroy() def crop(self, x1, y1, x2, y2): blockdata = self.blockdata start = y1 * self.width + x1 width = x2 - x1 height = y2 - y1 self.blockdata = [] for y in xrange(height): for x in xrange(width): self.blockdata += [blockdata[start + y * self.width + x]] self.blockdata = bytearray(self.blockdata) self.width = width self.height = height def draw(self): for i in xrange(len(self.blockdata)): block_x = i % self.width block_y = i / self.width self.draw_block(block_x, block_y) def draw_block(self, block_x, block_y): # the canvas starts at 4, 4 for some reason # probably something to do with a border index, indey = 4, 4 # Draw one block (4x4 tiles) block = self.blockdata[block_y * self.width + block_x] for j, tile in enumerate(self.tileset.blocks[block]): try: # Tile gfx are split in half to make vram mapping easier if tile >= 0x80: tile -= 0x20 tile_x = block_x * 32 + (j % 4) * 8 tile_y = block_y * 32 + (j / 4) * 8 self.canvas.create_image(index + tile_x, indey + tile_y, image=self.tileset.tiles[tile]) except: pass
class MainNavView(Frame): def __init__(self, controller, parent): self.controller = controller self.parent = parent self.app = self.controller.app self.enabled = False self.has_selected = False self.planet_images = [] self.main_window = controller.parent.view self.main_nav = Frame(self.main_window, height=self.main_window.sh, width=self.main_window.sw - 200, background='black') # self.main_nav = Frame.__init__(self.main_window, height=self.main_window.sh, width=self.main_window.sw - 200, background='black') self.main_nav.place(x=200, y=0) self.main_canvas = Canvas(self.parent) self.main_canvas_has_been_created = True def build(self): # formerly build_main_nav self.app.debug("Building Main Nav View") if self.enabled: self.main_canvas.destroy() self.build_planet_view() else: self.build_planet_view() self.enabled = True def build_planet_view(self): app = self.app main_window = app.main_controller.view player = app.game.player # global main_canvas_has_been_created, main_nav, main_canvas self.app.debug(("Displayed: main_nav,", main_window.sw - 200, ",", main_window.sh)) # draw corner lines if self.app.conf.debug_lines == 1: self.main_canvas.create_line(0, 0, main_window.sw - 200, main_window.sh, fill='red') self.main_canvas.create_line(main_window.sw - 200, 0, 0, main_window.sh, fill='red') if self.app.conf.debug == 1: print "CreatedLine:", 0, " ", 0, " ", main_window.sw - 200, " ", main_window.sh print "CreatedLine:", main_window.sw - 200, " ", 0, " ", 0, " ", main_window.sh print "CurrWin0:", self.convert_coordinates_x(0), self.convert_coordinates_y(0) self.main_canvas.config(width=main_window.sw - 200, height=main_window.sh) self.main_canvas.config(background='black') self.main_canvas.config(highlightbackground=self.app.conf.main_background) self.main_canvas.config(highlightthickness=0) if self.app.conf.debug == 1: print "*********************" print "***Drawing Planets***" print "*********************" # draw planets for planet in player.planets: if self.app.conf.debug == 1: print "init:", planet.loc.x, ",", planet.loc.y if planet == player.selected_planet: self.draw_planet_highlighted(planet) else: self.draw_planet(planet) self.finish_drawing_planets() def redraw_planet_view(self): app = self.app main_window = app.main_controller.view if self.main_canvas_has_been_created: self.main_canvas.config(width=main_window.sw - 200, height=main_window.sh) self.main_canvas.delete('all') self.finish_drawing_planets() self.app.debug("Redraw:AlreadyCreated") else: self.build_planet_view() self.app.debug("Redraw:New") def finish_drawing_planets(self): self.main_canvas.pack(fill='both') main_window = self.controller.parent.view self.app.debug(("WindowSize:", main_window.sw, ":", main_window.sh)) def draw_planet(self, planet): # global main_nav, main_canvas, label, planet_images, main_window new_x = self.convert_coordinates_x(planet.loc.x) new_y = self.convert_coordinates_y(planet.loc.y) name_y = self.convert_coordinates_name(planet.loc.y, planet.loc.size) color = self.get_terrain_color(planet.terrain) size = planet.loc.size, planet.loc.size planet_image = Image.open(self.get_terrain_image(planet.terrain)) planet_image.thumbnail(size, Image.ANTIALIAS) planet_image_res = ImageTk.PhotoImage(planet_image) new_planet_image = planet_image_res self.planet_images.append(new_planet_image) label = Label(self.main_canvas) label.config(image=planet_image_res) label.config(background='black') label.grid() label.planet_image_res = planet_image_res # keep a reference! label.place(anchor=CENTER, x=new_x, y=new_y) label.bind("<Button-1>", lambda event, arg=planet: self.controller.select_planet(event, arg)) label_name = Label(self.main_canvas, text=planet.name, fg=self.app.conf.main_text_color, bg='black' , borderwidth=1 , highlightthickness=0) label_name.place(anchor=CENTER, x=new_x, y=name_y) if self.app.conf.debug == 1: print "Drawing planet: [", planet.name, ",", new_x, ",", new_y, ",", planet.loc.size, ",", color, "]" def draw_planet_highlighted(self, planet): # global main_nav, main_canvas, label, planet_images, main_window new_x = self.convert_coordinates_x(planet.loc.x) new_y = self.convert_coordinates_y(planet.loc.y) name_y = self.convert_coordinates_name(planet.loc.y, planet.loc.size) color = self.get_terrain_color(planet.terrain) size = planet.loc.size, planet.loc.size planet_image = Image.open(self.get_terrain_image(planet.terrain)) planet_image.thumbnail(size, Image.ANTIALIAS) planet_image_res = ImageTk.PhotoImage(planet_image) new_planet_image = planet_image_res self.planet_images.append(new_planet_image) label_planet = Label(self.main_canvas) label_planet.config(image=planet_image_res) label_planet.config(background='black') label_planet.planet_image_res = planet_image_res # keep a reference! label_planet.place(anchor=CENTER, x=new_x, y=new_y) label_planet.bind("<Button-1>", lambda event, arg=planet: self.controller.select_planet(event, arg)) label_name = Label(self.main_canvas, text=planet.name, fg='red', bg='black', borderwidth=1 , highlightthickness=0) label_name.place(anchor=CENTER, x=new_x, y=name_y) if self.app.conf.debug == 1: print "Drawing planet: [", planet.name, ",", new_x, ",", new_y, ",", planet.loc.size, ",", color, "]" # get nearest planet and draw a line if self.has_selected: nearest_planet = self.get_nearest_planet(planet) l = self.get_line_points((planet.loc.x, planet.loc.y) , (nearest_planet.loc.x, nearest_planet.loc.y) , planet.loc.size , nearest_planet.loc.size) self.main_canvas.create_line(l.x1, l.y1, l.x2, l.y2, fill='blue', dash=(4, 4)) self.main_canvas.pack() self.app.debug(("Drawing line:", l.x1, ',', l.y1, ',', l.x2, ',', l.y2)) else: self.app.debug("Line next time") self.has_selected = True def draw_planet_h(self, planet): # global main_nav, main_canvas, label, planet_images, main_window new_x = self.convert_coordinates_x(planet.loc.x) new_y = self.convert_coordinates_y(planet.loc.y) name_y = self.convert_coordinates_name(planet.loc.y, planet.loc.size) color = self.get_terrain_color(planet.terrain) size = planet.loc.size, planet.loc.size planet_image = Image.open(self.get_terrain_image(planet.terrain)) planet_image.thumbnail(size, Image.ANTIALIAS) planet_image_res = ImageTk.PhotoImage(planet_image) new_planet_image = planet_image_res self.planet_images.append(new_planet_image) label_planet = Label(self.main_canvas) label_planet.config(image=planet_image_res) label_planet.config(background='black') label_planet.planet_image_res = planet_image_res # keep a reference! label_planet.place(anchor=CENTER, x=new_x, y=new_y) label_planet.bind("<Button-1>", lambda event, arg=planet: self.controller.select_planet(event, arg)) label_name = Label(self.main_canvas, text=planet.name, fg='red', bg='black', borderwidth=1 , highlightthickness=0) label_name.place(anchor=CENTER, x=new_x, y=name_y) if self.app.conf.debug == 1: print "Drawing planet: [", planet.name, ",", new_x, ",", new_y, ",", planet.loc.size, ",", color, "]" def get_nearest_planet(self, planet): planets = self.app.game.player.planets distances = {} for i in range(len(planets)): if planets[i].name != planet.name: print i tmp = self.get_distance(planet, planets[i]) distances[i] = tmp self.app.debug(("Found nearest planet:", planets[min(distances)].name, "and", planet.name)) self.draw_planet_h(planets[min(distances)]) return planets[min(distances)] @staticmethod def get_distance(planet1, planet2): return hypot(planet2.loc.x - planet1.loc.x, planet2.loc.y - planet1.loc.y) def redraw_planet(self, planet): self.draw_planet(self.app.game.player.last_selected_planet) self.draw_planet_highlighted(planet) @staticmethod def get_terrain_color(terrain): """ :param terrain: :return: # Planet Terrains # 1 Ice # 2 Rock # 3 Green # 4 Water # 5 Alien """ if terrain == 1: return 'ice' elif terrain == 2: return 'rock' elif terrain == 3: return 'green' elif terrain == 4: return 'water' elif terrain == 5: return 'alien' else: return 'black' def get_terrain_image(self, terrain): # Planet Terrains # 1 Ice # 2 Rock # 3 Green # 4 Water # 5 Alien if terrain == 1: return self.app.conf.ice_planet_image_path elif terrain == 2: return self.app.conf.rock_planet_image_path elif terrain == 3: return self.app.conf.green_planet_image_path elif terrain == 4: return self.app.conf.water_planet_image_path elif terrain == 5: return self.app.conf.alien_planet_image_path else: return self.app.conf.alien_planet_image_path def convert_coordinates_x(self, x): main_window = self.app.main_controller.view return ((main_window.sw - 200) / 2) + x def convert_coordinates_y(self, y): main_window = self.app.main_controller.view return (main_window.sh / 2) + y def convert_coordinates_name(self, y, size): main_window = self.app.main_controller.view return (main_window.sh / 2) + y - (size / 2) - self.app.conf.planet_name_height @staticmethod def angle(pt1, pt2): x1, y1 = pt1 x2, y2 = pt2 deltax = x2 - x1 deltay = y2 - y1 angle_rad = atan2(deltay, deltax) angle_deg = angle_rad * 180.0 / pi # return angle_rad return angle_deg def get_line_points(self, p1, p2, p1width, p2width): # initialize vars x1, y1 = p1 x2, y2 = p2 self.app.debug(("x1", x1)) self.app.debug(("y1", y1)) self.app.debug(("x2", x2)) self.app.debug(("y2", y2)) # x3 = 0 # y3 = 0 # x4 = 0 # y4 = 0 # get angle1 a1 = self.angle(p1, p2) # determine line start distance from planet centers o1 = 2 * p1width o2 = 2 * p2width # get first point of the line x3 = x1 + (cos(a1) * o1) y3 = y1 + (sin(a1) * o1) # get angle 2 a2 = (90 + a1) - 180 # establish 2nd point of the line x4 = x2 + (cos(a2) * o2) y4 = y2 + (sin(a2) * o2) # convert coordinates for window size x3 = self.convert_coordinates_x(x3) y3 = self.convert_coordinates_y(y3) x4 = self.convert_coordinates_x(x4) y4 = self.convert_coordinates_y(y4) # create object to return line_points = LinePoints(x3, y3, x4, y4) return line_points def get_line_points_(self, p1, p2, p1width, p2width): # initialize vars x1, y1 = p1 x2, y2 = p2 # x3 = 0 # y3 = 0 # x4 = 0 # y4 = 0 # get angle1 a1 = self.angle(p1, p2) # determine line start distance from planet centers o1 = 2 * p1width o2 = 2 * p2width # get first point of the line x3 = x1 + (cos(a1) * o1) y3 = y1 + (sin(a1) * o1) # get angle 2 a2 = (90 + a1) - 180 # establish 2nd point of the line x4 = x2 + (cos(a2) * o2) y4 = y2 + (sin(a2) * o2) # create object to return line_points = LinePoints(x3, y3, x4, y4) return line_points