def main(): root = TK.Tk() cv1 = TK.Canvas(root, width=300, height=200, bg='#ddffff') cv2 = TK.Canvas(root, width=300, height=200, bg='#ffeeee') cv1.pack() cv2.pack() s1 = TurtleScreen(cv1) s1.bgcolor(0.85, 0.85, 1) s2 = TurtleScreen(cv2) s2.bgcolor(1, 0.85, 0.85) p = RawTurtle(s1) q = RawTurtle(s2) p.color('red', (1, 0.85, 0.85)) p.width(3) q.color('blue', (0.85, 0.85, 1)) q.width(3) for t in (p, q): t.shape('turtle') t.lt(36) q.lt(180) for t in (p, q): t.begin_fill() for i in range(5): for t in (p, q): t.fd(50) t.lt(72) for t in (p, q): t.end_fill() t.lt(54) t.pu() t.bk(50) return 'EVENTLOOP'
class Gamefield: """Die Klasse Bescreibt wie ein Feld aussieht (Muss kein Gamefeld sein)""" def __init__(self, tkFrame, backgroundColor): self.rootWindow = TurtleScreen(tkFrame) self.rootWindow.bgcolor(backgroundColor) self.rootWindow.tracer(0) def getRootWindow(self): return self.rootWindow # In der gameListenToPresskey Methode werden alle move Methoden einem Tastatur-Knopf zugewiesen. (für die erste Schlange) def gameListenToPresskey(self, basilisk): self.rootWindow.listen() self.rootWindow.onkeypress(basilisk.moveUpwards, "Up") self.rootWindow.onkeypress(basilisk.moveDownwards, "Down") self.rootWindow.onkeypress(basilisk.moveLeftwards, "Left") self.rootWindow.onkeypress(basilisk.moveRightwards, "Right") # In der gameListenToPresskey Methode werden alle move Methoden einem Tastatur-Knopf zugewiesen. (für die zweite Schlange) def gameListenToPresskeyForTowPlayer(self, basilisk): self.rootWindow.listen() self.rootWindow.onkeypress(basilisk.moveUpwards, "w") self.rootWindow.onkeypress(basilisk.moveDownwards, "s") self.rootWindow.onkeypress(basilisk.moveLeftwards, "a") self.rootWindow.onkeypress(basilisk.moveRightwards, "d") def gamefieldUpdate(self): self.rootWindow.update() def gamefieldMainloop(self): self.rootWindow.mainloop() def addShape(self, gif): self.rootWindow.addshape(gif)
def main(): root = TK.Tk() cv1 = TK.Canvas(root, width=300, height=200, bg="#ddffff") cv2 = TK.Canvas(root, width=300, height=200, bg="#ffeeee") cv1.pack() cv2.pack() s1 = TurtleScreen(cv1) s1.bgcolor(0.85, 0.85, 1) s2 = TurtleScreen(cv2) s2.bgcolor(1, 0.85, 0.85) p = RawTurtle(s1) q = RawTurtle(s2) p.color("red", (1, 0.85, 0.85)) p.width(3) q.color("blue", (0.85, 0.85, 1)) q.width(3) for t in p,q: t.shape("turtle") t.lt(36) q.lt(180) for t in p, q: t.begin_fill() for i in range(5): for t in p, q: t.fd(50) t.lt(72) for t in p,q: t.end_fill() t.lt(54) t.pu() t.bk(50) return "EVENTLOOP"
def Rank(): root = TK.Tk() cv1 = TK.Canvas(root, width=400, height=200) cv1.pack() s1 = TurtleScreen(cv1) s1.bgcolor("#42f4ad") t = RawTurtle(s1) t.hideturtle() t.penup() t.goto(-50,70) t.write("내가 예측한 1등: "+ guess) t.goto(-50,50) if PlayerNumber>=1: t.write("1등 : "+PlayerRank[0]) t.goto(-50,40) if PlayerNumber>=2: t.write("2등 : "+PlayerRank[1]) t.goto(-50,30) if PlayerNumber>=3: t.write("3등 : "+PlayerRank[2]) t.goto(-50,20) if PlayerNumber>=4: t.write("4등 : "+PlayerRank[3]) t.goto(-50,10) if PlayerNumber>=5: t.write("5등 : "+PlayerRank[4]) t.goto(-100,-20) if(guess==PlayerRank[0]): t.write("축하드립니다. 1등을 맞추셨습니다.") else: t.write("1등을 맞추지 못했습니다.")
class KonnaRakendus(Frame): """Frame, mida saab suvalises teises rakenduses kasutada""" def __init__(self, parent): super().__init__(parent) # Sisuliselt sama kui Tk() # Määrame rea ja veeru indeksiga 0 kõige kaalukamateks self.rowconfigure(index=0, weight=1) self.columnconfigure(index=0, weight=1) # Tekita lõuend, seo see root objektiga c = Canvas(self) # Lõuendi nähtavaks muutmiseks paigutame ta lahtrisse 0,0 c.grid(column=0, row=0, sticky=(N, S, W, E)) # Seo lõuendiga TurtleScreen ja seo TurtleScreeniga konn self.ts = TurtleScreen(c) self.algseis() # Tekitame nuppude paneeli f f = Frame(self) f.grid(column=0, row=1) # Tekita edasiliikumise nupp b = Button(f, text="Edasi", command=self.edasi) b.grid(column=0, row=0) # Tekita vasakpöörde nupp bv = Button(f, text="Vasakule", command=self.vasakule) bv.grid(column=1, row=0) # Tekita parempöörde nupp bp = Button(f, text="Paremale", command=self.paremale) bp.grid(column=2, row=0) # Tekita muutuja kiirus ja sildiga tekstikast kiiruse sisestamiseks self.kiirus = IntVar() self.kiirus.set(100) lbl_kiirus = Label(f, text=" Kiirus: ") lbl_kiirus.grid(column=3, row=0) entry_kiirus = Entry(f, textvariable=self.kiirus) entry_kiirus.grid(column=4, row=0) # Tekita algseisu nupp ba = Button(f, text="Algseis", command=self.algseis) ba.grid(column=5, row=0) def algseis(self): self.ts.clear() self.ts.bgcolor('cyan') self.konn = Frog(self.ts, x=0, y=0) def edasi(self): self.konn.forward(self.kiirus.get() / 2) self.konn.jump(self.kiirus.get() / 2) def vasakule(self): self.konn.left(10) def paremale(self): self.konn.right(10)
#!/usr/bin/python ## DEMONSTRATES USE OF 2 CANVASES, SO CANNOT BE RUN IN DEMOVIEWER! """turtle example: Using TurtleScreen and RawTurtle for drawing on two distinct canvases. """ from turtle import TurtleScreen, RawTurtle, TK root = TK.Tk() cv1 = TK.Canvas(root, width=300, height=200, bg="#ddffff") cv2 = TK.Canvas(root, width=300, height=200, bg="#ffeeee") cv1.pack() cv2.pack() s1 = TurtleScreen(cv1) s1.bgcolor(0.85, 0.85, 1) s2 = TurtleScreen(cv2) s2.bgcolor(1, 0.85, 0.85) p = RawTurtle(s1) q = RawTurtle(s2) p.color("red", (1, 0.85, 0.85)) p.width(3) q.color("blue", (0.85, 0.85, 1)) q.width(3) for t in p,q: t.shape("turtle") t.lt(36) q.lt(180)
def main(): player_N = 15 root = TK.Tk() canvas = TK.Canvas(root, width=1200, height=700, bg="#ddffff") canvas.pack() turtleScreen = TurtleScreen(canvas) turtleScreen.bgcolor("gray") turtleScreen.tracer(0,0) pl = [] for i in range(player_N): #プレイヤーの生成 random.seed() window_h = turtleScreen.window_height()/2 window_w = turtleScreen.window_width()/2 x = random.uniform(-window_w,window_w) y = random.uniform(-window_h,window_h) m = random.uniform(1,5) R = 600 pl_type = random.choice(["high_level_predator","middle_level_predator","low_level_predator","producer"]) k_high = random.uniform(0,150) k_middle = random.uniform(0,150) k_low = random.uniform(0,150) k_producer = random.uniform(0,150) if pl_type == "high_level_predator": #k_high = 0 pass elif pl_type == "middle_level_predator": k_middle = 0 k_high *= -1 elif pl_type == "low_level_predator": #k_low = 0 k_high *= -1 k_middle *= -1 elif pl_type == "producer": #k_producer = 0 k_high *= -1 k_middle *= -1 k_low *= -1 pl.append(Player(turtleScreen,pl_type,(x,y),k_high,k_middle,k_low,k_producer,m,R)) turtleScreen.update() #time.sleep(1) while(1): for me in turtleScreen.turtles(): me.acc -= me.acc for you in turtleScreen.turtles(): r = you.pos()-me.pos() r_d = abs(r) if me != you and r_d<me.R and you.isvisible(): me.acc += (me.get_K(you)/(me.m*pow(r_d,3)))*r if me.strengthpower == you.strengthpower: me.acc = 0.3*me.acc+0.7*((r_d/me.R)*me.acc + ((me.R-r_d)/me.R)*you.acc) if r_d<10 : if me.strengthpower > you.strengthpower: you.hiding() me.energy += you.energy me.v -= 1.1*me.v elif me.strengthpower == you.strengthpower: me.v = -0.1*r me.v += me.acc if abs(me.v)>10: me.v = me.v*(10/abs(me.v)) me.setpos(me.pos()+me.v) if me.xcor()<-600 or me.xcor()>600 or me.ycor()<-350 or me.ycor()>350: me.v = (-0.5/abs(me.pos()))*me.pos() me.acc -= me.acc #print(me.energy) turtleScreen.update() time.sleep(0.01)
import turtle from tkinter import * from tkinter.ttk import * #Uuema valjanagemisega tkinter from turtle import TurtleScreen, RawTurtle root = Tk() root.title('Kochi kõver nuppudega') root.rowconfigure(index=0, weight=1) root.columnconfigure(index=0, weight=1) c = Canvas(root) c.grid(column=0, row=0, sticky=(N, S, W, E)) ts = TurtleScreen(c) ts.bgcolor('cyan') turtle = RawTurtle(ts) turtle.color('green') turtle.penup() turtle.setposition(0, -500) turtle.pendown() def koch(): joonista_koch(pikkus.get(), min_pikkus.get()) def joonista_koch(pikkus, min_pikkus=1): if pikkus >= min_pikkus: turtle.speed(0) joonista_koch(pikkus / 3, min_pikkus)
def loadAndDraw(load, draw, indicatorList, trades): def get_mouse_click_coor(x, y): print(x, y) barNumber = round(x / 10) barNumber = max(1, barNumber) print("Bar Number: ", barNumber, " ", d[startPt + barNumber - 1], " ", o[startPt + barNumber - 1], " ", highestHigh) # tkMessageBox("Information",str(barNumber) # # trtl.write('Vivax Solutions', font=("Arial", 20, "bold")) # chosing the font ## trtl.goto(10,highestHigh-.05*(highestHigh - lowestLow)) ## trtl.pendown() indexVal = startPt + barNumber - 1 outPutStr = str(d[indexVal]) + " " + str(o[indexVal]) + " " + str( h[indexVal]) + " " + str(l[indexVal]) + " " + str( c[indexVal]) # chosing the font root.focus_set() T.focus_set() T.insert(tk.END, outPutStr + "\n") ## trtl.goto(20,highestHigh-60) ## trtl.write(str(o[50-(50-barNumber)]), font=("Arial", 8, "bold")) # chosing the font ## trtl.goto(20,highestHigh-80) ## trtl.write(str(h[50-(50-barNumber)]), font=("Arial", 8, "bold")) # chosing the font ## trtl.goto(20,highestHigh-100) ## trtl.write(str(l[50-(50-barNumber)]), font=("Arial", 8, "bold")) # chosing the font ## trtl.goto(20,highestHigh-120) ## trtl.write(str(c[50-(50-barNumber)]), font=("Arial", 8, "bold")) # chosing the font ## ## #root.withdraw() if load == True: cnt = 0 file = askopenfilename( filetypes=(('CSV files', '*.csv'), ('TXT files', '*.txt'), ('POR files', '*.por')), title='Select Markets or Ports. To Test- CSV format only!') with open(file) as f: f_csv = csv.reader(f) numDecs = 0 for row in f_csv: numCols = len(row) cnt += 1 d.append(int(row[0])) dt.append(datetime.datetime.strptime(row[0], '%Y%m%d')) o.append(float(row[1])) h.append(float(row[2])) l.append(float(row[3])) c.append(float(row[4])) v.append(float(row[5])) oi.append(float(row[6])) oString = str(o[-1]) if '.' in oString: decLoc = oString.index('.') numDecs = max(numDecs, len(oString) - decLoc - 1) xDate = list() yVal = list() zVal = list() w.Button5.configure(state="normal") w.Entry1.insert(0, str(d[-1])) if draw == True: startDrawDateStr = w.Entry1.get() startDrawDate = int(startDrawDateStr) cnt = -1 for x in range(0, len(d)): cnt += 1 if startDrawDate >= d[x]: startPt = x numBarsPlot = 60 if startPt + numBarsPlot > len(d): startPt = len(d) - (numBarsPlot + 1) print(startPt, " ", len(d), " ", numBarsPlot) indicCnt = 0 screen = TurtleScreen(w.Canvas1) trtl = RawTurtle(screen) screen.tracer(False) screen.bgcolor('white') clr = ['red', 'green', 'blue', 'yellow', 'purple'] trtl.pensize(6) trtl.penup() trtl.color("black") highestHigh = 0 lowestLow = 99999999 # scaleMult = 10**numDecs scaleMult = 1 for days in range(startPt, startPt + numBarsPlot): if h[days] * scaleMult > highestHigh: highestHigh = h[days] * scaleMult if l[days] * scaleMult < lowestLow: lowestLow = l[days] * scaleMult hhllDiffScale = (highestHigh - lowestLow) / 1.65 hhllDiff = highestHigh - lowestLow botOfChart = lowestLow screen.setworldcoordinates(-10, highestHigh - hhllDiffScale, 673, highestHigh) print(highestHigh, " ", lowestLow) m = 0 trtl.setheading(0) trtl.penup() for i in range(startPt, startPt + numBarsPlot + 1): m = m + 1 trtl.goto(m * 10, h[i] * scaleMult) trtl.pendown() trtl.goto(m * 10, l[i] * scaleMult) trtl.penup() trtl.goto(m * 10, c[i] * scaleMult) trtl.pendown() trtl.goto(m * 10 + 5, c[i] * scaleMult) trtl.penup() trtl.goto(m * 10, o[i] * scaleMult) trtl.pendown() trtl.goto(m * 10 - 5, o[i] * scaleMult) trtl.penup() trtl.goto(10, highestHigh) print("Indicator List: ", indicatorList) if len(indicatorList) != 0: movAvgParams = list([]) if "movAvg" in indicatorList: movAvgVal = 0 movAvgParamIndexVal = indicatorList.index("movAvg") movAvgParams.append(indicatorList[movAvgParamIndexVal + 1]) movAvgParams.append(indicatorList[movAvgParamIndexVal + 2]) movAvgParams.append(indicatorList[movAvgParamIndexVal + 3]) for j in range(0, 3): n = 0 trtl.penup() if j == 0: trtl.color("red") if j == 1: trtl.color("green") if j == 2: trtl.color("blue") for i in range(startPt, startPt + numBarsPlot): n = n + 1 movAvgVal = 0 for k in range(i - movAvgParams[j], i): movAvgVal = movAvgVal + c[k] * scaleMult if movAvgParams[j] != 0: movAvgVal = movAvgVal / movAvgParams[j] if i == startPt: trtl.goto(n * 10, movAvgVal) trtl.pendown() trtl.goto(n * 10, movAvgVal) trtl.penup() # print("PlotTrades : ",plotTrades) if trades.draw: debugTradeDate = tradeDate[0] debugDate = d[startPt] n = 0 while debugTradeDate <= debugDate: n += 1 debugTradeDate = tradeDate[n] m = 0 for i in range(startPt, startPt + numBarsPlot): m = m + 1 debugDate = d[i] if debugDate == debugTradeDate: trtl.penup() tradeValue = tradePrice[n] if tradeType[n] == "buy": trtl.color("Green") trtl.goto(m * 10 - 5, tradeValue - hhllDiff * .03) trtl.pensize(3) trtl.pendown() trtl.goto(m * 10, tradeValue) trtl.goto(m * 10 + 5, tradeValue - hhllDiff * .03) trtl.penup() if tradeType[n] == "sell": trtl.color("Red") trtl.goto(m * 10 - 5, tradeValue + hhllDiff * .03) trtl.pensize(3) trtl.pendown() trtl.goto(m * 10, tradeValue) trtl.goto(m * 10 + 5, tradeValue + hhllDiff * .03) trtl.penup() if tradeType[n] == "longLiq": trtl.color("Blue") trtl.penup() trtl.goto(m * 10 - 5, tradeValue) trtl.pensize(3) trtl.pendown() trtl.goto(m * 10 + 5, tradeValue) trtl.penup() trtl.pensize(1) print("Found a trade: ", tradeValue, " ", debugTradeDate, " m= ", m, " ", tradeValue - hhllDiff * .05) n += 1 if n < len(tradeDate): debugTradeDate = tradeDate[n] trtl.color("black") trtl.goto(-10, botOfChart) trtl.pendown() trtl.goto(673, botOfChart) trtl.penup() trtl.goto(-10, botOfChart) m = 0 for i in range(startPt, startPt + numBarsPlot): if i % 10 == 0: m = m + 1 trtl.pendown() trtl.write(str(d[i]), font=("Arial", 8, "bold")) # chosing the font trtl.penup() trtl.goto(m * 100, botOfChart) trtl.penup() trtl.goto(628, highestHigh) trtl.pendown() trtl.goto(628, botOfChart) trtl.penup() m = 0 vertIncrement = hhllDiff / 10 for i in range(0, 11): trtl.goto(630, highestHigh - m * vertIncrement) trtl.pendown() trtl.write(str(highestHigh - m * vertIncrement), font=("Arial", 8, "bold")) trtl.penup() m += 1 # turtle.done() screen.onscreenclick(get_mouse_click_coor)
win_width = master.winfo_screenwidth() win_height = master.winfo_screenheight() x = (win_width / 2) - (app_width / 2) y = (win_height / 2) - (app_height / 2) master.geometry(f"{app_width}x{app_height}+{int(x)}+{int(y)}") master.overrideredirect(True) master.after(2000, lambda: master.destroy()) WIDTH, HEIGHT = 450, 450 canvas = Canvas(master, width=WIDTH, height=HEIGHT, bg="green") canvas.pack(ipadx=30) root = TurtleScreen(canvas) turtle = RawTurtle(root, visible=False) root.bgcolor("white") turtle.color('#F09F13') turtle.pensize(4) turtle.speed(15) turtle.hideturtle() turtle.penup() turtle.setposition(70, 90) turtle.pendown() turtle.fillcolor("#F09F13") turtle.begin_fill() turtle.circle(40) turtle.end_fill() turtle.hideturtle()
from turtle import TurtleScreen, RawTurtle, TK root = TK.Tk() cv1 = TK.Canvas(root, width=500, height=500, bg="#ddffff") cv1.pack() s1 = TurtleScreen(cv1) s1.bgcolor("orange") p = RawTurtle(s1) t = RawTurtle(s1) p.begin_fill() p.circle(60) p.end_fill() TK.mainloop()
from turtle import TK, TurtleScreen, RawTurtle root=TK.Tk() cv1 = TK.Canvas(root,width=300,height=200,bg='yellow') cv2 = TK.Canvas(root,width=300,height=200,bg='blue') cv1.pack() cv2.pack() top = TurtleScreen(cv1) top.bgcolor('yellow') top_turtle=RawTurtle(top) bottom=TurtleScreen(cv2) bottom.bgcolor('blue') bottom_turtle=RawTurtle(bottom) TK.mainloop()
from turtle import TurtleScreen, RawTurtle, TK root = TK.Tk() cv1 = TK.Canvas(root, width=500, height=500, bg="#ddffff") cv1.pack() s1 = TurtleScreen(cv1) s1.bgcolor("orange") p = RawTurtle(s1) t = RawTurtle(s1)
class TurtleGraphics(BasicGUI): """GUI with graphics created using 'turtle'.""" _WORLD_COORDS = (-2, -2, 10, 10) _PEG_OFFSET = (0, 0.4) HADES = (0, 12) best_move = None @classmethod def _add_offset(cls, position): """Adds offset to peg's position coordinates.""" peg_pos = tuple(map(add, position, cls._PEG_OFFSET)) peg_pos = tuple(round(i, 1) for i in peg_pos) return peg_pos @classmethod def _subtract_offset(cls, position): """Subtracts offset from peg's position coordinates.""" peg_pos = tuple(map(sub, position, cls._PEG_OFFSET)) peg_pos = tuple(map(int, peg_pos)) return peg_pos def _draw_board(self): """Draws board.""" tri = ((-1.5, -0.5), (4, 9.5), (9.5, -0.5)) artist = RawPen(self.window) # Draws grooves in wood: artist.pen(pendown=False, pensize=2, speed=0) x1, y1, x2, y2 = __class__._WORLD_COORDS for y in range(y1, y2 + 1, 2): artist.goto(x1, y) artist.pendown() artist.goto(x2, y) artist.penup() # Draws board: artist.pen(pencolor=(34, 16, 0), fillcolor=(51, 25, 0), pensize=6, speed=0) artist.goto(tri[-1]) artist.pendown() artist.begin_fill() for coord in tri: artist.goto(coord) artist.end_fill() # Draws peg holes: artist.pen(pencolor="gray", fillcolor="black", pensize=1) for peg_hole in self.game.board: artist.penup() artist.goto(peg_hole) artist.pendown() artist.begin_fill() artist.circle(0.4) artist.end_fill() artist.penup() artist.goto(__class__.HADES) def _place_pegs(self): """Places pegs.""" for peg_hole in self.game.board: if self.game.board[peg_hole]: start_point = __class__._add_offset(peg_hole) peg = Peg(start_point, self) self.peg_dir.append(peg) def _add_callbacks(self): """Adds callbacks to buttons.""" self.undo_btn["command"] = self.game.undo self.restart_btn["command"] = self.game.restart self.show_moves_btn["command"] = self.show_legal_moves self.best_move_btn["command"] = self.show_best_move def _find_best_move(self): """Finds best move possible for current game.""" if len(self.game.moves) <= 3: with shelve.open("paths") as db: best_paths = db[str(self.game.moves)] best_path = choice(best_paths) else: self.path_finder(self.game) best_path = self.path_finder.best_path best_move = best_path[len(self.game.moves)] best_move = (__class__._add_offset(best_move[0]), best_move[1]) return best_move def _disable_all(self): """Disables all buttons and pegs.""" self.undo_btn["state"] = "disabled" self.restart_btn["state"] = "disabled" self.show_moves_btn["state"] = "disabled" self.best_move_btn["state"] = "disabled" for peg in self.peg_dir: peg.moveable = False def _restore_all(self): """Enables pegs and buttons that would normally be enabled.""" self.update_gui() for peg in self.peg_dir: peg.moveable = True def _delayed_callback(self, arrows): """Banishes arrows and restores GUI.""" for arrow in arrows: arrow.banish() self._restore_all() def construct(self): """Constructs graphics.""" self.window = TurtleScreen(self.canvas) self.window.setworldcoordinates(*__class__._WORLD_COORDS) self.window.bgcolor(102, 51, 0) self.peg_dir = [] self.arrow_dir = [] self.graveyard = [] self.path_finder = PathFinder() self._draw_board() self._place_pegs() self._add_callbacks() def update_(self, peg, move): """Updates the graphics when a move is made.""" midpoint = __class__._add_offset(self.game._midpoint(peg, move)) lower_bound = (midpoint[0], midpoint[1] - 0.01) upper_bound = (midpoint[0], midpoint[1] + 0.01) dead_peg = [ peg for peg in self.peg_dir if peg.pos() > lower_bound and peg.pos() < upper_bound ][0] dead_peg.goto(__class__.HADES) self.peg_dir.remove(dead_peg) self.graveyard.append(dead_peg) def erase(self): """Updates the graphics when a move is undone.""" last_peg_pos = __class__._add_offset( tuple(map(add, *self.game.moves[-1]))) last_peg = [ peg for peg in self.peg_dir if abs(peg.pos() - last_peg_pos) < 0.1 ][0] last_peg.goto(__class__._add_offset(self.game.moves[-1][0])) last_peg.start_point = last_peg.pos() revived_peg = self.graveyard.pop() revived_peg.goto(revived_peg.start_point) self.peg_dir.append(revived_peg) def reset_(self): """Updates the graphics when the game is restarted.""" for obj in [self.window, self.peg_dir, self.arrow_dir, self.graveyard]: del obj self.canvas.destroy() self.canvas = Canvas(self.mainframe, width=500, height=500, relief="sunken", borderwidth=3) self.canvas.grid(row=1, column=1, sticky=(N, S, E, W)) self.construct() def show_legal_moves(self): """Shows the player all legal moves.""" self._disable_all() move_count = 0 legal_moves = self.game.find_legal_moves() for val in legal_moves.values(): for move in val: move_count += 1 arrows_needed = move_count - len(self.arrow_dir) for task in range(arrows_needed): self.arrow_dir.append(Arrow(self)) used_arrows = [] arrow_count = 0 for start_peg in legal_moves: for move in legal_moves[start_peg]: arrow = self.arrow_dir[arrow_count] origin = __class__._add_offset(start_peg) destination = tuple(map(add, origin, move)) arrow.draw(origin, destination) used_arrows.append(arrow) arrow_count += 1 self.root.after(3000, self._delayed_callback, used_arrows) def show_best_move(self): """Shows the player the best move to make next.""" self._disable_all() if not self.arrow_dir: self.arrow_dir.append(Arrow(self)) arrow = self.arrow_dir[0] origin = self.best_move[0] destination = tuple(map(add, origin, self.best_move[1])) arrow.draw(origin, destination) self.root.after(3000, self._delayed_callback, [arrow]) def update_peg_moves(self): """Updates move list for all pegs and updates best move, if required.""" legal_moves = self.game.find_legal_moves() for peg in self.peg_dir: board_pos = __class__._subtract_offset(peg.pos()) peg.possible_moves = legal_moves.get(board_pos, []) if legal_moves and self.game.moves: self.best_move = self._find_best_move() def update_gui(self): """Updates GUI to reflect current game conditions.""" legal_moves = self.game.find_legal_moves() if self.game.moves: self.undo_btn["state"] = "!disabled" self.restart_btn["state"] = "!disabled" self.best_move_btn["state"] = "!disabled" else: self.undo_btn["state"] = "disabled" self.restart_btn["state"] = "disabled" if legal_moves: self.show_moves_btn["state"] = "!disabled" else: self.show_moves_btn["state"] = "disabled" if legal_moves and self.game.moves: self.best_move_btn["state"] = "!disabled" else: self.best_move_btn["state"] = "disabled"
from turtle import RawTurtle, TurtleScreen from tkinter import Tk, Canvas WIDTH = 1200 HEIGHT = 675 START_POS = (-WIDTH / 2), (-HEIGHT / 2) + HEIGHT / 20 # print(START_POS) root = Tk() # set up canvas canvas = Canvas(root, width=WIDTH, height=HEIGHT, highlightthickness=0) turtle_screen = TurtleScreen(canvas) turtle_screen.bgcolor("black") canvas.pack() # set up turtle turt = RawTurtle(turtle_screen) turt.hideturtle() turt.speed(0) turt.pencolor("RED") turt.width(3) turt.up() turt.setx(START_POS[0]) turt.sety(START_POS[1]) turt.down() farthest_pos = [0, 0] def update_pos():
#!/usr/bin/env python3 ## DEMONSTRATES USE OF 2 CANVASES, SO CANNOT BE RUN IN DEMOVIEWER! """turtle example: Using TurtleScreen and RawTurtle for drawing on two distinct canvases. """ from turtle import TurtleScreen, RawTurtle, TK root = TK.Tk() cv1 = TK.Canvas(root, width=300, height=200, bg="#ddffff") cv2 = TK.Canvas(root, width=300, height=200, bg="#ffeeee") cv1.pack() cv2.pack() s1 = TurtleScreen(cv1) s1.bgcolor(0.85, 0.85, 1) s2 = TurtleScreen(cv2) s2.bgcolor(1, 0.85, 0.85) p = RawTurtle(s1) q = RawTurtle(s2) p.color("red", (1, 0.85, 0.85)) p.width(3) q.color("blue", (0.85, 0.85, 1)) q.width(3) for t in p, q: t.shape("turtle") t.lt(36) q.lt(180)
CANVAS_HEIGHT = int(CANVAS_WIDTH * 9 / 16) # Produces the eye-pleasing 16:9 HD aspect ratio. # Create a Tkinter graphics window graphics_window = TK.Tk() graphics_window.title("Lab 5 Problems") # Create a "canvas" inside the graphics window to draw on my_canvas = TK.Canvas(graphics_window, width=CANVAS_WIDTH, height=CANVAS_HEIGHT) my_canvas.pack() # Organizes my_canvas inside the graphics window # Create a "canvas" made specifically for turtle graphics turtle_canvas = TurtleScreen(my_canvas) turtle_canvas.bgcolor("white") # Create a turtle to draw on the canvas mary = RawTurtle(turtle_canvas) #---------------------------------------------------------------------- # Problems 1 # Write a program that prints "We like Python's turtles!" 1000 times. #---------------------------------------------------------------------- # for i in range(1000): # print("We like Python's turtles!") # ---------------------------------------------------------------------- # Problems 6 # Write a program that asks the user for the number of sides, the length