def main(): t = Turtle() t.speed('fast') t.pensize(10) draw_loop(t, 20, 10) t.clear() draw_olympics_logo(t, 50) t.clear() draw_telerik_logo(t, 200) done()
def random_color(): r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) return r, g, b # Draw Square for _ in range(4): timmy.forward(50) timmy.right(90) # Dash Line timmy.clear() timmy.reset() for i in range(10): if i % 2 == 0: timmy.color("blue") else: timmy.color("white") timmy.forward(10) timmy.color("red") for i in range(10): if i % 2 == 0: timmy.penup() else: timmy.pendown() timmy.forward(10)
for e in enemies: y = e.ycor() y -= 10 e.sety(y) winsound.PlaySound('cartoon060.wav', winsound.SND_ASYNC) enemyspeed *= -1 # Bullet and enemy collision if isCollision(bullet, enemy): bullet.hideturtle() bulletstate = 'ready' bullet.setposition(0, -400) enemy.hideturtle() score = score + 10 scorestring = 'Score: %s' % score sp.clear() sp.write(scorestring, False, align='left', font=('Arial', 14, 'normal')) winsound.PlaySound('invaderkilled.wav', winsound.SND_ASYNC) # Player and enemy collision if isCollision(enemy, player): player.hideturtle() enemy.hideturtle() score = score - score print('Game Over!') winsound.PlaySound('explosion.wav', winsound.SND_ASYNC) time.sleep(3) exit() # Moving the bullet if bulletstate == 'fire':
t.write(str(message), font=style) colors = ['red', 'orange', 'yellow', 'dark green', 'blue', 'purple'] winsound.PlaySound('Flyflyfly', winsound.SND_ASYNC) s = Screen() s.screensize() s.setup(width=1.0, height=1.0) screenheight = s.window_height() screenwidth = s.window_width() s.bgcolor('black') rules = Turtle() writeAt(rules, 'People in a City', 0, 0, 'white', 30, 'center') time.sleep(5) timeseconds = 0 rules.clear() writeAtB(rules, 'You have 10 seconds to observe the crowd.', -480, 150, 'white', 16) writeAtB( rules, 'Your score is the absolute value of the difference between your guess and the actual amount.', -480, 120, 'white', 16) writeAtB(rules, 'Smaller score = better. (0 is the best)', -480, 90, 'white', 16) writeAtB(rules, 'A window will pop up for you to submit response.', -480, 60, 'white', 16) writeAtB(rules, 'Press enter to submit.', -480, 30, 'white', 16) writeAtB(rules, 'Good luck! Have fun.', -480, 0, 'white', 20) while timeseconds < 10: timeseconds += 1 time.sleep(1)
class Game: def __init__(self): self.screen = Screen() self.artist = Turtle(visible=False) self.artist.up() self.artist.speed("slowest") self.snake = Snake() self.food = Food(100, 0) self.counter = 0 self.commandpending = False self.screen.tracer(0) self.screen.listen() self.screen.onkey(self.snakedown, "Down") self.screen.onkey(self.snakeup, "Up") self.screen.onkey(self.snakeleft, "Left") self.screen.onkey(self.snakeright, "Right") def nextFrame(self): self.artist.clear() if (self.snake.nextposition[0], self.snake.nextposition[1]) == (self.food.x, self.food.y): self.snake.eatFood() self.food.changelocation() else: self.snake.moveOneStep() if self.counter == 10: self.food.changestate() self.counter = 0 else: self.counter += 1 self.food.drawself(self.artist) self.snake.drawself(self.artist) self.screen.update() self.screen.ontimer(lambda: self.nextFrame(), 100) def snakeup(self): if not self.commandpending: self.commandpending = True self.snake.moveup() self.commandpending = False def snakedown(self): if not self.commandpending: self.commandpending = True self.snake.movedown() self.commandpending = False def snakeleft(self): if not self.commandpending: self.commandpending = True self.snake.moveleft() self.commandpending = False def snakeright(self): if not self.commandpending: self.commandpending = True self.snake.moveright() self.commandpending = False
iter = Turtle() cleanwriter = Turtle() iter.ht() cleanwriter.ht() iter.penup() cleanwriter.penup() iter.setpos(0, -h / 2 + 50) cleanwriter.setpos(0, -h / 2 + 20) room_state = list(Room_state.keys()) state = SimpleQueue() state.put_nowait(((choice(room_state)), choice(room_state))) while True: iter.clear() cleanwriter.clear() iter.write("Iteration : " + str(count), align="center", font=("Arial", 16, "normal")) cleanwriter.write("Times Cleaned : " + str(cleaned), align="center", font=("Arial", 16, "normal")) condition = state.get_nowait() stateA = condition[0] stateB = condition[1] X.clear() Y.clear()
t.right(90) t.forward(l) def drawQuad(l, w): t.forward(l) t.right(90) t.forward(w) t.right(90) t.forward(l) t.right(90) t.forward(w) t = Turtle() t.clear() t.speed(52) # draw boundary #t.penup() #t.backward(200) #t.left(90) #t.forward(200) #t.right(90) #t.pendown() #drawQuad(500, 500) #take pen to center #t.backward(200) #t.right(90)
class Game(object): NBADDR = ((-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)) def __init__(self): screen.tracer(False) screen.setup(width=MAX_X*SQUARE_WIDTH + DM, height = (MAX_Y+FREEROWS)*SQUARE_WIDTH + DM, startx = -20, starty = 20) screen.screensize(MAX_X*SQUARE_WIDTH + DM - 50, (MAX_Y+FREEROWS)*SQUARE_WIDTH + DM -50) self.designer = Turtle(visible=False) starttime = time.clock() self.messagero = Turtle(visible=False) self.messagero.penup() self.messagero.pencolor("blue") self.messagero.goto(0, -(MAX_Y+FREEROWS)*SQUARE_WIDTH/2+6) self.message("Please wait a moment!") self.designer.pencolor("gray90") for c in range(MAX_X+1): self.line((-MAX_X/2. -.5 + c)*SQUARE_WIDTH + MARG_X, ((-MAX_Y + FREEROWS)/2. -.5 + 0)*SQUARE_WIDTH + MARG_Y, (-MAX_X/2. -.5 + c)*SQUARE_WIDTH + MARG_X, ((-MAX_Y + FREEROWS)/2. -.5 + MAX_Y)*SQUARE_WIDTH + MARG_Y) for r in range(MAX_Y+1): self.line((-MAX_X/2. -.5 + 0)*SQUARE_WIDTH + MARG_X, ((-MAX_Y + FREEROWS)/2. -.5 + r)*SQUARE_WIDTH + MARG_Y, (-MAX_X/2. -.5 + MAX_X)*SQUARE_WIDTH + MARG_X, ((-MAX_Y + FREEROWS)/2. -.5 + r)*SQUARE_WIDTH + MARG_Y) screen.update() self.patches = {} for r in range(MAX_Y): for c in range(MAX_X): self.patches[(c, r)] = Patch(c, r) self.state = set([(41,33), (42,33), (43,34), (42,32), (42,34)]) for cell in self.state: self.patches[cell].showturtle() self.newstate = None stoptime = time.clock() print(stoptime - starttime) screen.update() screen.onkey(self.run, "space") screen.onkey(screen.bye, "Escape") screen.onkey(self.clear, "c") screen.listen() screen.onclick(self.toggle) self.message("spacebar:start/pause | left click:toggle cell | c:clear" " | escape:quit") def message(self, txt): self.messagero.clear() self.messagero.write(txt, align="center", font=("Courier", 14, "bold")) def line(self, x1, y1, x2, y2): self.designer.penup() self.designer.goto(x1, y1) self.designer.pendown() self.designer.goto(x2, y2) def calcnext(self): cd = {} for (x,y) in self.state: for dx, dy in Game.NBADDR: xx, yy = x+dx, y+dy cd[(xx,yy)] = cd.get((xx,yy), 0) + 1 cd[(x,y)] = cd.get((x,y), 0) + 10 td = [] for c in cd: if cd[c] not in [3, 12, 13]: td.append(c) for c in td: del cd[c] return set(cd.keys()) def update_display(self): screen.tracer(False) for cell in self.newstate - self.state: try: self.patches[cell].showturtle() except: pass for cell in self.state - self.newstate: try: self.patches[cell].hideturtle() except: pass screen.tracer(True) def clear(self): self.newstate = set() self.update_display() self.state = set() def toggle(self, x, y): cell = cellindices(x, y) self.newstate = self.state.copy() if cell in self.newstate: self.newstate.discard(cell) else: self.newstate.add(cell) self.update_display() self.state = self.newstate def run(self): starttime = time.clock() anzahl_generationen = 0 screen.onkey(self.stop, "space") self.RUNNING = True while self.RUNNING: self.newstate = self.calcnext() self.update_display() self.state = self.newstate anzahl_generationen +=1 stoptime = time.clock() t = stoptime - starttime print(anzahl_generationen, t, anzahl_generationen/t) def stop(self): self.RUNNING = False screen.onkey(self.run, "space")
class Game(object): NBADDR = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)) def __init__(self): screen.tracer(False) screen.setup(width=MAX_X * SQUARE_WIDTH + DM, height=(MAX_Y + FREEROWS) * SQUARE_WIDTH + DM, startx=-20, starty=20) screen.screensize(MAX_X * SQUARE_WIDTH + DM - 50, (MAX_Y + FREEROWS) * SQUARE_WIDTH + DM - 50) self.designer = Turtle(visible=False) starttime = time.clock() self.messagero = Turtle(visible=False) self.messagero.penup() self.messagero.pencolor("blue") self.messagero.goto(0, -(MAX_Y + FREEROWS) * SQUARE_WIDTH / 2 + 6) self.message("Please wait a moment!") self.designer.pencolor("gray90") for c in range(MAX_X + 1): self.line( (-MAX_X / 2. - .5 + c) * SQUARE_WIDTH + MARG_X, ((-MAX_Y + FREEROWS) / 2. - .5 + 0) * SQUARE_WIDTH + MARG_Y, (-MAX_X / 2. - .5 + c) * SQUARE_WIDTH + MARG_X, ((-MAX_Y + FREEROWS) / 2. - .5 + MAX_Y) * SQUARE_WIDTH + MARG_Y) for r in range(MAX_Y + 1): self.line( (-MAX_X / 2. - .5 + 0) * SQUARE_WIDTH + MARG_X, ((-MAX_Y + FREEROWS) / 2. - .5 + r) * SQUARE_WIDTH + MARG_Y, (-MAX_X / 2. - .5 + MAX_X) * SQUARE_WIDTH + MARG_X, ((-MAX_Y + FREEROWS) / 2. - .5 + r) * SQUARE_WIDTH + MARG_Y) screen.update() self.patches = {} for r in range(MAX_Y): for c in range(MAX_X): self.patches[(c, r)] = Patch(c, r) self.state = set([(41, 33), (42, 33), (43, 34), (42, 32), (42, 34)]) for cell in self.state: self.patches[cell].showturtle() self.newstate = None stoptime = time.clock() print(stoptime - starttime) screen.update() screen.onkey(self.run, "space") screen.onkey(screen.bye, "Escape") screen.onkey(self.clear, "c") screen.listen() screen.onclick(self.toggle) self.message("spacebar:start/pause | left click:toggle cell | c:clear" " | escape:quit") def message(self, txt): self.messagero.clear() self.messagero.write(txt, align="center", font=("Courier", 14, "bold")) def line(self, x1, y1, x2, y2): self.designer.penup() self.designer.goto(x1, y1) self.designer.pendown() self.designer.goto(x2, y2) def calcnext(self): cd = {} for (x, y) in self.state: for dx, dy in Game.NBADDR: xx, yy = x + dx, y + dy cd[(xx, yy)] = cd.get((xx, yy), 0) + 1 cd[(x, y)] = cd.get((x, y), 0) + 10 td = [] for c in cd: if cd[c] not in [3, 12, 13]: td.append(c) for c in td: del cd[c] return set(cd.keys()) def update_display(self): screen.tracer(False) for cell in self.newstate - self.state: try: self.patches[cell].showturtle() except: pass for cell in self.state - self.newstate: try: self.patches[cell].hideturtle() except: pass screen.tracer(True) def clear(self): self.newstate = set() self.update_display() self.state = set() def toggle(self, x, y): cell = cellindices(x, y) self.newstate = self.state.copy() if cell in self.newstate: self.newstate.discard(cell) else: self.newstate.add(cell) self.update_display() self.state = self.newstate def run(self): starttime = time.clock() anzahl_generationen = 0 screen.onkey(self.stop, "space") self.RUNNING = True while self.RUNNING: self.newstate = self.calcnext() self.update_display() self.state = self.newstate anzahl_generationen += 1 stoptime = time.clock() t = stoptime - starttime print(anzahl_generationen, t, anzahl_generationen / t) def stop(self): self.RUNNING = False screen.onkey(self.run, "space")
turtle2.st() stageCount = 0 ##Create the stageCount variable while True: ##Loop till the convo ends if stageCount == 0: ##Stage 0 of the conversation turtle1.write("Hey hows it going dude?", align='center') sleep(3) turtle2.write("Yeah I'm pretty good dude, how's you?", align='center') sleep(5) elif stageCount == 1: ##Stage 1 of the convo turtle1.write("Yeah I'm pretty good bro. Is your fridge running?", align='center') sleep(3) turtle2.write("Yeah... I should hope so dude", align='center') sleep(5) elif stageCount == 2: ##Stage 2 of the convo turtle1.write("Then you had better go catch it then!", align='center') sleep(6) turtle2.write("...", align='center') sleep(5) elif stageCount == 3: ##Stage 3 of the convo turtle2.write("Ugh. Get the hell out of here jim", align='center') sleep(2) turtle1.write(":(", align='center') sleep(10) break ##Clear both turtles dialogue after they have finished a stage turtle1.clear() turtle2.clear() stageCount += 1 ##Increment the stage count by 1 once a stage has completed
class NewWindow(object): def __init__(self): self.root = turtle._root = Tk() self.fields = {} pane = PanedWindow(orient=VERTICAL, sashwidth=1, sashrelief=SOLID, bg='#ddd') pane.add(self.addButton(pane, 'calculate', command = self.calculate)) pane.add(self.addTextField(pane, 'input')) pane.add(self.makeGraphFrame(pane)) pane.add(self.addButton(pane, 'clear', command = self.refreshCanvas)) pane.add(self.addTextField(pane, 'scale', str(scale))) pane.add(self.addButton(pane, 'refresh scale', command = self.refreshscale)) pane.add(self.addButton(pane, 'restart', command = main)) pane.grid(row=0, columnspan=4, sticky='news') self.dirty = False self.t = Turtle() self.t.hideturtle() self.g = Turtle() self.g.hideturtle() self.nscale = self.fields['scale'] self.input = self.fields['input'] makegraph(self.g) self.errortext='" This equation contains a detail that has not been fully resolved' self.rungraphs=[] def addTextField(self, master, name, text = 'f(x)=', row = 2, column =1, columnspan = 1, rowspan = 1, width = 20, sticky = N+E, state = NORMAL): """Creates and inserts a text field at the row and column, and returns the text field.""" field = strField(master, text, width, state) master.rowconfigure(row, weight = 1) master.columnconfigure(column, weight = 1) field.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) self.fields[name] = field return field def addButton(self, master, text, row = 1, column =1, columnspan = 1, rowspan = 1, command = lambda: None, state = NORMAL): """Creates and inserts a button at the row and column, and returns the button.""" button = Button(master, text = text, command = command, state = state) master.rowconfigure(row, weight = 1) master.columnconfigure(column, weight = 1) button.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5) return button def makeGraphFrame(self, root): turtle._Screen._root = root self.canvwidth = 850 self.canvheight = 850 turtle._Screen._canvas = self._canvas = canvas = turtle.ScrolledCanvas( root, 800, 550, self.canvwidth, self.canvheight) canvas.adjustScrolls() self.screen = _s_ = turtle.Screen() turtle.TurtleScreen.__init__(_s_, _s_._canvas) self.scanvas = _s_._canvas turtle.RawTurtle.screens = [_s_] return canvas def get(self): return self.input.get() def refreshCanvas(self, boolean = True): if self.dirty: self.t.clear() self.dirty=False if boolean: self.rungraphs=[] def clearCanvas(self): self.refreshCanvas() self.screen._delete('all') self.scanvas.config(cursor='') self.configGUI(NORMAL, DISABLED, DISABLED) def calculate(self): original = self.get() try: neq = create(original) except Exception as e: print(repr(e)) if original.endswith(self.errortext): return self.input.set(original + self.errortext) return t = self.t if neq in self.rungraphs: return try: graph(t, neq) except Exception as e: print(repr(e)) if original.endswith(self.errortext): return self.input.set(original + self.errortext) return self.rungraphs.append(neq) self.dirty=True def refreshscale(self): global scale nscale = self.nscale.get() if is_float(nscale) and float(nscale)>0 and float(nscale) != scale: graph(self.t, create('0')) self.dirty = True scale = tryint(float(nscale)) self.refreshCanvas(False) self.g.clear() makegraph(self.g) if self.rungraphs: for neq in self.rungraphs: graph(self.t, neq) self.dirty = True else: nscale = self.nscale.set(str(scale))
class Drawing(): def __init__(self): """ This drawing class is for practicing drawing simple or even geometrical pictures with turtle module. Let's apply this method with easy examples. gb = turtle.Turtle() ; gb.rigth, left, forward, backward, circle, shape, shapesize, penup, pendown, home, clear You can get a lot of detail information by googling 'python turtle'. """ self.gb = Turtle() self.gb.shape('turtle') self.gb.speed(6) #self.screen = self.gb.getscreen() #w = 150 #self.screen.setworldcoordinates(-w,-w,w,w) print 'A cute turtle is ready to draw!' def swirl(self,shape='turtle',speed=0): self.gb.shape(shape) self.gb.speed(speed) self.gb.color('black') for i in range(500): self.gb.forward(i) self.gb.right(98) def color_swirl(self,shape='turtle',speed=0): self.gb.shape(shape) self.gb.speed(speed) for i in range(500): color = colorsys.hsv_to_rgb(i/1000.0,1.0,1.0) self.gb.color(color) self.gb.forward(i) self.gb.right(98) def zigzag(self,shape='turtle',speed=0): self.gb.shape(shape) self.gb.speed(speed) for i in range(180): self.gb.forward(100) self.gb.right(30) self.gb.forward(20) self.gb.left(60) self.gb.forward(50) self.gb.right(30) self.gb.penup() self.gb.setposition(0,0) self.gb.pendown() self.gb.right(2) def square(self,shape='turtle',speed=0): self.gb.shape(shape) self.gb.speed(speed) for i in range(400): self.gb.forward(i) self.gb.left(90.5) def gohome(self): wiggle = [30,30,30,30] self.gb.shape('turtle') self.gb.speed(6) self.gb.clear() self.gb.penup() for tick in wiggle: self.gb.right(tick) self.gb.left(tick) self.gb.home() self.gb.clear() self.gb.pendown() self.gb.color('black')
class NCSimVisualizer: def __init__(self, cfg_os): # Create Screen Object self.screen = Screen() # Add app icon LOGO_PATH = "assets/favicon.ico" # do not forget "@" symbol and .xbm format for Ubuntu LOGO_LINUX_PATH = "@assets/favicon_linux.xbm" # Use the same Tk root with turtle: # noinspection PyProtectedMember # assert isinstance(self.screen._root, tk.Tk) # True # noinspection PyProtectedMember self.root = self.screen.getcanvas().winfo_toplevel() self.root.title("Network Coding Simulator") if cfg_os.lower() == "linux": self.root.iconbitmap(LOGO_LINUX_PATH) else: self.root.iconbitmap(LOGO_PATH) # tkinter use same root self.controls = tk.Frame(self.root) # Create Screen Layout Cursor self.layout_cursor = Turtle() self.layout_cursor.ht() self.layout_cursor.penup() self.layout_cursor.pensize(3) self.layout_cursor.color("slate grey") # Create Screen Message Cursor self.msg_cursor = Turtle() self.msg_cursor.ht() self.msg_cursor.penup() self.msg_cursor.color("midnight blue") # Create Screen coverage Cursor self.coverage_cursor = Turtle() self.coverage_cursor.ht() self.coverage_cursor.penup() self.coverage_cursor.pensize(2) self.coverage_cursor.color("saddle brown") # Create Screen Send Packet Cursor self.snd_pckt = Turtle() self.snd_pckt.ht() self.snd_pckt.penup() self.snd_pckt.pensize(2) self.snd_pckt.color("saddle brown") # Call Screen Init Method self.screen_init() def screen_init(self): # Set Screen Dimensions and Coloring self.screen.setup(TOTAL_WIDTH, TOTAL_HEIGHT) self.screen.bgcolor(SCREEN_BGCOLOR) self.layout_cursor.color("slate grey") self.layout_cursor.setposition(-((TOTAL_WIDTH / 2) - SCREEN_MARGIN), -((TOTAL_HEIGHT / 2) - SCREEN_MARGIN)) self.layout_cursor.speed(8) self.layout_cursor.pendown() self.layout_cursor.fd(SCREEN_WIDTH) self.layout_cursor.rt(-90) self.layout_cursor.fd(SCREEN_HEIGHT) self.layout_cursor.rt(-90) self.layout_cursor.fd(SCREEN_WIDTH) self.layout_cursor.rt(-90) self.layout_cursor.fd(SCREEN_HEIGHT) self.layout_cursor.setheading(90) self.layout_cursor.fd(MESSAGE_MARGIN) self.layout_cursor.setheading(0) self.layout_cursor.fd(SCREEN_WIDTH) self.layout_cursor.penup() self.layout_cursor.speed("fastest") self.layout_cursor.color("midnight blue") x_cor = 0 y_cor = int((TOTAL_HEIGHT / 2) - (3 / 4 * HEAD_MARGIN)) self.layout_cursor.setposition(x_cor, y_cor) self.layout_cursor.write(f"{SCREEN_HEADER}", align="Center", font=("Calibri", HEADER_FONT_SIZE, "bold")) x_cor = 20 - (int(SCREEN_WIDTH / 2)) y_cor = (int(TOTAL_HEIGHT / 2)) - (HEAD_MARGIN + 40) self.layout_cursor.setposition(x_cor, y_cor) self.layout_cursor.write(f"Topology: {TOPOLOGY_TYPE.title()}", align="Left", font=("Calibri", TEXT_FONT_SIZE, "bold")) x_cor = (int(SCREEN_WIDTH / 2)) - 20 y_cor = (int(TOTAL_HEIGHT / 2)) - (HEAD_MARGIN + 40) self.layout_cursor.setposition(x_cor, y_cor) self.layout_cursor.write(f"Nodes: {NUM_OF_NODES}", align="Right", font=("Calibri", TEXT_FONT_SIZE, "bold")) self.visual_output_msg("This where the text message appears") # Stop Auto-update Screen changes self.screen.tracer(0) def visual_output_msg(self, message): x_cor = 20 - (int(SCREEN_WIDTH / 2)) y_cor = (SCREEN_MARGIN + 15) - (int(TOTAL_HEIGHT / 2)) self.msg_cursor.setposition(x_cor, y_cor) self.msg_cursor.clear() self.msg_cursor.write(f"{message}", align="Left", font=("Calibri", TEXT_FONT_SIZE, "bold")) def visual_send_packet(self, tx_node, rx_nodes): # draw arrow for all neighbors for rx_node in rx_nodes: self.snd_pckt.setposition(tx_node.pos()) self.snd_pckt.pendown() self.snd_pckt.setheading(self.snd_pckt.towards(rx_node.pos())) self.snd_pckt.setposition(rx_node.pos()) self.snd_pckt.bk(11) # Drawing arrow head self.snd_pckt.left(45) self.snd_pckt.backward(10) self.snd_pckt.forward(10) self.snd_pckt.right(90) self.snd_pckt.backward(10) self.snd_pckt.penup() def clear_send_packets(self): self.snd_pckt.pd() self.snd_pckt.clear() self.snd_pckt.pu() def show_coverage(self, node): self.coverage_cursor.goto(node.xcor(), node.ycor() - node.coverage) self.coverage_cursor.pendown() self.coverage_cursor.circle(node.coverage) self.coverage_cursor.penup() self.coverage_cursor.goto(node.pos()) def hide_coverage(self): self.coverage_cursor.pendown() self.coverage_cursor.clear() self.coverage_cursor.penup() def screen_refresh(self): self.screen.update() def mainloop(self): while True: try: self.root.update() self.root.update_idletasks() except Exception as exp: print(exp) print("bye") break
def play(): """ design the screen, create required objects, define key events that allow the player to control the movements of the snake figure, and implement the functional logic in a game loop """ # setting the size/dimensions of the screen screen.setup(width=600, height=600) # setting the background colour of the screen screen.bgcolor("black") # setting a title for the screen screen.title("My Snake Game") screen.tracer(0) # add further turtle shapes (= used for some food variants) screen.addshape("banana.GIF") screen.addshape("plum.GIF") screen.addshape("diamond.GIF") # creating the required objects snake = Snake() food = Food() scoreboard = Scoreboard() # defining key events screen.listen() screen.onkey(snake.up, "Up") screen.onkey(snake.down, "Down") screen.onkey(snake.left, "Left") screen.onkey(snake.right, "Right") # --- GAME LOOP --- game_is_on = True while game_is_on: screen.update() # refresh the screen time.sleep(0.1) # wait for 0.1 sec # move the snake one step snake.move() # if the food appearing is a turtle, move it towards the margin if food.variant == 4: food.speed("slow") food.forward(3) if not 280 > food.xcor() > -280 or not 280 > food.ycor() > -280: food.refresh() # detect any collision with a food object, update the scoreboard if snake.head.distance(food) < 15: # distance in pixels food.refresh() snake.extend() scoreboard.increase_score() # detect a collision with a wall --> trigger "reset" if snake.head.xcor() > 290 or snake.head.xcor( ) < -290 or snake.head.ycor() > 290 or snake.head.ycor() < -290: game_is_on = False # detect a collision with the snake's tail - # if the head collides with any segment of the tail --> trigger "reset" for segment in snake.segments[1:]: if snake.head.distance(segment) < 10: game_is_on = False # prepare the restart of the game label_1 = Turtle() label_1.hideturtle() label_1.goto(0, 0) label_1.color("salmon") label_1.write("GAME OVER!", align=ALIGNMENT, font=("Courier", 32, "normal")) label_2 = Turtle() label_2.hideturtle() label_2.goto(0, -30) label_2.color("orange") label_2.pendown() if scoreboard.score > scoreboard.high_score: label_2.write("Congrats! You've reached a new high score!", align=ALIGNMENT, font=FONT) time.sleep(2) label_2.clear() label_2.write(f"Last score: {scoreboard.score}", align=ALIGNMENT, font=FONT) time.sleep(3) scoreboard.reset() snake.reset() sketch_restart_button() screen.onscreenclick(button_click) screen.listen() screen.mainloop()
turtle.goto(x, y-radius) turtle.pendown() turtle.fill(True) turtle.circle(radius) turtle.fill(False) def draw_bullseye(turtle, x, y, wn): color = True for radius in range(circle_radius, circle_inner_radius, -40): if color: turtle.fillcolor("red") else: turtle.fillcolor("white") origin_circle(turtle,radius,x,y,wn) color = not color while True: t1.speed(0) wn = t1.getscreen() t1.ht() width = wn.window_width() height = wn.window_height() wn.screensize(width, height, None) x = randint( -(width/2) + circle_radius, (width/2) - circle_radius) y = randint( -(height/2) + circle_radius, (height/2) - circle_radius) print x, y print width, height draw_bullseye(t1, x, y, wn) time.sleep(3) t1.clear()
if ball.ycor() > 280 or ball.ycor() < -280: ball.bounce_walls() if ball.xcor() > 330: if 50 > ball.ycor() - paddle1.ycor() > -50 or 50 > ball.ycor( ) + paddle1.ycor() > -50: ball.bounce_paddle() if ball.xcor() < -330: if 50 > ball.ycor() - paddle2.ycor() > -50 or 50 > ball.ycor( ) + paddle2.ycor() > -50: ball.bounce_paddle() if ball.xcor() > 370: winner.clear() score_left += 1 winner.clear() winner.write(f"Score: Left:{score_left} Right: {score_right}", align="center", font=("Arial", 30, "normal")) point_is_on = False if ball.xcor() < -370: score_right += 1 winner.clear() winner.write(f"Score: Left:{score_left} Right: {score_right}", align="center", font=("Arial", 30, "normal")) point_is_on = False
class Game: def __init__(self): # game object has a screen, a turtle, a basic snake and a food self.screen = Screen() self.artist = Turtle(visible=False) self.artist.up() self.artist.speed("slowest") self.snake = Snake() self.food = Food(100, 0) self.counter = 0 # this will be used later self.commandpending = False # as will this self.screen.tracer(0) # follow it so far? self.screen.listen() self.screen.onkey(self.snakedown, "Down") self.screen.onkey(self.snakeup, "Up") self.screen.onkey(self.snakeleft, "Left") self.screen.onkey(self.snakeright, "Right") def nextFrame(self): self.artist.clear() if (self.snake.nextposition[0], self.snake.nextposition[1]) == (self.food.x, self.food.y): self.snake.eatFood() self.food.changelocation() else: self.snake.moveOneStep() if self.counter == 10: self.food.changestate() # makes the food flash slowly self.counter = 0 else: self.counter += 1 self.food.drawself(self.artist) # show the food and snake self.snake.drawself(self.artist) self.screen.update() self.screen.ontimer(lambda: self.nextFrame(), 100) def snakeup(self): if not self.commandpending: self.commandpending = True self.snake.moveup() self.commandpending = False def snakedown(self): if not self.commandpending: self.commandpending = True self.snake.movedown() self.commandpending = False def snakeleft(self): if not self.commandpending: self.commandpending = True self.snake.moveleft() self.commandpending = False def snakeright(self): if not self.commandpending: self.commandpending = True self.snake.moveright() self.commandpending = False
class ScreenCursor: def __init__(self): self.screen = Screen() self.screen.tracer(0) self.screen.title("U.S. States Game") self.screen.setup(725, 632) self.screen.bgpic("blank_states_img.gif") ##------------------------------------------- self.main_cursor = Turtle() self.main_cursor.ht() self.main_cursor.pu() self.display_game_title() ##------------------------------------------- self.message_cursor = Turtle() self.message_cursor.ht() self.message_cursor.pu() self.message_cursor.color("black") ##------------------------------------------- self.state_cursor = Turtle() self.state_cursor.ht() self.state_cursor.pu() self.state_cursor.color("black") def display_game_title(self): self.main_cursor.color("black") self.main_cursor.setposition(160, 267) self.main_cursor.write("U.S. States Game", move=False, align="center", font=("Verdana", 28, "bold")) self.main_cursor.color("grey") self.main_cursor.setposition(210, 252) self.main_cursor.write(f"How well do you memorize US States?", move=False, align="center", font=("Verdana", 10, "italic")) def display_game_title(self): self.main_cursor.color("black") self.main_cursor.setposition(160, 267) self.main_cursor.write("U.S. States Game", move=False, align="center", font=("Verdana", 28, "bold")) self.main_cursor.color("grey") self.main_cursor.setposition(210, 252) self.main_cursor.write(f"How well do you memorize US States?", move=False, align="center", font=("Verdana", 10, "italic")) def display_welcome_message(self, x_position): self.message_cursor.clear() self.message_cursor.setposition(x_position, 0) self.message_cursor.write("Welcome to U.S. States Game", move=False, align="center", font=("Verdana", 18, "bold")) def display_input(self, message): self.message_cursor.clear() self.message_cursor.setposition(-350, -243) self.message_cursor.write(message, move=False, align="left", font=("Courier", 14, "bold")) def display_state_name(self, state_name, x_position, y_position): self.state_cursor.setposition(x_position, y_position) self.state_cursor.write(state_name, move=False, align="center", font=("Verdana", 8, "bold"))
from turtle import Turtle from random import random def random_color(): return(random(),random(),random()) MorganFreeman = Turtle() MorganFreeman.pensize(15) MorganFreeman.speed(0) while True: for counter in range(225): MorganFreeman.pencolor(random_color()) MorganFreeman.forward(counter) MorganFreeman.right(198) MorganFreeman.forward(counter) MorganFreeman.right(72) #The previous "turn right" command can be replaced with 70 #for a different "rotating-star" effect. MorganFreeman.penup() MorganFreeman.home() MorganFreeman.pendown() MorganFreeman.clear()
class Score: def __init__(self): self.value = 0 self.lose_count = 8 self.player_life = [] self.init_player_life() self.cursor = Turtle() self.cursor.ht() self.cursor.pu() self.print() def init_player_life(self): x_cor = -365 for i in range(self.lose_count): x_cor += 25 temp = Turtle("square") # temp.shapesize(2, 1) temp.pu() temp.color("red") temp.setposition(x_cor, -290) self.player_life.append(temp) temp = Turtle() temp.ht() temp.pu() temp.color("gray") temp.setposition(-348, -276) temp.write(f"PLAYER LIFE BAR:", move=False, align="left", font=("Verdana", 10, "normal")) def update(self): self.value += 1 def player_lose(self): self.lose_count -= 1 self.player_life[self.lose_count].ht() if self.lose_count == 0: return True else: return False def player_win(self): if self.value == 50: return True else: return False def print(self): self.cursor.clear() if self.value < 10: score_output = f"0{self.value}/50" else: score_output = f"{self.value}/50" self.cursor.color("grey") self.cursor.setposition(330, -270) self.cursor.write(f"SCORE", move=False, align="right", font=("Verdana", 10, "normal")) self.cursor.color("black") self.cursor.setposition(340, -312) self.cursor.write(score_output, move=False, align="right", font=("Arial", 30, "bold"))
wn.onkeypress(gr, 'd') # Main Game Loop while True: wn.update() # Border Collisions if p.ycor() > 290 or p.ycor() < -290 or p.xcor() > 290 or p.xcor() < -290: time.sleep(1) p.goto(0, 0) p.direction = 'stop' for s in bs: s.goto(10000, 10000) bs.clear() score = 0 pen.clear() pen.write('Score: {} Highscore: {}'.format(score, hscore), align='center', font=('Courier', 24, 'normal')) # Food Collisions if p.distance(f) < 20: x = random.randint(-290, 290) y = random.randint(-290, 290) f.goto(x, y) score += 10 if score > hscore: hscore = score pen.clear() pen.write('Score: {} Highscore: {}'.format(score, hscore), align='center',
if enemy.ycor() < -285: enemy.setposition(-200, 250) if isCollision(bullet, enemy): # reset bullet os.system("aplay cat_growl.wav&") os.system("aplay Explosion+3.wav&") bullet.hideturtle() bullet_state = "ready" bullet.setposition(0, -400) # reset enemy that was hit enemy.setposition(-200, 250) # add points to score score += 10 score_string = "Score: %s" % score score_pen.clear() score_pen.write(score_string, False, align="left", font=("Arial", 14, "normal")) # speed up enemies enemy_speed += 2 if isCollision(player, enemy): os.system("aplay dog_whine.wav&") player.hideturtle() enemy.hideturtle() print("game over") break # if bullet_state == "fire":
class GraphicalCircle(object): """ Wraps Circle object with a primitive graphical interface. Each GraphicalCircle object maintains its own circle object and Turtle graphics Turtle object. """ def __init__(self, center, radius): """ (GraphicalCircle, tuple, int) -> GraphicalCircle Initializes a graphical circle object The circle is centered at the position <center>. The circle radius is set to the <radius> """ # Make a turtle graphics object to do the drawing. # Assign it to an instance variable the_turtle, # so other methods can access it self.the_turtle = Turtle() self.the_turtle.speed(0) # fastest turtle self.the_turtle.hideturtle() # hide turtle the_screen = Screen() # Create local screen object: Receive user input the_screen.delay(0) # trace drawing delay - slow the_screen.listen() # focus on keystrokes # Mouse click re-positions the circle the_screen.onclick(self.move) # Set mouse press handler - # Up cursor key calls the increases method to expand the circle the_screen.onkey(self.increase, 'Up') # Set "up" cursor key handler # Down cursor key calls the deecrease method to contract the circle the_screen.onkey(self.decrease, 'Down') # Set "Down" cursor key handler # Make a circle object # Assign it to an instance variable the_circle, # so other methods can access it self.the_circle = Circle(center, radius) mainloop() # Start event loop def draw(self): """ (GraphicalCircle) -> turtle Draw circle in the graphical window """ x_pos, y_pos = self.the_circle.get_center( ) # unpack center's coordinates radius = self.the_circle.get_radius() self.the_turtle.penup() # lift pen self.the_turtle.setposition(x_pos, y_pos) # Move pen to (x,y) position self.the_turtle.pendown() # pen ready self.the_turtle.dot() # draw dot: circle's center self.the_turtle.penup() # lift pen self.the_turtle.setposition( x_pos, y_pos - radius) # position pen to draw rim of circel self.the_turtle.pendown() # pen ready self.the_turtle.circle(radius) # draw the circle self.the_turtle.penup() # lift pen def move(self, x_pos, y_pos): """ (int, int) -> turtle Moves the circle's center to <x_pos> and <y_pos> Delegates the work to the contained Circle object """ self.the_circle.move((x_pos, y_pos)) # Move to new pos self.redraw() def increase(self): """ (GraphicalCircle) -> turtle Increase the circle's radius by 1 unit, then redraw the circle Delegates the work to the contained Circle object """ self.the_circle.grow() self.redraw() def decrease(self): """ (GraphicalCircle) -> turtle Decrease the circle's radius by 1 unit, then redraw the circle Delegates the work to the contained Circle object """ self.the_circle.shrink() self.redraw() def redraw(self): """ (GraphicalCircle) -> turtle Clears the graphical window, then draws the circle """ self.the_turtle.clear() self.draw()
from turtle import Turtle, Screen import random tim = Turtle() for _ in range(4): tim.forward(100) tim.left(90) tim.clear() for _ in range(15): tim.pendown() tim.forward(10) tim.penup() tim.forward(10) screen = Screen() screen.exitonclick()
class Spiro: def __init__(self, xc, yc, col, R, r, l): self.turtle = Turtle() # set the cursor shape self.turtle.shape('turtle') # set the step in degrees self.step = 5 # set the drawing complete flag self.drawing_complete = False # set parameters self.set_parameters(xc, yc, col, R, r, l) # initalize the drawing self.restart() def set_parameters(self, xc, yc, col, R, r, l): # Spirograph parameters self.xc = xc self.yc = yc self.col = col self.R = R self.r = r self.l = l # reduce r/R to its smallest form by dividing with the GCD gcd_val = gcd(self.r, self.R) self.n_rot = self.r // gcd_val # get ratio of radii self.k = r / float(R) self.turtle.color(*col) # store the current angle self.a = 0 def restart(self): # set the flag self.drawing_complete = False # show the turtle self.turtle.showturtle() # go to the first point self.turtle.up() R, k, l = self.R, self.k, self.l a = 0.0 x = R * ((1 - k) * math.cos(a) + 1 * k * math.cos((1 - k) * a / k)) y = R * ((1 - k) * math.sin(a) - 1 * k * math.sin((1 - k) * a / k)) self.turtle.setpos(self.xc + x, self.yc + y) self.turtle.down() def draw(self): R, k, l = self.R, self.k, self.l for i in range(0, int(360 * self.n_rot + 1), self.step): a = math.radians(i) x = R * ((1 - k) * math.cos(a) + 1 * k * math.cos((1 - k) * a / k)) y = R * ((1 - k) * math.sin(a) - 1 * k * math.sin((1 - k) * a / k)) self.turtle.setpos(self.xc + x, self.yc + y) self.turtle.hideturtle() def update(self): # skip the rest of the steps if done if self.drawing_complete: return # increment the angle self.a += self.step # draw a step R, k, l = self.R, self.k, self.l a = math.radians(self.a) x = R * ((1 - k) * math.cos(a) + 1 * k * math.cos((1 - k) * a / k)) y = R * ((1 - k) * math.sin(a) - 1 * k * math.sin((1 - k) * a / k)) self.turtle.setpos(self.xc + x, self.yc + y) # if drawing is complete, set the flag if self.a >= 360 * self.n_rot: self.drawing_complete = True # drawing is now done so hide the turtle cursor self.turtle.hideturtle() def clear(self): self.turtle.clear()
class Snake: #the parameters in __init__ are the parameters that allow the player instances to be called, e.g. 'color' allows the instances to be called with different colors so the players know who is who def __init__(self, goto, color, player, setx, sety): self.sc = Screen() #setting up the 'head' of the player, this is the square the player will move. self.head = Turtle() self.head.color(color) self.head.fillcolor('white') self.head.shapesize(outline=5) self.head.shape('square') self.head.penup() self.head.speed(0) self.head.goto(goto) self.head.direction = 'stop' #setting up the point system and player graphics self.score = 0 self.player = player self.pen = Turtle() self.pen.color('black') self.color = color self.pen.speed(0) self.pen.shapesize(outline=10) self.pen.fillcolor('white') self.pen.penup() self.pen.hideturtle() self.pen.goto(setx, sety) self.pen.write('Player {} ({}) Score: {}'.format(self.player, self.color, self.score), align='center', font=('courier', 24, 'normal')) #This will be increased every time a player moves over food to increase the speed, or decrease if they hit a border. self.di = 7 # assigning keys def move(self, left_key, right_key, up_key, down_key): self.sc.listen() self.sc.onkey(self.up, up_key) self.sc.onkey(self.down, down_key) self.sc.onkey(self.left, left_key) self.sc.onkey(self.right, right_key) #creating the turn functions def turn(self): if self.head.direction == 'left': l = self.head.xcor() self.head.setx(l - self.di) if self.head.direction == 'right': r = self.head.xcor() self.head.setx(r + self.di) if self.head.direction == 'up': u = self.head.ycor() self.head.sety(u + self.di) if self.head.direction == 'down': d = self.head.ycor() self.head.sety(d - self.di) def left(self): self.head.direction = 'left' def right(self): self.head.direction = 'right' def up(self): self.head.direction = 'up' def down(self): self.head.direction = 'down' #This function resets the player position and decreases the speed if they get too close the edge of the screen, unless their speed is already less than 7. # It also decreases the player score by 10 every time they collide with the edge of the screen, unless they already have zero points, in which case their score remains the same. #This means that a player's speed will always increase or decrease at the same level as their points. def border_c(self): if self.head.xcor()>390 or self.head.xcor()<-390 or self.head.ycor()>390 or self.head.ycor()<-390: self.head.goto(0,0) if self.di > 7: self.di -= 1 elif self.di < 7: pass if self.score >= 10: self.score -= 10 self.pen.clear() self.pen.write('Player {} ({}) Score: {}'.format(self.player, self.color, self.score), align='center', font=('courier', 24, 'normal')) elif self.score < 10: pass #This function increases the score and speed if the player moves over food, and moves the food to a new position. def scores(self): self.random = random if self.head.distance(food) < 20: self.di += 1 self.score += 10 self.pen.clear() self.pen.write('Player {} ({}) Score: {}'.format(self.player, self.color, self.score), align='center', font=('courier', 24, 'normal')) y = self.random.randint(-390, 390) x = self.random.randint(-390, 390) food.goto(x,y) #This ends the game when a player has a score of 100, and announces the winner. if self.score > 95: self.pen.goto(0,0) self.pen.color('black') self.pen.fillcolor('black') self.pen.shapesize(outline=20) self.pen.write('Player {} is the winner!'.format(self.player), align='center', font=('courier', 40, 'bold')) wn.mainloop()
class GameGUI: def __init__(self): self.screen = Screen() self.main_cursor = Turtle() self.level_cursor = Turtle() self.speeed = 0.1 self.level = 1 self.init_screen_configs() def init_screen_configs(self): self.screen.tracer(0) self.screen.setup(SCREEN_X, SCREEN_Y) # Enter Taskbar Title self.screen.title("Crossing Road Game") self.screen.bgcolor("gainsboro") self.main_cursor.speed("fastest") self.main_cursor.ht() self.main_cursor.pu() # Enter Game Title self.main_cursor.setposition(GAME_TITLE_POSITION) self.main_cursor.write(".:Crossing Road:.", move=False, align="left", font=("Calibri", 30, "bold")) # Draw Game Roads borders self.main_cursor.pensize(3) self.main_cursor.color("dim grey") for x in [-200, -150, -100, -50, 0, 50, 100, 150, 200]: self.main_cursor.pu() self.main_cursor.setposition(-410, x) self.main_cursor.pd() self.main_cursor.fd(820) # Draw Game Roads Dotted lines self.main_cursor.pensize(2) self.main_cursor.color("silver") for x in LANES: self.main_cursor.pu() self.main_cursor.setposition(-410, x) for i in range(int(820/15)): if i % 2 == 0: self.main_cursor.pd() else: self.main_cursor.pu() self.main_cursor.fd(15) # Draw Start Sign self.main_cursor.pu() self.main_cursor.shape("square") self.main_cursor.shapesize(0.5) self.main_cursor.setheading(0) self.main_cursor.showturtle() self.main_cursor.setposition(START_SIGN[0]) for i in range(11): if i % 2 == 0: self.main_cursor.color("black") self.main_cursor.stamp() else: self.main_cursor.color("white") self.main_cursor.stamp() self.main_cursor.fd(10) self.main_cursor.setposition(START_SIGN[1]) for i in range(11): if i % 2 == 0: self.main_cursor.color("white") self.main_cursor.stamp() else: self.main_cursor.color("black") self.main_cursor.stamp() self.main_cursor.fd(10) self.main_cursor.ht() # Draw Finish Sign self.main_cursor.pu() self.main_cursor.shape("square") self.main_cursor.shapesize(0.5) self.main_cursor.setheading(0) self.main_cursor.showturtle() self.main_cursor.setposition(FINISH_SIGN[1]) for i in range(11): if i % 2 == 0: self.main_cursor.color("black") self.main_cursor.stamp() else: self.main_cursor.color("white") self.main_cursor.stamp() self.main_cursor.fd(10) self.main_cursor.setposition(FINISH_SIGN[0]) for i in range(11): if i % 2 == 0: self.main_cursor.color("white") self.main_cursor.stamp() else: self.main_cursor.color("black") self.main_cursor.stamp() self.main_cursor.fd(10) self.main_cursor.ht() # Init Score Cursor self.level_cursor.shape("square") self.level_cursor.ht() self.level_cursor.pu() self.level_cursor.color("black") self.level_cursor.setposition(LEVELBOARD_POSITION) self.level_cursor.write(f"Level: {self.level}", move=False, align="right", font=("Courier", 18, "bold")) def update_level(self): self.level += 1 self.speeed *= 0.75 self.level_cursor.clear() self.level_cursor.write(f"Level: {self.level}", move=False, align="right", font=("Courier", 18, "bold")) def game_over(self): self.level_cursor.setposition(0, 0) self.level_cursor.write("GAME OVER", move=False, align="center", font=("Calibri", 28, "bold"))
class NimView: ''' View(視圖) ''' def __init__(self, game): self.game = game self.screen = game.screen self.model = game.model self.screen.colormode(255) self.screen.tracer(False) #背景顏色 self.screen.bgcolor((240, 240, 255)) self.writer = turtle.Turtle(visible=False) self.writer.pu() self.writer.speed(0) self.sticks = {} self.set_msg() #self.level = Level(game) self.level = game.level self.hint = game.hint ''' #--------------------- if self.game.hint.value == False: msg ='hint=' self.writer.goto(0,-100) self.writer.write(msg) #--------------------- ''' self.nRows = game.nRows ## 把排數(nRows)在此記住,很重要。 for row in range(self.nRows): #3): for col in range(MAXSTICKS): self.sticks[(row, col)] = Stick(row, col, game) self.display("... 等一下 ...") self.screen.tracer(True) # # ry: 以下開始創造 Menu # #self.menu= Menu(self.game.tk) #self.set_menu() self.menu = game.menu #CvMenu(game) def set_msg(self): msg = ''' Python 拈遊戲 (NimGame) 以下是遊戲規則: 1. 玩家與電腦輪流撿棒子,撿到最後一個的就贏了。 2. 點擊任一棒子則玩家將會撿走該棒子右側的所有棒子。 3. 點擊左下角的方塊會給予提示。 4. 點擊右下角的烏龜可選擇難度(黃色代表難,橘色代表簡單) 5. 遊戲開始前請選擇排數 ''' self.t = Turtle() self.t.pu() self.t.ht() self.t.goto(0, -50) self.t.write(msg, align="center", font=('Arial', 15, 'bold')) def display(self, msg1, msg2=None): self.screen.tracer(False) self.writer.clear() if msg2 is not None: self.writer.goto(0, -SCREENHEIGHT // 2 + 48) self.writer.pencolor("red") self.writer.write(msg2, align="center", font=("Courier", 18, "bold")) self.writer.goto(0, -SCREENHEIGHT // 2 + 20) self.writer.pencolor("black") self.writer.write(msg1, align="center", font=("Courier", 14, "bold")) self.screen.tracer(True) def setup(self): self.screen.tracer(False) #-------------------------------------------- for row in range(self.nRows): #3): for col in range(MAXSTICKS): #self.sticks[(row, col)] = Stick(row, col, self.game) self.sticks[(row, col)].showturtle() #-------------------------------------------- for row in range(self.nRows): for col in range(self.model.sticks[row]): self.sticks[(row, col)].color(SCOLOR) for row in range(self.nRows): for col in range(self.model.sticks[row], MAXSTICKS): self.sticks[(row, col)].color("white") #設定當遊戲開始則無法設定排數 self.menu.entryconfig('棒子排數', state='disabled') #設定當遊戲開始則無法選擇模式 self.menu.entryconfig('遊戲模式', state='disabled') #清除一開始寫的說明 #self.game.hint.t.clear() self.t.clear() if self.game.mode == 0: self.display("輪到你了,請點擊棒子移除其右邊之所有棒子。") else: self.display("玩家1") self.screen.tracer(True) def notify_move(self, row, col, maxspalte, player): if player == 0: farbe = HCOLOR for s in range(col, maxspalte): self.sticks[(row, s)].color(farbe) else: self.display(" ... 想一想 ... ") time.sleep(0.5) self.display(" ... 想一想 ... 啊!想出來了 ...") farbe = COLOR for s in range(maxspalte - 1, col - 1, -1): time.sleep(0.2) self.sticks[(row, s)].color(farbe) self.display("輪到你了,請點擊棒子移除其右邊之所有棒子。") #--------------------------------------------------------- #--------------------------------------------------------- def player_move(self, row, col, maxspalte, player): if player == 0: farbe = HCOLOR for s in range(col, maxspalte): self.sticks[(row, s)].color(farbe) self.display("") time.sleep(0.05) self.display("輪到玩家 2 了") else: farbe = COLOR for s in range(col, maxspalte): self.sticks[(row, s)].color(farbe) self.display("") time.sleep(0.05) self.display("輪到玩家 1 了") #--------------------------------------------------------- #--------------------------------------------------------- def notify_over(self): if self.game.model.winner == 0: msg2 = "你贏了!" else: msg2 = "你輸了。" #當遊戲結束則可以改排數 self.menu.entryconfig('棒子排數', state='normal') #當遊戲結束則可以選模式 self.menu.entryconfig('遊戲模式', state='normal') self.display("按【空白鍵】再玩一次,按【Esc】鍵離開。", msg2) def player_over(self): if self.game.model.winner == 0: msg2 = "玩家1贏了!" else: msg2 = "玩家2贏了" #當遊戲結束則可以改排數 self.menu.entryconfig('棒子排數', state='normal') #當遊戲結束則可以選模式 self.menu.entryconfig('遊戲模式', state='normal') self.display("按【空白鍵】再玩一次,按【Esc】鍵離開。", msg2) def clear(self): if self.game.state == NimGame.OVER: self.screen.clear()
class Snake: #the parameters in __init__ are the parameters that allow the player instances to be called, e.g. 'color' allows the instances to be called with different colors so the players know who is who def __init__(self, goto, color, player, setx, sety, foodgoto): self.sc = Screen() #setting up the 'head' of the player, this is the square the player will move. self.head = Turtle() self.head.color(color) self.head.fillcolor('white') self.head.shapesize(outline=10) self.head.shape('square') self.head.penup() self.head.pensize(1) self.head.speed(0) self.head.goto(goto) self.head.direction = 'stop' #creating the food the player will move over to score points self.food = turtle.Turtle() self.food.penup() self.food.goto(foodgoto) self.food.speed(0) self.food.shape('circle') self.food.color('white') self.food.fillcolor(color) #setting up the point system and player graphics self.score = 0 self.player = player self.pen = Turtle() self.pen.speed(0) self.pen.shape('square') self.pen.color('white') self.pen.pensize() self.pen.penup() self.pen.hideturtle() self.pen.goto(setx, sety) self.pen.write('Player {} Score: {}'.format(self.player, self.score), align='center', font=('courier', 24, 'normal')) #This will be increased every time a player moves over food to increase the speed, or reset if they hit an edge. self.di = 12 # creating the move function def move(self, left_key, right_key, up_key, down_key): self.sc.listen() self.sc.onkey(self.up, up_key) self.sc.onkey(self.down, down_key) self.sc.onkey(self.left, left_key) self.sc.onkey(self.right, right_key) #creating the turn functions def turn(self): if self.head.direction == 'left': l = self.head.xcor() self.head.setx(l - self.di) if self.head.direction == 'right': r = self.head.xcor() self.head.setx(r + self.di) if self.head.direction == 'up': u = self.head.ycor() self.head.sety(u + self.di) if self.head.direction == 'down': d = self.head.ycor() self.head.sety(d - self.di) def left(self): self.head.direction = 'left' def right(self): self.head.direction = 'right' def up(self): self.head.direction = 'up' def down(self): self.head.direction = 'down' #This function resets the player position and speed if they get too close the edge of the screen. def border_c(self): if self.head.xcor() > 390 or self.head.xcor() < -390 or self.head.ycor( ) > 390 or self.head.ycor() < -390: self.head.pensize(1) self.head.goto(0, 0) self.di = 12 self.score = 0 self.pen.clear() self.pen.write('Player {} Score: {}'.format( self.player, self.score), align='center', font=('courier', 24, 'normal')) #This function increases the score and speed if the player moves over food, and resets the position of the food. def scores(self): self.seg = [] self.random = random if self.head.distance(self.food) < 20: self.di += 3 p = self.head.pensize() new = p + 3 self.head.pensize(new) self.score += 10 self.pen.clear() y = self.random.randint(-390, 390) x = self.random.randint(-390, 390) self.food.goto(x, y) self.pen.write('Player {} Score: {}'.format( self.player, self.score), align='center', font=('courier', 24, 'normal')) #This ends the game when a player has a score of 100, and announces the winner. if self.score > 95: self.pen.goto(0, 0) self.pen.color('white') self.pen.fillcolor('black') self.pen.shapesize(outline=20) self.pen.write('Player {} is the winner!'.format(self.player), align='center', font=('courier', 40, 'bold')) wn.mainloop()
class Game(object): def __init__(self): screen.tracer(False) screen.setup(width=MAX_X * SQUARE_WIDTH + DM, height=(MAX_Y + FREEROWS) * SQUARE_WIDTH + DM, startx=-20, starty=20) screen.screensize(MAX_X * SQUARE_WIDTH + DM - 50, (MAX_Y + FREEROWS) * SQUARE_WIDTH + DM - 50) self.designer = Turtle(visible=False) starttime = time.clock() self.messagero = Turtle(visible=False) self.messagero.penup() self.messagero.pencolor("blue") self.messagero.goto(0, -(MAX_Y + FREEROWS) * SQUARE_WIDTH / 2 + 6) self.message("Please wait a moment!") self.designer.pencolor("gray90") w2 = SQUARE_WIDTH // 2 for c in range(MAX_X + 1): x1, y1 = coords(c, 0) x2, y2 = coords(c, MAX_Y) x1, y1, y2 = x1 - w2, y1 - w2, y2 - w2 self.line(x1, y1, x1, y2) for r in range(MAX_Y + 1): x1, y1 = coords(0, r) x2, y2 = coords(MAX_X, r) x1, y1, x2 = x1 - w2, y1 - w2, x2 - w2 self.line(x1, y1, x2, y1) screen.update() self.patches = {} for r in range(MAX_Y): for c in range(MAX_X): self.patches[(c, r)] = Patch(c, r) self.state = { (41, 33): 1, (42, 33): 1, (43, 34): 1, (42, 32): 1, (42, 34): 1 } for cell in self.state: self.patches[cell].showturtle() self.newstate = None stoptime = time.clock() print(stoptime - starttime) screen.update() screen.onkey(self.run, "space") screen.onkey(screen.bye, "Escape") screen.onkey(self.clear, "c") screen.listen() screen.onclick(self.toggle) self.message("spacebar:start/pause | left click:toggle cell | c:clear" " | escape:quit") def message(self, txt): self.messagero.clear() self.messagero.write(txt, align="center", font=("Courier", 14, "bold")) def line(self, x1, y1, x2, y2): self.designer.penup() self.designer.goto(x1, y1) self.designer.pendown() self.designer.goto(x2, y2) def update_display(self): screen.tracer(False) for cell in self.state: if cell not in self.newstate: try: self.patches[cell].hideturtle() except KeyError: pass for cell in self.newstate: try: self.patches[cell].showturtle() self.patches[cell].color(calccolor(self.newstate[cell])) except KeyError: pass screen.tracer(True) def clear(self): self.newstate = {} self.update_display() self.state = {} def toggle(self, x, y): cell = cellindices(int(x), int(y)) self.newstate = self.state.copy() if cell in self.newstate: del self.newstate[cell] else: self.newstate[cell] = 1 self.update_display() self.state = self.newstate def run(self): starttime = time.clock() anzahl_generationen = 0 screen.onkey(self.stop, "space") generation = generate(self.state) self.RUNNING = True while self.RUNNING: self.newstate = next(generation) self.update_display() self.state = self.newstate anzahl_generationen += 1 stoptime = time.clock() t = stoptime - starttime print(anzahl_generationen, t, anzahl_generationen / t) def stop(self): self.RUNNING = False screen.onkey(self.run, "space")
cross.showturtle() for j in range(0, 2): for x in range(1, 5): level = x ready = False levels(Turtle(), f"Starting level {level}...") ready = True enemyWave() upgrading = True x = 0 while upgrading: upgrades() x += 1 if x == 10: upw.clear() x = 0 upw.clear() for x in range(5, 1, 10): level = x ready = False levels(Turtle(), f"Starting level {level}...") ready = True enemyWave() enemy_speed *= 2 upw.clear() quit() screen.mainloop()
def enemyWave(): global round_time round_time = 0 deathcount = 0 enemy.clear() scoreTurt = Turtle() scoreTurt.color("white") scoreTurt.penup() scoreTurt.hideturtle() scoreTurt.setpos(-180, 230) scoreTurt.write("Deathcount: " + str(deathcount), font=("Arial", 12, "normal")) for x in range(0, level * 5): #populate the enemy list with 5 cats per level enemy.append(Turtle(shape="cat_right.gif")) enemy[x].hideturtle enemy[x].setheading(random.randint(0, 359)) enemy[x].penup() enemy[x].speed(0) enemy[x].setpos(random.randint(-225, 225), random.randint(-215, 215)) while deathcount != len( enemy): #While deathcount is NOT the length of the enemy list if countdown(): drawsecs() for x in range(0, len(enemy)): #For each enemy if enemy[x].isvisible( ): #If it can be seen, do the following calculations if random.randint( 0, 10) == 7: #if a seven is rolled, change directions enemy[x].right(random.randint(0, 360)) enemy[x].forward(enemy_speed) #Move it forward by enemyspeed if enemy[x].xcor() > 215: #Check collision right wall enemy[x].setx(210) enemy[x].left(180) enemy[x].shape("cat_left.gif") if enemy[x].xcor() < -215: #Check collision left wall enemy[x].setx(-210) enemy[x].right(180) enemy[x].shape("cat_right.gif") if enemy[x].ycor() > 215: #Check ceiling collision enemy[x].sety(210) enemy[x].right(180) if enemy[x].ycor() < -215: #Check floor collision enemy[x].sety(-210) enemy[x].left(180) if collided(you, enemy[x], eat_range): #Check collision with player enemy[x].hideturtle() #Hide if collided enemy[x].setpos( -600, -600) #Move far away to prevent duplicate collisions deathcount += 1 #Update deathcount chomp(you) scoreTurt.clear() scoreTurt.write("Deathcount: " + str(deathcount), font=("Arial", 12, "normal")) for j in range(0, len(ball_list)): #check ball collision if collided(ball_list[j], enemy[x], ball_range): enemy[x].hideturtle() #Hide if collided enemy[x].setpos( -600, -600 ) #Move far away to prevent duplicate collisions deathcount += 1 #Update deathcount scoreTurt.clear() scoreTurt.write("Deathcount: " + str(deathcount), font=("Arial", 12, "normal")) scoreTurt.clear()
class TurtlePaint(): def __init__(self, settings): self.t1 = Turtle() # main turtle self.t2 = Turtle() # draws color bar self.t3 = Turtle() # selects current color self.t4 = Turtle() # draws tool bar border self.t5 = Turtle() # makes shape stamps self.t6 = Turtle() # selects current shape self.t7 = Turtle() # refers to instructions self.t8 = Turtle() # selects current fillcolor self.s = Screen() self.instructions = { "b": "begin filling", "c": "clear all", "e": "end filling", "f": "change fillcolor", "h": "turn left", "j": "go backward", "k": "go forward", "l": "turn right", "p": "pen up / pen down", "s": "save picture", "t": "change turtle shape", "u": "undo last drawing", "space": "change pencolor", "arrow_up": "increase pensize", "arrow_down": "decrease pensize" } self.v = VolumeBar(settings.get("start_volume_bar"), settings.get("max_pensize"), self.s) self.toggler = StringToggler(settings.get("start_pendown"), settings.get("start_penup"), "pen down", "pen up", self.s) self.colors = [ "green", "red", "yellow", "pink", "blue", "lightblue", "orange", "purple", "black", "white" ] self.fillcolors = [ "green", "red", "yellow", "pink", "blue", "lightblue", "orange", "purple", "black", "white" ] self.shapes = [ "turtle", "triangle", "circle", "square", "arrow", "classic" ] self.settings = settings self.setup() def setup(self): self.t1.speed(0) self.t1.resizemode("auto") # turtlesize increases with pensize self.t2.hideturtle() self.t3.hideturtle() self.t4.hideturtle() self.t5.hideturtle() self.t6.hideturtle() self.t7.hideturtle() self.t8.hideturtle() self.s.screensize( settings.get("screen_dims")[0], settings.get("screen_dims")[1]) # space for turtle self.s.setup( settings.get("screen_dims")[0] * 1.1, settings.get("screen_dims")[1] * 1.1) # actual screen size self.s.cv._rootwindow.resizable(False, False) self.s.title(self.settings.get("title")) self.draw_color() self.v.draw_volume_bar() self.draw_toolbar() self.draw_shapes() self.refer_to_instructions() self.v.fill_volume_bar(self.t1.pensize() / self.settings.get("max_pensize")) self.register_callbacks() def register_callbacks(self): self.t1.onclick(self.t1.goto, 1) self.s.onkey(self.pen_change, "p") self.s.onkey(self.change_color, "space") self.s.onkey(self.increase_pensize, "Up") self.s.onkey(self.decrease_pensize, "Down") self.s.onscreenclick(self.go_to, 1) self.t1.ondrag(self.go_to, 1) self.s.onkey(self.screen_exit_handler, "Escape") self.s.onkey(self.screen_save_handler, "s") self.s.onkeypress(self.undo_drawings, "u") self.s.onkey(self.clear_all, "c") self.s.onkey(self.change_shape, "t") self.s.onkeypress(self.move_down, "j") self.s.onkey(self.show_instructions, "?") self.s.onkeypress(self.move_up, "k") self.s.onkeypress(self.turn_left, "h") self.s.onkeypress(self.turn_right, "l") self.s.onkey(self.t1.begin_fill, "b") self.s.onkey(self.t1.end_fill, "e") self.s.onkey(self.change_fillcolor, "f") self.s.listen() def screen_exit_handler(self): print("[debug] got ESC, quitting") exit(0) def screen_save_handler(self): print("[debug] trying to save canvas to a pdf file") name = self.s.textinput("Save a Screenshot to PDF", "Please enter a filename (without .pdf): ") self.s.getcanvas().postscript(file="tmp.ps", colormode="color") if platform.system() == "Windows": cmd = r'c:\Program Files\Git\usr\bin\bash.exe' p = subprocess.Popen( [cmd, "ps2pdf", "tmp.ps", "{}.pdf".format(name)], shell=True) else: # we're actually on a good OS here p = subprocess.Popen(["ps2pdf tmp.ps {}.pdf".format(name)], shell=True) ret = p.wait() if ret == 0: os.remove("tmp.ps") self.s.listen() # required to re-focus onto turtle def show_instructions(self): win = Tk() row = 0 column = 0 for instruction in self.instructions: Label(win, text=instruction).grid(row=row, column=column, sticky="W", ipadx=10) column += 1 Label(win, text=self.instructions.get(instruction)).grid(row=row, column=column, sticky="W", ipadx=10) row += 1 column = 0 def pen_change(self): if self.t1.isdown(): self.t1.penup() self.toggler.toggle() else: self.t1.pendown() self.toggler.toggle() def draw_selector(self, turtle, pensize): turtle.clear() turtle.pensize(pensize) for _ in range(4): turtle.fd(30) turtle.left(90) def draw_color(self): self.s.tracer(False) x = -410 pos = (x, 310) self.t2.penup() self.t3.penup() self.t8.penup() self.t2.goto(pos) self.t3.goto(-50, 310) self.t8.goto(-35, 295) self.t2.right(90) self.t3.right(90) self.t2.pendown() self.t3.pendown() self.t8.pendown() self.t2.pensize(1) for color in self.colors: # determine colors if color == "white": self.t2.pencolor("black") self.t2.fillcolor("white") else: self.t2.color(color) # draw square self.t2.begin_fill() for _ in range(4): self.t2.fd(30) self.t2.left(90) # pen up, go to next square, pen down self.t2.end_fill() self.t2.penup() x += 40 self.t2.goto(x, 310) self.t2.pendown() self.s.tracer(True) def change_color(self): if self.t3.pos()[0] >= -50: x = -410 else: x = self.t3.pos()[0] + 40 color = self.colors.pop(0) self.t1.pencolor(color) self.colors.append(color) self.s.tracer(False) if color == "black": self.t3.pencolor("dim gray") else: self.t3.pencolor("black") self.t3.penup() self.t3.goto(x, 310) self.t3.pendown() self.draw_selector(self.t3, 4) self.s.tracer(True) def change_fillcolor(self): self.s.tracer(False) if self.t8.pos()[0] >= -36: x = -395 else: x = self.t8.pos()[0] + 40 fillcolor = self.fillcolors.pop(0) self.t1.fillcolor(fillcolor) self.fillcolors.append(fillcolor) if fillcolor == "black": self.t8.pencolor("dim gray") else: self.t8.pencolor("black") self.t8.penup() self.t8.goto(x, 295) self.t8.pendown() self.t8.clear() self.t8.dot(10) self.s.tracer(True) def increase_pensize(self): pensize = self.t1.pensize() + self.settings.get("pensize_stepsize") if pensize <= self.settings.get("max_pensize"): self.t1.pensize(pensize) self.v.fill_volume_bar(self.t1.pensize() / self.settings.get("max_pensize")) def decrease_pensize(self): pensize = self.t1.pensize() - self.settings.get("pensize_stepsize") if pensize >= 1: self.t1.pensize(pensize) self.v.fill_volume_bar(self.t1.pensize() / self.settings.get("max_pensize")) def draw_toolbar(self): self.s.tracer(False) self.t4.penup() self.t4.goto(-420, 260) self.t4.pensize(3) self.t4.pendown() self.t4.fd(840) self.t4.penup() self.t4.goto(-420, -300) self.t4.pendown() self.t4.fd(840) self.s.tracer(True) def draw_shapes(self): self.s.tracer(False) self.t5.penup() self.t5.resizemode("user") self.t5.shapesize(0.9, 0.9) x = 200 self.t5.fillcolor("white") for shape in self.shapes: self.t5.shape("turtle") self.t5.goto(x, 295) self.t5.shape(shape) self.t5.stamp() x += 40 self.t6.penup() self.t6.goto(389, 280) self.s.tracer(True) def change_shape(self): self.s.tracer(False) shape = self.shapes.pop(0) self.t1.shape(shape) self.shapes.append(shape) if self.t6.pos()[0] >= 380: x = 189 elif shape == "circle": x = self.t6.pos()[0] + 38 elif shape == "arrow": x = self.t6.pos()[0] + 43 elif shape == "classic": x = self.t6.pos()[0] + 32 elif shape == "triangle": x = self.t6.pos()[0] + 39 else: x = self.t6.pos()[0] + 40 self.t6.penup() self.t6.goto(x, 280) self.t6.pendown() self.t6.pencolor("green") self.draw_selector(self.t6, 2) self.s.tracer(True) def refer_to_instructions(self): self.s.tracer(False) self.t7.penup() self.t7.goto(-410, -320) self.t7.pendown() self.t7.write("press '?' for instructions") self.s.tracer(True) def move_up(self): self.t1.fd(10) def move_down(self): self.t1.backward(10) def turn_left(self): heading = self.t1.heading() if heading == 355: self.t1.setheading(0) else: heading += 5 self.t1.setheading(heading) def turn_right(self): heading = self.t1.heading() if heading == 0: self.t1.setheading(355) else: heading -= 5 self.t1.setheading(heading) def go_to(self, x, y): if y < 258 and y > -300: self.t1.goto(x, y) def undo_drawings(self): self.t1.undo() def clear_all(self): self.t1.clear() def mainloop(self): mainloop()
writer.hideturtle() writer.setpos(-40, 270) # Main Game is_food = False game_on = True while game_on: screen.update() write_score() move_snake() # Getting Turtle object and BOOL for is_food if is_food == False: food = create_food() is_food = True # All Collision Checks # Checks for collision and hides object, sets food false, clears score, grows snake. if check_col_food(): grow_snake() is_food = False food.hideturtle() writer.clear() check_col_wall() check_col_body() time.sleep(0.1) screen.mainloop()
class TetrisBoard(object): def __init__(self, cols, rows): self.cols, self.rows = cols, rows self.screen = Screen() self.screen.screensize(BLOCKWIDTH*cols-50, BLOCKWIDTH*rows-50) self.screen.setup(BLOCKWIDTH*cols+12, BLOCKWIDTH*rows+12) self.screen.title("Turtle Tetris") self.screen.bgcolor("black") self.writer = Turtle() self.writer.ht() self.label = None self.grid = {} self.screen.tracer(False) for row in range(rows): for col in range(cols): self.grid[(col, row)] = TetrisTurtle(col, row) self.screen.tracer(True) self.brick = TetrisBrick(self) self.result = 0 self.LEVEL = 0.6 self.keybuffer = KeyBuffer(self.screen, ["Right", "Left", "Up", "Down", "space", "Escape"]) self.reset() self.screen.listen() self.t1 = time() def reset(self): self.result = 0 self.LEVEL = 0.600 self.screen.tracer(False) self.writer.clear() if self.label: self.writer.clearstamp(self.label) for x in range(COLUMNS): for y in range(ROWS): self.grid[(x,y)].fillcolor("") self.screen.tracer(True) self.state = "NEWBRICK" def blink(self, y, n=1): for _ in range(n): for color in ("white", "black"): self.screen.tracer(False) for x in range(COLUMNS): self.grid[(x,y)].pencolor(color) sleep(self.LEVEL/10.0) self.screen.tracer(True) def display_result(self): tb = self tb.writer.color("white", "gray20") tb.writer.shape("square") tb.writer.shapesize(5, 15) tb.writer.goto(-4 ,0) self.label = tb.writer.stamp() tb.writer.goto(-2,3) tb.writer.write(str(tb.result) + " rows!", align="center", font = ("Courier", 24, "bold") ) tb.writer.goto(-2,-22) tb.writer.write("New game : <spacebar>", align="center", font = ("Courier", 16, "bold") ) tb.writer.goto(-2,-42) tb.writer.write("Quit : <escape>", align="center", font = ("Courier", 16, "bold") ) def getcolor(self, col, row): return self.grid[(col, row)].fillcolor() def setcolor(self, col, row, color): return self.grid[(col, row)].fillcolor(color) def rowfree(self, row): return not any([self.getcolor(col, row) for col in range(COLUMNS)]) def rowfull(self, row): return all([self.getcolor(col, row) for col in range(COLUMNS)]) def cleanup(self, shp): try: ymax = max([y for (x,y) in shp]) except ValueError: self.state = "FINIS" return currenty = ymax while currenty > 0: if self.rowfull(currenty): self.blink(currenty, 2) self.result += 1 if self.result == 8: self.LEVEL = 0.4 elif self.result == 20: self.LEVEL = 0.25 y = currenty while True: self.screen.tracer(False) for c in range(COLUMNS): self.setcolor(c, y, self.getcolor(c, y-1)) self.screen.tracer(True) if self.rowfree(y): break else: y -= 1 else: currenty -= 1 tetris.state = "NEWBRICK" def run(self): tb = self b = self.brick ### actions to be done unconditionally if tb.state == "NEWBRICK": if b.reset(): self.t1 = time() tb.state = "FALL" else: tb.state = "FINIS" t2 = time() if tb.state == "FALL" and t2 - self.t1 > self.LEVEL: b.down() b.apply("Step") self.t1 = t2 ### actions bound to key events key = self.keybuffer.getkey() if key: if tb.state == "FALL": if key == "Left": b.shiftleft() elif key == "Right": b.shiftright() elif key == "Down": b.drop() tb.state = "CLEANUP" elif key == "Up": b.turn() elif key == "space": tb.state = "BREAK" b.apply(key) elif tb.state == "BREAK": if key == "space": tb.state = "FALL" elif tb.state == "ADE": if key == "space": tb.reset() tb.state = "NEWBRICK" elif key == "Escape": tb.screen.bye() if tb.state == "CLEANUP": tb.cleanup(b.shape1) if tb.state == "FINIS": tb.display_result() tb.state = "ADE" self.screen.ontimer(self.run, 100)
class ScoreBoard: def __init__(self): self.scores = HighScores() self.player_score = 0 self.text_turtle = Turtle() self.screen = Screen() # to be a read/write from a text file and allow high scores to transcend to other runs of the program self.high_scores = self.scores.get_scores() def display_score(self): self.text_turtle.penup() self.text_turtle.hideturtle() self.text_turtle.goto(0, 280) self.text_turtle.color("green") self.text_turtle.write(f"Player score: {self.player_score}", move=False, align="center", font=("Arial", 14, "normal")) def update_score(self): self.player_score += 1 self.text_turtle.clear() self.text_turtle.write(f"Player score: {self.player_score}", move=False, align="center", font=("Arial", 14, "normal")) def check_high_score(self): if self.player_score > self.high_scores[len(self.high_scores) - 1][1]: player_name = self.screen.textinput( "High score detected!", "What name should we record the high score under?") self.order_high_scores(player_name) self.scores.record_scores(self.high_scores) self.display_high_scores() # this is weird, could be written cleaner def order_high_scores(self, name): for score in range(len(self.high_scores) - 1, -1, -1): if self.high_scores[score][1] < self.player_score: x = self.high_scores[score] self.high_scores[score] = (name, self.player_score) if score + 1 <= len(self.high_scores) - 1: self.high_scores[score + 1] = x def display_high_scores(self): turtle_x = 0 turtle_y = 70 self.text_turtle.goto(turtle_x, turtle_y) self.text_turtle.write( arg=f" Game Over!\nFinal score: {self.player_score}", align="center", font=("Arial", 16, "normal")) turtle_y -= 40 self.text_turtle.goto(turtle_x, turtle_y) self.text_turtle.write(arg=f" HIGH SCORES!", align="center", font=("Arial", 20, "normal")) turtle_y -= 20 for hscore in self.high_scores: turtle_y -= 20 self.text_turtle.goto(turtle_x, turtle_y) self.text_turtle.write(arg=f" {hscore[0]}: {hscore[1]}", align="center", font=("Arial", 16, "normal"))
class Game(object): def __init__(self): screen.tracer(False) screen.setup(width=MAX_X*SQUARE_WIDTH + DM, height = (MAX_Y+FREEROWS)*SQUARE_WIDTH + DM, startx = -20, starty = 20) screen.screensize(MAX_X*SQUARE_WIDTH + DM - 50, (MAX_Y+FREEROWS)*SQUARE_WIDTH + DM -50) self.designer = Turtle(visible=False) starttime = time.clock() self.messagero = Turtle(visible=False) self.messagero.penup() self.messagero.pencolor("blue") self.messagero.goto(0, -(MAX_Y+FREEROWS)*SQUARE_WIDTH/2+6) self.message("Please wait a moment!") self.designer.pencolor("gray90") w2 = SQUARE_WIDTH // 2 for c in range(MAX_X+1): x1, y1 = coords(c,0) x2, y2 = coords(c, MAX_Y) x1, y1, y2 = x1 - w2, y1 - w2, y2 - w2 self.line(x1, y1, x1, y2) for r in range(MAX_Y+1): x1, y1 = coords(0, r) x2, y2 = coords(MAX_X, r) x1, y1, x2 = x1 - w2, y1 - w2, x2 - w2 self.line(x1, y1, x2, y1) screen.update() self.patches = {} for r in range(MAX_Y): for c in range(MAX_X): self.patches[(c, r)] = Patch(c, r) self.state = {(41,33):1, (42,33):1, (43,34):1, (42,32):1, (42,34):1} for cell in self.state: self.patches[cell].showturtle() self.newstate = None stoptime = time.clock() print(stoptime - starttime) screen.update() screen.onkey(self.run, "space") screen.onkey(screen.bye, "Escape") screen.onkey(self.clear, "c") screen.listen() screen.onclick(self.toggle) self.message("spacebar:start/pause | left click:toggle cell | c:clear" " | escape:quit") def message(self, txt): self.messagero.clear() self.messagero.write(txt, align="center", font=("Courier", 14, "bold")) def line(self, x1, y1, x2, y2): self.designer.penup() self.designer.goto(x1, y1) self.designer.pendown() self.designer.goto(x2, y2) def update_display(self): screen.tracer(False) for cell in self.state: if cell not in self.newstate: try: self.patches[cell].hideturtle() except KeyError: pass for cell in self.newstate: try: self.patches[cell].showturtle() self.patches[cell].color(calccolor(self.newstate[cell])) except KeyError: pass screen.tracer(True) def clear(self): self.newstate = {} self.update_display() self.state = {} def toggle(self, x, y): cell = cellindices(int(x), int(y)) self.newstate = self.state.copy() if cell in self.newstate: del self.newstate[cell] else: self.newstate[cell] = 1 self.update_display() self.state = self.newstate def run(self): starttime = time.clock() anzahl_generationen = 0 screen.onkey(self.stop, "space") generation = generate(self.state) self.RUNNING = True while self.RUNNING: self.newstate = next(generation) self.update_display() self.state = self.newstate anzahl_generationen +=1 stoptime = time.clock() t = stoptime - starttime print(anzahl_generationen, t, anzahl_generationen/t) def stop(self): self.RUNNING = False screen.onkey(self.run, "space")
cursor.speed(2) cursor.penup() cursor.setposition(-70,0) cursor.color('red') cursor.pendown() cursor.left(90) cursor.forward(100) cursor.right(150) cursor.forward(115) cursor.left(120) cursor.forward(115) cursor.right(150) cursor.forward(100) time.sleep(0.5) cursor.clear() cursor.penup() cursor.setposition(-70,0) cursor.right(180) cursor.color('blue') cursor.pendown() cursor.right(30) cursor.forward(115) cursor.right(120) cursor.forward(115) cursor.right(180) cursor.forward(57.5) cursor.left(60) cursor.forward(60) time.sleep(0.5)