def enemy_attack(): global bullets global enemyleft global enemy_shooting_time_interval turtle.addshape("bulletnew.gif") for enemy in enemies: if enemy.isvisible()== True and cheatcontrol==1 : enemyleft.append(enemy) if len(enemyleft)>0 and cheatcontrol==1 : no_of_enemy = random.randint(0,len(enemyleft)-1) bullet = turtle.Turtle() bullet.hideturtle() if newthemegamecontrol == 0: bullet.shape("circle") bullet.shapesize(0.5,0.5,1) bullet.fillcolor("red") if newthemegamecontrol == 1: bullet.shape("bulletnew.gif") bullet.shapesize(0.5,0.5,1) bullet.up() bullet.goto(enemyleft[no_of_enemy].xcor(),\ enemyleft[no_of_enemy].ycor()) bullet.right(90) bullets.append(bullet) bullet.showturtle() enemyleft=[] turtle.ontimer(enemy_attack,enemy_shooting_time_interval)
def main(): #设置一个画面 windows = turtle.Screen() #设置背景 windows.bgcolor('blue') #生成一个黄色乌龟 bran = turtle.Turtle() bran.shape('turtle') bran.color('yellow') #开始你的表演 bran.circle(50,360) bran.turtlesize(1,1,3) #乌龟大小 #bran.home() bran.setx(300) bran.sety(100) #设置乌龟为止 bran.seth(90) #设置乌龟开始的角度 bran.begin_poly() #开始记录多边形顶点 bran.fd(100) #forward bran.left(20) bran.fd(30) bran.left(60) bran.fd(50) bran.end_poly() #停止记录多边形顶点,并将其与第一个顶点相连 #p=turtle.get_poly() turtle.addshape('triangle',((5,-3),(0,5),(-5,-3))) #添加形状 sea = turtle.Turtle() sea.shape('triangle') #改成刚加入的形状 sea.color('red') sea.setpos(-30,100) #设置起始位置 sea.circle(50,360,200)
def createJigsaw(): global allTurtles # Initialize the variables of total number of rows and columns # Now we go through the jigsaw piece row-column structure # Go through each row # Go through each column in this row for row in range(3): for column in range(3): # Make a new turtle x = random.randint(-width / 2, width / 2) y = random.randint(-height / 2, height / 2) turtleone = turtle.Turtle() turtleone.up() turtleone.goto(x, y) turtle.down() # Move it to a random position # Build the image file name thisFilename = "image" + "-" + str(row) + "-" + str( column) + ".gif" turtle.addshape(thisFilename) turtleone.shape(thisFilename) turtleone.ondrag(turtleone.goto) turtleone.speed(0) allTurtles.append(turtleone)
def main(): #设置一个画面 windows = turtle.Screen() #设置背景 windows.bgcolor('blue') #生成一个黄色乌龟 bran = turtle.Turtle() bran.shape('turtle') bran.color('yellow') #开始你的表演 bran.circle(50, 360) bran.turtlesize(1, 1, 3) #乌龟大小 #bran.home() bran.setx(300) bran.sety(100) #设置乌龟为止 bran.seth(90) #设置乌龟开始的角度 bran.begin_poly() #开始记录多边形顶点 bran.fd(100) #forward bran.left(20) bran.fd(30) bran.left(60) bran.fd(50) bran.end_poly() #停止记录多边形顶点,并将其与第一个顶点相连 #p=turtle.get_poly() turtle.addshape('triangle', ((5, -3), (0, 5), (-5, -3))) #添加形状 sea = turtle.Turtle() sea.shape('triangle') #改成刚加入的形状 sea.color('red') sea.setpos(-30, 100) #设置起始位置 sea.circle(50, 360, 200)
def register_shapes(): def rotate(point, angle, origin=(0, 0)): """ Rotate a point counterclockwise by a given angle around a given origin. The angle should be given in radians. """ ox, oy = origin px, py = point sa, ca = sin(angle), cos(angle) dx, dy = px - ox, py - oy qx = ox + ca * dx - sa * dy qy = oy + sa * dx + ca * dy return qx, qy def map_transform(points, angle=pi / 2, dx=0, dy=0, scale=1): return list( map( lambda x: rotate((scale * (x[0] + dx), scale * (x[1] + dy)), pi / 2), points)) def build_tank(side, objects): tank = turtle.Shape("compound") for o in objects: tank.addcomponent(*o) turtle.addshape("tank_" + side, tank) # Bullet b = turtle.Shape("polygon", ((-5, -5), (-5, 5), (5, 5), (5, -5))) turtle.addshape("bullet", b) circle = screen._shapes["circle"]._data # 3 wheels components = [] components.append((map_transform(circle, dy=-5), "black")) components.append((map_transform(circle, dx=20, dy=-5), "yellow")) components.append((map_transform(circle, dx=-20, dy=-5), "black")) # Tank body trapezoid = ((-35, 5), (35, 5), (30, 25), (-30, 25)) components.append((map_transform(trapezoid), "red")) # Tank turret / gun rectangle = ((30, 15), (30, 20), (60, 20), (60, 15)) components.append((map_transform(rectangle), "red")) build_tank("left", components) components.pop() components.pop() components.append((map_transform(trapezoid), "blue")) rectangle = ((-30, 15), (-30, 20), (-60, 20), (-60, 15)) components.append((map_transform(rectangle), "blue")) # Uncomment to draw bounding box for debugging #components.append((map_transform(circle, 0, 0, 0, 3), "yellow")) build_tank("right", components)
def newthemegamestart(): global newthemegamecontrol global intro_line global new_intro_line newthemegamecontrol = 1 turtle.bgpic("BGPICNEW.gif") new_gamestarsoundeffect.play() time.sleep(2) global player, laser global enemy_shooting_time_interval intro_line.clear() new_intro_line.clear() start_button.clear() start_button.hideturtle() new_theme_start_button.clear() new_theme_start_button.hideturtle() left_arrow.hideturtle() right_arrow.hideturtle() labels.clear() enemy_number_text.clear() if enemy_number>=6: enemy_max_x = window_width/2 - enemy_size * 6 else: enemy_max_x = window_width/2 - enemy_size * enemy_number turtle.addshape("new_spaceship.gif") player = turtle.Turtle() player.shape("new_spaceship.gif") player.up() player.goto(player_init_x, player_init_y) turtle.onkeypress(playermoveleft,"Left") turtle.onkeypress(playermoveright,"Right") turtle.listen() for i in range(enemy_number): enemy = turtle.Turtle() enemy.shape("new_enemy.gif") enemy.up() enemy.goto(enemy_init_x + enemy_size * (i % 6), \ enemy_init_y - enemy_size * (i // 6)) enemies.append(enemy) laser = turtle.Turtle() laser.shape("bookfire.gif") # Change the size of the turtle and change the orientation of the turtle laser.shapesize(laser_width / 20, laser_height / 20) laser.left(90) laser.up() # Hide the laser turtle laser.hideturtle() # Part 4.2 - Mapping the shooting function to key press event turtle.onkeypress(shoot,"space") turtle.listen() turtle.update() turtle.ontimer(enemy_attack,enemy_shooting_time_interval) turtle.ontimer(updatescreen,update_interval)
def forme(self, hauteur, largeur): # crée un polygone ayant une certaine largeur et hauteur forme = ((0, 0), (-hauteur, 0), (-hauteur, -largeur), (0, -largeur), (0, 0), (-hauteur, 0), (-hauteur, largeur), (0, largeur)) turtle.addshape("forme",forme) self.color('gray') self.fillcolor('gray') self.shape("forme") self.penup()
def inst(): inn = turtle.clone() inn.home() turtle.addshape("in.gif") inn.shape("in.gif") inn.stamp() turtle.update()
def initialize_resolution(): """This function is used for configure resolution settings""" turtle.screensize() turtle.setup(width = 1.0, height = 1.0) turtle.speed(0) turtle.Screen() turtle.title("TURTLE RACE") turtle.addshape('python.gif')
def drawMTAMap(): mapImage = turtle.Turtle() image = "MTAMap.gif" # image size windowAdj = (int(turtle.screensize()[0]/2),int(turtle.screensize()[1]/2)) mapImage.goto(imageSize[0]/2-windowAdj[0],imageSize[1]/2-windowAdj[1]) turtle.addshape(image) mapImage.shape(image)
def __init__(self): turtle.Turtle.__init__(self) self.penup() turtle.addshape("player.gif") self.shape("player.gif") self.speed(0) self.width = 20 self.height = 20 self.dy = 0 self.dx = 0 self.state = "ready" self.goto(-200, GROUND_LEVEL + self.height / 2)
def draw(grid, size): turtle.ht() turtle.speed(0) turtle.begin_poly() for x in range(4): turtle.fd(size) turtle.rt(90) turtle.end_poly() turtle.addshape('block', turtle.get_poly()) turtle.shape('block') turtle.pu() turtle.clear() file = "Mazes/maze " + str(len(grid[0]) - 2) + 'x' + str(len(grid) - 2) + " Solution" + ".txt" index = open(file, 'w') for x in grid: index.write(''.join(x) + '\n') print(''.join(x)) index.close() for n, i in enumerate(grid): turtle.setpos(-400, -n * size + 385) for j in i: if j == '#': turtle.pd() turtle.stamp() turtle.pu() turtle.fd(size) elif j == 'S': turtle.color("Red") turtle.pd() turtle.stamp() turtle.pu() turtle.color("Black") turtle.fd(size) elif j == 'E': turtle.pd() turtle.color("Green") turtle.stamp() turtle.color("Black") turtle.pu() turtle.fd(size) elif j == 'X': turtle.pd() turtle.color("Blue") turtle.stamp() turtle.color("Black") turtle.pu() turtle.fd(size) else: turtle.fd(size)
def draw(grid, size): turtle.ht() turtle.speed(0) turtle.begin_poly() for x in range(4): turtle.fd(size) turtle.rt(90) turtle.end_poly() turtle.addshape('block', turtle.get_poly()) turtle.shape('block') turtle.pu() turtle.clear() furthest = [] ends = deadends(grid) grid[ends[0][1]][ends[0][0]] = 'S' for x in ends: furthest.append(x[0] + x[1]) grid[ends[furthest.index(max(furthest))][1]][ends[furthest.index( max(furthest))][0]] = 'E' file = "Mazes/maze " + str(len(grid[0]) - 2) + 'x' + str(len(grid) - 2) + ".txt" index = open(file, 'w') for x in grid: index.write(''.join(x) + '\n') print(''.join(x)) index.close() for n, i in enumerate(grid): turtle.setpos(-400, -n * size + 385) for j in i: if j == '#': turtle.pd() turtle.stamp() turtle.pu() turtle.fd(size) elif j == 'S': turtle.color("Red") turtle.pd() turtle.stamp() turtle.pu() turtle.color("Black") turtle.fd(size) elif j == 'E': turtle.pd() turtle.color("Green") turtle.stamp() turtle.color("Black") turtle.pu() turtle.fd(size) else: turtle.fd(size)
def choice_character(): IMG = turtle.Turtle() turtle.addshape("./img7.gif") IMG.shape("./img7.gif") IMG.up() IMG.goto(-370, 0) IMG2 = turtle.Turtle() turtle.addshape("./img32.gif") IMG2.shape("./img32.gif") IMG2.up() IMG2.goto(370, 0)
def __init__(self, initSpeed, startx, starty): '''initialize a turtle for the invader given a speed to move the invader at''' turtle.Turtle.__init__(self) os.chdir(os.getcwd() + '/img') turtle.addshape('invader.gif') turtle.addshape('explosion.gif') os.chdir('..') self.invaderspeed = initSpeed self.invaderstate = 'live' self.shape('invader.gif') self.penup() self.speed(0) self.setposition(startx, starty)
def __init__(self, initSpeed): '''initialize a turtle for the player given a speed to move the player at''' turtle.Turtle.__init__(self) os.chdir(os.getcwd() + '/img') turtle.addshape('player.gif') os.chdir('..') self.playerspeed = initSpeed self.color('white') self.shape('player.gif') self.penup() self.speed(0) self.setposition(0, -185) #bottom middle of screen self.setheading(90) #rotate 90 degrees CCW
def add_object(Object, x, y, gif): # the speed that turtle module draws the shape on screen whenever it moves to let us see it Object.speed(0) #to let the shape updated in the maximum speed #no drawing when the turtle object is moving Object.penup() #position of the Object Object.goto(x, y) #turtle model has these shapes ['arrow', 'blank', 'circle', 'classic', 'square', 'triangle', 'turtle'] #but we can add a shape as gif image using the addshape method turtle.addshape(name=gif, shape=None) #we use the shape method to get the shape on the window and we use our shape instead of the ready shapes like shape("square") Object.shape(gif) # to be appeared and visible on the screen at the same time Object.showturtle()
def ajouterDemiCercle(): # Initialisation. points = () for i in range(0,11): # Calcul des coordonnées du point. x = 10 * math.cos(math.pi/10 * i) y = 10 * math.sin(math.pi/10 * i) # Ajout du point au tuple. points = points + ((x,y),) # Ajouter le demi-cercle. turtle.addshape("semicircle", points)
def gameover(message): # Part 5.3 - Improving the gameover() function gameover_turtle = turtle.Turtle() gameover_turtle.hideturtle() turtle.addshape("yoda.gif") gameover_turtle.shape("yoda.gif") gameover_turtle.pencolor("yellow") gameover_turtle.up() #gameover_turtle.goto(-50,-100) #gameover_turtle.down() gameover_turtle.write(message, align="center", font=("System", 30, "bold")) gameover_turtle.showturtle() turtle.update()
def startGame(): global robot_turtle, drawing_turtle global current_task_handler # Set up the turtle window turtle.setup(500, 500) turtle.title("COMP1021 Robot Game") # Set up the coordinate system of the window to be the same as the map turtle.setworldcoordinates(-1, game_map_total_rows + 0.5, game_map_total_cols + 0.5, -1) # Add the robot images as turtle shapes turtle.addshape("robot_up.gif") turtle.addshape("robot_down.gif") turtle.addshape("robot_left.gif") turtle.addshape("robot_right.gif") # Create a robot turtle robot_turtle = turtle.Turtle() robot_turtle.up() robot_turtle.shape("robot_up.gif") # Create a turtle for drawing the game graphics such as the map drawing_turtle = turtle.Turtle() drawing_turtle.up() drawing_turtle.hideturtle() # Set up the key event for the 'r' key turtle.onkeypress(toggleRobotView,'r') turtle.listen() # Update the game map drawGameMap() # Select corresponding task handler if currentTask == "task0": current_task_handler = task_handlers["task0"] elif currentTask == "task1": current_task_handler = task_handlers["task1"] elif currentTask == "task2": current_task_handler = task_handlers["task2"] elif currentTask == "task3": current_task_handler = task_handlers["task3"] elif currentTask == "task4": current_task_handler = task_handlers["task4"] else: current_task_handler = task_handlers["task5"] # Start the game loop turtle.ontimer(gameLoop, timing) turtle.done()
def gamestart(x, y): start_button.clear() start_button.hideturtle() Labels.clear() enemy_number_text.clear() Left_arrow.hideturtle() Right_arrow.hideturtle() text.clear() showtime.write("Shoot Interval:", font=("System", 10, "bold")) time.write(interval, font=("System", 10, "bold")) global player, laser turtle.addshape("spaceship.gif") player = turtle.Turtle() player.shape("spaceship.gif") player.up() player.goto(player_init_x, player_init_y) turtle.onkeypress(playermoveleft, "Left") turtle.onkeypress(playermoveright, "Right") turtle.listen() turtle.addshape("enemy.gif") turtle.addshape("enemy2.gif") for i in range(enemy_number): enemy = turtle.Turtle() enemy.shape("enemy.gif") enemy.up() enemy.goto(enemy_init_x + enemy_size * (i % 6), enemy_init_y - enemy_size * (i // 6)) enemies.append(enemy) laser = turtle.Turtle() turtle.addshape("laser.gif") laser.shape("laser.gif") laser.left(90) laser.up() laser.hideturtle() turtle.onkeypress(shoot, "space") turtle.listen() turtle.update() turtle.ontimer(updatescreen, update_interval) turtle.ontimer(shoot_bullet, interval) turtle.onkeypress(decreasetime, ",") turtle.onkeypress(increasetime, ".") turtle.listen() turtle.onkeypress(cheat_mode, "s") turtle.listen()
def prepareMissile(self): temporary = turtle.Turtle() temporary.color(self.color) screen = turtle.getscreen() delay = screen.delay() screen.delay(0) temporary.hideturtle() temporary.penup() missile = turtle.Shape("compound") body = ((0, 2), (-4, 0), (-4, -12), (-8, -16), (-8, -20), (8, -20), (8, -16), (4, -12), (4, 0)) missile.addcomponent(body, self.color, 'black') fire = ((-2, -20), (0, -32), (2, -20)) missile.addcomponent(fire, 'red', 'red') name = 'missile_{0}'.format(self.color) turtle.addshape(name, shape=missile) del temporary screen.delay(delay)
def createJigsaw(): global allTurtles # Initialize the variables of total number of rows and columns totalRows = 4 totalColumns = 4 # Now we go through the jigsaw piece row-column structure # Go through each row for row in range(totalRows): # Go through each column in this row for column in range(totalColumns): # Generate a random position width = turtle.window_width() height = turtle.window_height() x = random.randint(-width / 2, width / 2) y = random.randint(-height / 2, height / 2) print(x, y) # Make a new turtle newTurtle = turtle.Turtle() newTurtle.up() #speed is fastest so that you can get fast response when dragging the image newTurtle.speed(0) # Move it to the random position newTurtle.goto(x, y) # Build the image file name theFilename = str(row) + "-" + str(column) + ".gif" print(theFilename) # Add the image to the turtle system turtle.addshape( "C:\\Users\\Owner\\Desktop\\documents hkust\\sem 2 2020 spring\\COMP 1021\\cut_images_TRiwhzo2T2\\" + theFilename) # Apply the new image to this turtle newTurtle.shape( "C:\\Users\\Owner\\Desktop\\documents hkust\\sem 2 2020 spring\\COMP 1021\\cut_images_TRiwhzo2T2\\" + theFilename) # when drag, go to the place that it is dragged newTurtle.ondrag(newTurtle.goto) # Add the new turtle to the new list of turtles allTurtles.append(newTurtle)
def win(): #If you win win = int(random.uniform( 1, 4)) #picks random number and choose a you win image if win == 1: tigerblood = r"win1.gif" elif win == 2: tigerblood = r"win2.gif" elif win == 3: tigerblood = r"win3.gif" turtle.addshape(tigerblood) turtle.shape(tigerblood) w = turtle.Turtle() w.penup() w.hideturtle() w.goto(-120, -300) w.pendown() w.write("Congratulations!!!", font=(20))
def visualize_init(): global male_turtle, female_turtle, text_turtle turtle.setup(800, 200) turtle.screensize(780, 180) # Canvas size < window size to avoid scrollbars turtle.title("Gender Display") turtle.addshape("icon_male.gif") turtle.addshape("icon_female.gif") turtle.tracer(False) male_turtle = turtle.Turtle() female_turtle = turtle.Turtle() male_turtle.shape("icon_male.gif") female_turtle.shape("icon_female.gif") male_turtle.up() female_turtle.up() text_turtle = turtle.Turtle() text_turtle.up() text_turtle.hideturtle()
def lose(): #If you lose lost = int(random.uniform( 1, 4)) #picks random number and choose a you lose image if lost == 1: lost = r"lost1.gif" #assigns image to variable elif lost == 2: lost = r"lost2.gif" elif lost == 3: lost = r"lost3.gif" turtle.addshape(lost) #Adds image to turtle environment turtle.shape(lost) #displays it l = turtle.Turtle() l.penup() l.hideturtle() l.goto(-120, -300) l.pendown() l.write("Sorry, you lose!", font=(20))
def wombotCursor(): temporary = turtle.Turtle() screen = turtle.getscreen() delay = screen.delay() screen.delay(0) temporary.hideturtle() temporary.penup() wombot = turtle.Shape("compound") #legs leg1 = polyDodec(temporary, ORIGIN, ORIGIN, LENGTH_LONG) wombot.addcomponent(leg1, BROWN, "black") leg2 = polyDodec(temporary, ORIGIN, FOOT, LENGTH_LONG) wombot.addcomponent(leg2, BROWN, "black") leg3 = polyDodec(temporary, FOOT, ORIGIN, LENGTH_LONG) wombot.addcomponent(leg3, BROWN, "black") leg4 = polyDodec(temporary, FOOT, FOOT, LENGTH_LONG) wombot.addcomponent(leg4, BROWN, "black") #body body = polyTwoHalfDodec(temporary, BODY_X, BODY_Y, LENGTH_BODY) wombot.addcomponent(body, BROWN, "black") #eyes eye1 = polyDodec(temporary, EYE_X, EYE_Y1, LENGTH_MED) wombot.addcomponent(eye1, "white", "black") pupil1 = polyDodec(temporary, PUP_X, PUP_Y1, LENGTH_SHORT) wombot.addcomponent(pupil1, "black", "black") eye2 = polyDodec(temporary, EYE_X, EYE_Y2, LENGTH_MED) wombot.addcomponent(eye2, "white", "black") pupil2 = polyDodec(temporary, PUP_X, PUP_Y2, LENGTH_SHORT) wombot.addcomponent(pupil2, "black", "black") eyelid1 = polyHalfDodec(temporary, LID_X, LID_Y1, LENGTH_MED1) wombot.addcomponent(eyelid1, BROWN, "black") eyelid2 = polyHalfDodec(temporary, LID_X, LID_Y2, LENGTH_MED1) wombot.addcomponent(eyelid2, BROWN, "black") #nose nose = polyRoundishTri(temporary, NOSE_X, NOSE_Y, LENGTH_TRI) wombot.addcomponent(nose, "black", "black") turtle.addshape("wombot", shape=wombot) del temporary
def ending_surprise(user): turtle.addshape("./img33.gif") turtle.addshape("./img34.gif") ending_turtle = turtle.Turtle() ending_writer = turtle.Turtle() ending_writer.up() ending_writer.hideturtle() ending_writer.goto(0, -370) if (user == 1): ending_turtle.shape("./img34.gif") ending_writer.write("波贏", align="center", font=("Arial", 50, "normal")) elif (user == -1): ending_turtle.shape("./img33.gif") ending_writer.write("郭懂贏", align="center", font=("Arial", 50, "normal")) def ending_clear(x, y): ending_turtle.hideturtle() ending_turtle.onclick(ending_clear)
def process(x, y): if (-290 <= x <= -110): img = IMG[0] img.goto(-370, 0) IMG[1].hideturtle() IMG[2].hideturtle() elif (-90 <= x <= 90): img = IMG[1] img.goto(-370, 0) IMG[0].hideturtle() IMG[2].hideturtle() elif (110 <= x <= 290): img = IMG[2] img.goto(-370, 0) IMG[0].hideturtle() IMG[1].hideturtle() jef = turtle.Turtle() jef.up() turtle.addshape("./img0.gif") jef.shape("./img0.gif") jef.goto(350, 0) return
def prepareMissile(self): temporary = turtle.Turtle() temporary.color(self.color) screen = turtle.getscreen() delay = screen.delay() screen.delay(0) temporary.hideturtle() temporary.penup() missile = turtle.Shape("compound") body = self.polyRectangle(temporary, 0, 0, 20, 8) missile.addcomponent(body, self.color, 'black') left_eleron = ((-4, -20), (0, -20), (0, -12), (-4, -16)) missile.addcomponent(left_eleron, self.color, 'black') right_eleron = ((12, -20), (8, -20), (8, -12), (12, -16)) missile.addcomponent(right_eleron, self.color, 'black') nouse = ((0, 0), (4, 4), (8, 0)) missile.addcomponent(nouse, self.color, 'black') fire = ((2, -20), (4, -32), (6, -20)) missile.addcomponent(fire, 'red', 'red') turtle.addshape("missile", shape=missile) del temporary screen.delay(delay)
def choice_character(): def process(x, y): if (-290 <= x <= -110): img = IMG[0] img.goto(-370, 0) IMG[1].hideturtle() IMG[2].hideturtle() elif (-90 <= x <= 90): img = IMG[1] img.goto(-370, 0) IMG[0].hideturtle() IMG[2].hideturtle() elif (110 <= x <= 290): img = IMG[2] img.goto(-370, 0) IMG[0].hideturtle() IMG[1].hideturtle() jef = turtle.Turtle() jef.up() turtle.addshape("./img0.gif") jef.shape("./img0.gif") jef.goto(350, 0) return IMG = [0] * 3 randList = [2, 3, 4, 5, 6, 7, 8, 9, 10] rand_index = random.sample(randList, 3) for i in range(3): IMG[i] = turtle.Turtle() turtle.addshape("./img" + str(rand_index[i]) + ".gif") IMG[i].shape("./img" + str(rand_index[i]) + ".gif") IMG[i].up() IMG[i].goto(200 * (i - 1), 0) IMG[i].onclick(process)
def __init__(self, my_turtle=None, shape=None, pos=(0, 0)): ''' Initialize Button object. The button will be given an onclick listener that triggers the implementation of the abstract method, fun. :param my_turtle: turtle object which, when clicked, will trigger the action specified in the fun method. Default value=None - with this input, a new turtle is created. :param shape: shape for the turtle object. Default=None, in which case, the shape is the result of turtle.shape('square'); turtle.shapesize(2,10) :param pos: tuple input, (x,y), specifying the location of the turtle object. ''' print('test') if my_turtle is None: #If no turtle given, create new one self.turtle = turtle.clone() else: self.turtle = my_turtle self.turtle.speed(0) self.turtle.hideturtle() self.turtle.penup() self.turtle.goto(pos) if shape is None: self.turtle.shape('square') self.turtle.shapesize(2, 10) else: turtle.addshape(shape) self.turtle.shape(shape) self.turtle.showturtle() self.turtle.onclick(self.fun) #Link listener to button function turtle.listen() #Start listener
def start(self): self.bateau1 = MyTurtles() self.bateau1.penup() self.bateau1.speed(SPEED) self.bateau1.setx(300) self.bateau1.sety(200) bateauun = ((0, 0), ((0 - 5), (DEFAULT_MARGIN - DEFAULT_MARGIN / 4) / 2), (0, DEFAULT_MARGIN - DEFAULT_MARGIN / 4), ((DEFAULT_MARGIN * 2) - DEFAULT_MARGIN / 2, DEFAULT_MARGIN - DEFAULT_MARGIN / 4), (((DEFAULT_MARGIN * 2) - DEFAULT_MARGIN / 2) + 5, (DEFAULT_MARGIN - DEFAULT_MARGIN / 4) / 2), ((DEFAULT_MARGIN * 2) - DEFAULT_MARGIN / 2, 0)) turtle.addshape('bateauun', bateauun) self.bateau1.shape('bateauun') self.bateau1.penup() self.bateau1.fillcolor('white') self.bateau1.createBateau(2, self.bateau1.getcoords(self.bateau1.xcor(), self.bateau1.ycor()), "Torpilleur") self.listeBateauJoueur1.append(self.bateau1.bateau) self.bateau1.ondrag(self.bateau1.move) self.bateau1.onrelease(self.bateau1.changeOrientation, 3) self.bateau2 = MyTurtles() self.bateau2.penup() self.bateau2.speed(SPEED) self.bateau2.setx(250) self.bateau2.sety(200) bateaudeux = ((0, 0), ((0 - 5), (DEFAULT_MARGIN - DEFAULT_MARGIN / 4) / 2), (0, DEFAULT_MARGIN - DEFAULT_MARGIN / 4), ((DEFAULT_MARGIN * 3) - DEFAULT_MARGIN / 2, DEFAULT_MARGIN - DEFAULT_MARGIN / 4), (((DEFAULT_MARGIN * 3) - DEFAULT_MARGIN / 2) + 5, (DEFAULT_MARGIN - DEFAULT_MARGIN / 4) / 2), ((DEFAULT_MARGIN * 3) - DEFAULT_MARGIN / 2, 0)) turtle.addshape('bateaudeux', bateaudeux) self.bateau2.shape('bateaudeux') self.bateau2.fillcolor('red') self.bateau2.penup() self.bateau2.createBateau(3, self.bateau2.getcoords(self.bateau2.xcor(), self.bateau2.ycor()), "Sous-Marin") self.listeBateauJoueur1.append(self.bateau2.bateau) self.bateau2.ondrag(self.bateau2.move) self.bateau2.onrelease(self.bateau2.changeOrientation, 3) self.bateau3 = MyTurtles() self.bateau3.penup() self.bateau3.speed(SPEED) self.bateau3.setx(350) self.bateau3.sety(200) bateautrois = ((0, 0), ((0 - 5), (DEFAULT_MARGIN - DEFAULT_MARGIN / 4) / 2), (0, DEFAULT_MARGIN - DEFAULT_MARGIN / 4), ((DEFAULT_MARGIN * 3) - DEFAULT_MARGIN / 2, DEFAULT_MARGIN - DEFAULT_MARGIN / 4), (((DEFAULT_MARGIN * 3) - DEFAULT_MARGIN / 2) + 5, (DEFAULT_MARGIN - DEFAULT_MARGIN / 4) / 2), ((DEFAULT_MARGIN * 3) - DEFAULT_MARGIN / 2, 0)) turtle.addshape('bateautrois', bateautrois) self.bateau3.shape('bateautrois') self.bateau3.fillcolor('yellow') self.bateau3.penup() self.bateau3.createBateau(3, self.bateau3.getcoords(self.bateau3.xcor(), self.bateau3.ycor()), "Contre-Torpilleur") self.listeBateauJoueur1.append(self.bateau3.bateau) self.bateau3.ondrag(self.bateau3.move) self.bateau3.onrelease(self.bateau3.changeOrientation, 3) self.bateau4 = MyTurtles() self.bateau4.penup() self.bateau4.speed(SPEED) self.bateau4.setx(250) self.bateau4.sety(0) bateauquatre = ((0, 0), ((0 - 5), (DEFAULT_MARGIN - DEFAULT_MARGIN / 4) / 2), (0, DEFAULT_MARGIN - DEFAULT_MARGIN / 4), ((DEFAULT_MARGIN * 4) - DEFAULT_MARGIN / 2, DEFAULT_MARGIN - DEFAULT_MARGIN / 4), (((DEFAULT_MARGIN * 4) - DEFAULT_MARGIN / 2) + 5, (DEFAULT_MARGIN - DEFAULT_MARGIN / 4) / 2), ((DEFAULT_MARGIN * 4) - DEFAULT_MARGIN / 2, 0)) turtle.addshape('bateauquatre', bateauquatre) self.bateau4.shape('bateauquatre') self.bateau4.fillcolor('black') self.bateau4.penup() self.bateau4.createBateau(4, self.bateau4.getcoords(self.bateau4.xcor(), self.bateau4.ycor()), "Croiseur") self.listeBateauJoueur1.append(self.bateau4.bateau) self.bateau4.ondrag(self.bateau4.move) self.bateau4.onrelease(self.bateau4.changeOrientation, 3) self.bateau5 = MyTurtles() self.bateau5.penup() self.bateau5.speed(SPEED) self.bateau5.setx(300) self.bateau5.sety(0) bateaucinq = ((0, 0), ((0 - 5), (DEFAULT_MARGIN - DEFAULT_MARGIN / 4) / 2), (0, DEFAULT_MARGIN - DEFAULT_MARGIN / 4), ((DEFAULT_MARGIN * 5) - DEFAULT_MARGIN / 2, DEFAULT_MARGIN - DEFAULT_MARGIN / 4), (((DEFAULT_MARGIN * 5) - DEFAULT_MARGIN / 2) + 5, (DEFAULT_MARGIN - DEFAULT_MARGIN / 4) / 2), ((DEFAULT_MARGIN * 5) - DEFAULT_MARGIN / 2, 0)) turtle.addshape('bateaucinq', bateaucinq) self.bateau5.shape('bateaucinq') self.bateau5.fillcolor('gray') self.bateau5.penup() self.bateau5.createBateau(5, self.bateau5.getcoords(self.bateau5.xcor(), self.bateau5.ycor()), "Porte-Avion") self.listeBateauJoueur1.append(self.bateau5.bateau) self.bateau5.ondrag(self.bateau5.move) self.bateau5.onrelease(self.bateau5.changeOrientation, 3)
#Setting up the window and background window = turtle.Screen() window.bgpic("backgroundA.gif") os.system("afplay music.mp3&") #The music continues even when you exit the game #window.bgcolor("lightblue") turtle.setup(1000,1000) window.tracer(4) score = 0 window.title("Sweet Albert: Help him get candy! By Reena Sarkar and Amanda Chen") #Naming all of our turtles (characters and candies) mom = turtle.Turtle() mom.ht() mom.penup() turtle.addshape("pal.gif") mom.shape("pal.gif") dad = turtle.Turtle() dad.ht() dad.penup() turtle.addshape("dad.gif") dad.shape("dad.gif") sis = turtle.Turtle() sis.ht() sis.penup() turtle.addshape("sis.gif") sis.shape("sis.gif") bro = turtle.Turtle()
def gamestart(x, y): start_button.clear() start_button.hideturtle() labels.clear() enemy_number_text.clear() left_arrow.hideturtle() right_arrow.hideturtle() difficulty_text.clear() left_arrow_2.hideturtle() right_arrow_2.hideturtle() turtle.bgpic("ust2.gif") # Use the global variables here because we will change them inside this # function global player, laser, score, score_label, score_display # Score display initialization score_label.up() score_label.goto(-260, 275) score_label.color("Red") score_label.write("Score:", font=("System", 12, "bold"), align = "center") # Value display score_display.up() score_display.goto(-220, 275) score_display.color("Red") score_display.write(str(score), font=("System", 12, "bold"), align = "center") ### Player turtle ### # Add the spaceship picture turtle.addshape("redbird.gif") # Create the player turtle and move it to the initial position player = turtle.Turtle() player.shape("redbird.gif") player.up() player.goto(player_init_x, player_init_y) # Map player movement handlers to key press events turtle.onkeypress(playermoveleft, "Left") turtle.onkeypress(playermoveright, "Right") turtle.listen() ### Enemy turtles ### # Add the enemy picture turtle.addshape("closedbook.gif") turtle.addshape("openbook.gif") for i in range(enemy_number): # Create the turtle for the enemy enemy = turtle.Turtle() enemy.shape("closedbook.gif") enemy.up() # Move to a proper position counting from the top left corner enemy.goto(enemy_init_x + enemy_size * (i % 6), enemy_init_y - enemy_size * (i // 6)) # Add the enemy to the end of the enemies list enemies.append(enemy) turtle.onkeypress(stopkeypressed, 's') ### Laser turtle ### turtle.addshape("pen.gif") # Create the laser turtle laser = turtle.Turtle() laser.up() laser.shape("pen.gif") # Hide the laser turtle laser.hideturtle() turtle.onkeypress(shoot, "space") turtle.update() # Start the game by running updatescreen() turtle.ontimer(updatescreen, update_interval)
tracer(0) screen = Screen() canvas = getcanvas() # the canvas is the area that the turtle is moving (the white background) SCREEN_WIDTH = canvas.winfo_width() / 2 # here we get canvas(screen) width SCREEN_HEIGHT = canvas.winfo_height() / 2 # here we get the canvas(screen) height brick_width = 4 brick_height = 2 doritos = "Images/doritos.gif" mountain_dew = "Images/mountain_dew.gif" platform_image = "Images/mountain_dew_platform.gif" turtle.addshape(doritos) turtle.addshape(mountain_dew) turtle.addshape(platform_image) ht() setup(width, height) class Brick(Turtle): def __init__(self, x, y, width, height, shape, hp=1, is_platform=False): Turtle.__init__(self) self.is_platform = is_platform self.hp = hp self.shape(shape) self.showturtle()