Exemplo n.º 1
1
def top_layer():
    turtle.clearscreen()
    screen_setup()
    stations()
    sp = turtle.Turtle()
    sp.color('white')
    sp.penup()
    
    global top_pos
    sp.setpos(top_pos)
    sp.showturtle()
    sp.speed(1)
        
    def sta1():
        turn_and_go(sp, 'sta1')
    def sta2():
        turn_and_go(sp, 'sta2')
    def sta3():
        turn_and_go(sp, 'sta3')
        
    def zoom1():
        global top_pos
        top_pos = sp.pos()
        global middle_sta1_pos
        middle_sta1_pos = 250,-150
        if sp.pos() == (200,75):
            middle_layer_sta1()
        else:
            zoom()
    turtle.onkey(sta1, 'a')
    turtle.onkey(sta2, 'b')
    turtle.onkey(sta3, 'c')
    turtle.onkey(zoom1, '=')
    turtle.listen()
Exemplo n.º 2
0
def docking_layer():
    turtle.clearscreen()
    screen_setup()
    docking_port1()
    sp3 = turtle.Turtle()
    sp3.color('white')
    sp3.penup()
    sp3.speed(0)
    sp3.setpos(300, 0)
    sp3.seth(180)
    sp3.showturtle()
    speed = (10)
    def turnleft():
        sp3.left(30)
    def turnright():
        sp3.right(30)
    def forward():
        sp3.forward(speed)
    def backward():
        sp3.backward(speed)
        
    turtle.onkey(forward, 'Up')
    turtle.onkey(turnleft, 'Left')
    turtle.onkey(turnright, 'Right')
    turtle.onkey(backward, 'Down')
    turtle.onkey(middle_layer_sta1, '-')
    turtle.listen()
Exemplo n.º 3
0
def zoom():
    time.sleep(0.5)
    turtle.clearscreen()
    screen_setup()
    sp2 = turtle.Turtle()
    sp2.color('white')
    sp2.penup()
    sp2.speed(0)
    sp2.setpos(250, -150)
    sp2.seth(90)
    sp2.showturtle()
    speed = (10)
    b = 2
    def turnleft():
        sp2.left(30)
    def turnright():
        sp2.right(30)
    def forward():
        sp2.forward(speed)
    def backward():
        sp2.backward(speed)    
    
            
    turtle.onkey(forward, 'Up')
    turtle.onkey(turnleft, 'Left')
    turtle.onkey(turnright, 'Right')
    turtle.onkey(backward, 'Down')
    turtle.onkey(top_layer, '-')
    turtle.listen()
Exemplo n.º 4
0
    def __init__(self):
        super(LaserCannon, self).__init__()

        # Register events.  Note the function we register for 'q' is
        # a turtle function.
        turtle.onscreenclick(self.aim,1)
        turtle.onkey(self.shoot,"s")
        turtle.onkey(seeYaLater,'q')
Exemplo n.º 5
0
def top_layer():
    turtle.clearscreen()
    screen_setup()
    stations()
    sp = turtle.Turtle()
    sp.color('white')
    sp.penup()
    sp.setpos(200, 75)
    sp.showturtle()
    sp.speed(1)      
    def sta1():
        sp.goto(200, 75)
    def sta2():
        sp.goto(-300, 45)
    def sta3():
        sp.goto(-100,-200)
    def zoom1():
        if sp.pos() == (200,75):
            middle_layer_sta1()
        else:
            zoom()
    turtle.onkey(sta1, 'a')
    turtle.onkey(sta2, 'b')
    turtle.onkey(sta3, 'c')
    turtle.onkey(zoom1, '=')
    turtle.listen()
Exemplo n.º 6
0
	def hold(self):
		""" holds the screen open until the user clicks or types 'q' """
	
		# have the turtle listen for events
		turtle.listen()

		# hide the turtle and update the screen
		turtle.ht()
		turtle.update()

		# have the turtle listen for 'q'
		turtle.onkey( turtle.bye, 'q' )
		# have the turtle listen for a click
		turtle.onscreenclick( lambda x,y: turtle.bye() )

		# start the main loop until an event happens, then exit
		turtle.mainloop()
		exit()
Exemplo n.º 7
0
def start(x,y):
    turtle.onscreenclick(None)

    level_1()

    tfood = turtle.Turtle()
    tfood.hideturtle()
    tfood.pu()
    tfood.speed(0)
    tfood.shape("square")
    tfood.color("red")

    tscore = turtle.Turtle()
    tscore.hideturtle()
    tscore.pu()
    tscore.speed(0)
    tscore.goto(100,-250)
    tscore.write("Score:" + str(a[0]), align="center",font=(10))
    
    while x > -210 and x < 210 and y > -210 and y <210:
        if fcoord[2] == 0:
            food(tfood)
            fcoord[2] = 1
        turtle.onkey(u,"Up")
        turtle.onkey(l,"Left")
        turtle.onkey(r,"Right")
        turtle.onkey(d,"Down")
        turtle.listen()
        move()
        x = turtle.xcor()
        y = turtle.ycor()        
        if x > fcoord[0]*20-5 and x < fcoord[0]*20+5 and y > fcoord[1]*20-5 and y < fcoord[1]*20+5:
            fcoord[2] = 0
            tfood.clear()
            a[0] += 1
            tscore.clear()
            tscore.write("Score:" + str(a[0]), align="center",font=(10))
        
        if len(pos) > 1:
            for i in range(1,len(pos)):
                if x < pos[i][0]+5 and x > pos[i][0]-5 and y < pos[i][1]+5 and y > pos[i][1]-5:
                        tscore.clear()
                        tfood.clear()
                        gameover()
    tscore.clear()
    tfood.clear()
    gameover()
Exemplo n.º 8
0
Arquivo: spiro.py Projeto: diopib/pp
def main():
    # use sys.argv if needed
    print('generating spirograph...')
    # create parser
    descStr = """This program draws spirographs using the Turtle module. 
    When run with no arguments, this program draws random spirographs.
    
    Terminology:

    R: radius of outer circle.
    r: radius of inner circle.
    l: ratio of hole distance to r.
    """
    parser = argparse.ArgumentParser(description=descStr)
  
    # add expected arguments
    parser.add_argument('--sparams', nargs=3, dest='sparams', required=False, 
                        help="The three arguments in sparams: R, r, l.")
                        

    # parse args
    args = parser.parse_args()

    # set to 80% screen width
    turtle.setup(width=0.8)

    # set cursor shape
    turtle.shape('turtle')

    # set title
    turtle.title("Spirographs!")
    # add key handler for saving images
    turtle.onkey(saveDrawing, "s")
    # start listening 
    turtle.listen()

    # hide main turtle cursor
    turtle.hideturtle()

    # checks args and draw
    if args.sparams:
        params = [float(x) for x in args.sparams]
        # draw spirograph with given parameters
        # black by default
        col = (0.0, 0.0, 0.0)
        spiro = Spiro(0, 0, col, *params)
        spiro.draw()
    else:
        # create animator object
        spiroAnim = SpiroAnimator(4)
        # add key handler to toggle turtle cursor
        turtle.onkey(spiroAnim.toggleTurtles, "t")
        # add key handler to restart animation
        turtle.onkey(spiroAnim.restart, "space")

    # start turtle main loop
    turtle.mainloop()
def tegn_romskip():
    turtle.penup()
    turtle.shapesize(4)
    turtle.setpos(200, 400)
    turtle.setheading(90)
    turtle.color('blue')

    turtle.onkey(snu_hoyre, 'Right')
    turtle.onkey(snu_venstre, 'Left')
    turtle.onkey(bruk_motor, 'Up')
    turtle.listen()
Exemplo n.º 10
0
 def set_listeners(self):
     turtle.onscreenclick(self.clickcb, 1)
     # In OSX, ctrl-click doesn't give a button-3 click. Instead,
     # trackpad users have to enable secondary click in system
     # preferences. Then, right-clicking on trackpad generates a
     # button-2 click. I don't know what one-button mouse users can
     # do?
     turtle.onscreenclick(self.rightclickcb, 2)
     # On Linux, right-click generates a button-3 click.
     turtle.onscreenclick(self.rightclickcb, 3)
     turtle.onkey(self.spacecb, "space")
     turtle.onkey(self.savecb, "s")
     turtle.onkey(self.redisplaycb, "r")
     turtle.listen()
Exemplo n.º 11
0
def main():
    descStr = "This draws spirographs with turtle graphics, if no arguments are given, random spirographs will be drawn."
    parser = argparse.ArgumentParser(description=descStr)
    #add expected args
    parser.add_argument('--sparams', nargs=3, dest='sparams', required=False,
        help="The three arguments in sparams: R, r, l.")

    #parse args
    args = parser.parse_args()

    #set width of window to 80% of screen width
    turtle.setup(width=0.8)
    #set cursor shape to turtle
    turtle.shape('turtle')
    #set title to Spirographs!
    turtle.title("Spirographs!")
    #add keyhandler to save drawings
    turtle.onkey(saveDrawing, 's')
    #start listening
    turtle.listen()

    #hide main turtle cursor
    turtle.hideturtle()


    #check for any arguments sent to --sparams and draw spirograph
    if args.sparams:
        params = [float(x) for x in args.sparams]
        #draw spiro with given params
        col = (0.0, 0.0, 0.0)
        spiro = Spiro(0, 0, col, *params)
        spiro.draw()
    else:
        #create animator objects
        span = SpiroAnimator(6)
        #add key handler to toggle cursor
        turtle.onkey(span.toggleTurtles, "t")
        #add keyhandler to restart
        turtle.onkey(span.restart, "space")

    #start main loop
    turtle.mainloop()
import turtle

turtle.penup()
turtle.ht()

def up():
    print("You pressed Up!")

def down():
    print("You pressed Down!")

def left():
    print("You pressed Left!")

def right():
    print("You pressed Right!")
    
turtle.onkey(up, 'Up')
turtle.onkey(down, 'Down')
turtle.onkey(left, 'Left')
turtle.onkey(right, 'Right')

def repeat():
    turtle.ontimer(repeat, 500)

turtle.listen() # Remember to put this after your listeners!
    list= [pos[0], pos[1] - 100]
    tunnel.gi_beskjed(playerself, "goto",list)

def cmdright():
    pos = Ninjaturtles[playerself].position()
    list = [pos[0] + 100, pos[1]]
    tunnel.gi_beskjed(playerself, "goto",list)

def cmdleft():
    pos = Ninjaturtles[playerself].position()
    list= [pos[0] - 100, pos[1]]
    tunnel.gi_beskjed(playerself, "goto",list)



turtle.onkey(cmdup, "Up")
turtle.onkey(cmdup, "w")

turtle.onkey(cmddown, "Down")
turtle.onkey(cmddown, "s")

turtle.onkey(cmdright, "Right")
turtle.onkey(cmdright, "d")

turtle.onkey(cmdleft, "Left")
turtle.onkey(cmdleft,  "a")

if __name__ == '__main__':
    turtle.onkey(turtle.reset, "space")
    tunnel.init(tupdate)
Exemplo n.º 14
0
        turtle.goto(x, y + 100)
    if turtle.direction == "Right":
        turtle.goto(x + 100, y)
    if turtle.direction == "Down":
        turtle.goto(x, y - 100)
    if turtle.direction == "Left":
        turtle.goto(x - 100, y)


def up():
    turtle.direction = "Up"
    on_move()
    print("you pressed the up key ")


turtle.onkey(up, "Up")
turtle.listen()


def down():
    turtle.direction = "Down"
    on_move()
    print("you pressed the down key ")


turtle.onkey(down, "Down")
turtle.listen()


def left():
    turtle.direction = "Left"
Exemplo n.º 15
0
            Ally("ally.gif", "blue", allybase.xcor(), allybase.ycor()))

    particles = []
    colors = ["red", "yellow", "orange"]
    for p in range(20):
        particles.append(
            Particle("circle", random.choice(colors), -1000, -1000))

    bullets = []
    for b in range(2):
        bullets.append(Bullet("triangle", "yellow", 0.0, 0.0))

    game.set_state("playing")

#Keyboard Bindings
turtle.onkey(player.turn_left, "Left")
turtle.onkey(player.turn_right, "Right")
turtle.onkey(player.accelerate, "Up")
turtle.onkey(player.hyperspace, "Down")
turtle.onkey(game.fire_weapon, "space")
turtle.listen()

while True:
    turtle.update()
    if game.state == "restart":
        game.lives = 3
        game.score = 0
        player.speed = 0
        player.goto(0, 0)
        player.setheading(0)
        player.dx = 0
Exemplo n.º 16
0
def main():
    display_help_window()

    scr = turtle.Screen()
    turtle.mode('standard')
    xsize, ysize = scr.screensize()
    turtle.setworldcoordinates(0, 0, xsize, ysize)

    turtle.hideturtle()
    turtle.speed('fastest')
    turtle.tracer(0, 0)
    turtle.penup()

    board = LifeBoard(xsize // CELL_SIZE, 1 + ysize // CELL_SIZE)

    # Set up mouse bindings
    def toggle(x, y):
        cell_x = x // CELL_SIZE
        cell_y = y // CELL_SIZE
        if board.is_legal(cell_x, cell_y):
            board.toggle(cell_x, cell_y)
            board.display()

    turtle.onscreenclick(turtle.listen)
    turtle.onscreenclick(toggle)

    board.makeRandom()
    board.display()

    # Set up key bindings
    def erase():
        board.erase()
        board.display()
    turtle.onkey(erase, 'e')

    def makeRandom():
        board.makeRandom()
        board.display()
    turtle.onkey(makeRandom, 'r')

    turtle.onkey(sys.exit, 'q')

    # Set up keys for performing generation steps, either one-at-a-time or not.
    continuous = False
    def step_once():
        nonlocal continuous
        continuous = False
        perform_step()

    def step_continuous():
        nonlocal continuous
        continuous = True
        perform_step()

    def perform_step():
        board.step()
        board.display()
        # In continuous mode, we set a timer to display another generation
        # after 25 millisenconds.
        if continuous:
            turtle.ontimer(perform_step, 25)

    turtle.onkey(step_once, 's')
    turtle.onkey(step_continuous, 'c')

    # Enter the Tk main loop
    turtle.listen()
    turtle.mainloop()
Exemplo n.º 17
0
def main():
    import turtle
    import math
    import random
    import os
    score = 0
    import winsound
    # bg screen
    b = turtle.Screen()
    b.bgcolor("black")
    b.bgpic("giphy.gif")
    # border
    br = turtle.Turtle()
    br.penup()
    br.goto(-300, 300)
    br.pendown()
    br.width(4)
    br.speed(10000)
    br.color("blue")
    for i in range(4):
        br.fd(600)
        br.rt(90)
    br.hideturtle()
    # create player
    plr = turtle.Turtle()
    plr.shapesize(2, 2, 4)
    plr.shape("turtle")
    plr.color("green")
    plr.penup()
    plr.speed(0)
    speed = 1
    # food
    food = turtle.Turtle()
    food.shape("circle")
    food.color("red")
    food.penup()
    food.setposition(random.randint(-295, 295), random.randint(-295, 295))

    # keystrokes
    def turnleft():
        plr.lt(90)

    def turnryt():
        plr.rt(90)

    def speedup():
        global speed
        speed = speed + 1

    def slowdown():
        global speed
        speed = speed - 1

    def restart():
        turtle.Screen().clear()
        main()

    def iscollision(t1, t2):
        d = math.sqrt(
            math.pow(t1.xcor() - t2.xcor(), 2) +
            math.pow(t1.ycor() - t2.ycor(), 2))
        if d < 20:
            return True
        else:
            return False

    #game over
    def gameover():
        b.bgpic("blog-game-over.gif")
        plr.color("red")
        p = turtle.Turtle()
        p.color("blue")
        p.penup()
        p.hideturtle()
        p.setposition(-100, -100)
        g = "FINAL SCORE: %s" % score
        p.write(g, False, align="left", font=("Arial", 24, "normal"))
        f = open("hs.txt", 'r')
        t = f.read()
        f.close()
        if score > int(t):
            open("hs.txt", 'w').close()
            l = open("hs.txt", 'w')
            l.write("%s" % score)
            l.close()
            p.setposition(-200, 70)
            p.color("yellow")
            z = "CONGRAGULATIONS!!!!!\n NEW HIGH SCORE: %s" % score
            p.write(z, False, align="left", font=("Arial", 28, "normal"))

        p.setposition(-150, -130)
        e = "press space to play again"
        p.color("purple")
        p.write(e, False, align="left", font=("Arial", 20, "normal"))
        p.setposition(-70, -300)
        p.color("red")
        p.write("click to exit",
                False,
                align="left",
                font=("Arial", 14, "normal"))
        f = turtle.Screen()
        f.exitonclick()

    turtle.listen()
    turtle.onkey(turnleft, "Left")
    turtle.onkey(turnryt, "Right")
    turtle.onkey(speedup, "Up")
    turtle.onkey(restart, "space")
    while True:
        plr.fd(speed)
        # boundry
        if plr.xcor() > 280 or plr.xcor() < -280:
            gameover()
            winsound.PlaySound("smash.wav", winsound.SND_ASYNC)
            break

        if plr.ycor() > 280 or plr.ycor() < -280:
            gameover()
            winsound.PlaySound("smash.wav", winsound.SND_ASYNC)
            break

        if iscollision(plr, food):
            food.setposition(random.randint(-265, 265),
                             random.randint(-265, 265))
            score = score + 1
            br.undo()
            br.penup()
            br.hideturtle()
            br.setposition(-290, 300)
            s = "SCORE: %s" % score
            br.write(s, False, align="left", font=("Arial", 14, "normal"))
            winsound.PlaySound("jump.wav", winsound.SND_ASYNC)
            if score == 50:
                spped = speed + 1
            elif score == 40:
                b.bgpic("p1.gif")
                winsound.PlaySound("powerup.wav", winsound.SND_ASYNC)
                speed = speed + 0.50
            elif score == 30:
                b.bgpic("p2.gif")
                winsound.PlaySound("powerup.wav", winsound.SND_ASYNC)
                speed = speed + 0.70
            elif score == 20:
                b.bgpic("p3.gif")
                winsound.PlaySound("powerup.wav", winsound.SND_ASYNC)
                speed = speed + 0.40
            elif score == 10:
                b.bgpic("p4.gif")
                winsound.PlaySound("powerup.wav", winsound.SND_ASYNC)
                speed = speed + 0.30
Exemplo n.º 18
0
        bullet.showturtle()


def isCollision(t1, t2):
    distance = math.sqrt(
        math.pow(t1.xcor() - t2.xcor(), 2) +
        math.pow(t1.ycor() - t2.ycor(), 2))
    if distance < 15:
        return True
    else:
        return False


#keyboard binding
turtle.listen()
turtle.onkey(fireBullet, "space")
turtle.onkey(moveLeft, "Left")
turtle.onkey(moveRight, "Right")

#main loop
while True:
    for enemy in enemies:
        #moving the enemy
        x = enemy.xcor()
        x = x + enemyspeed
        enemy.setx(x)
        #move the enemy down and change direction
        if enemy.xcor() > 280:
            y = enemy.ycor()
            y = y - 30
            enemyspeed *= -1
Exemplo n.º 19
0
player2 = turtle.Turtle()

player2.color('blue')
player2.shape('turtle')

player2.penup()
player2.goto(-160, 0)
player2.pendown()

# button functions
def k1():
    player1.forward(10)
    if player1.xcor() > 100:
        print("player 1 wins")
        window.bye()

def k2():
    player2.forward(10)
    if player2.xcor() > 100:
        print("player 2 wins")
        window.bye()
def k3():
    window.bye()

#########     
turtle.listen()
turtle.onkey(k1, "Left")
turtle.onkey(k2, "Right")
turtle.onkey(k3, 'q')
    
Exemplo n.º 20
0
game = Game()

#Draw the game border
game.draw_border()

#Show the game status
game.show_status()

#Create my sprites
player = Player("triangle", "white", 0, 0)
enemy = Enemy("circle", "red", -100, 0)
missile = Missile("triangle", "yellow", 0, 0)
ally = Ally("square", "blue", 0, 0)

#Keyboard bindings
turtle.onkey(player.turn_left, "Left")
turtle.onkey(player.turn_right, "Right")
turtle.onkey(player.accelerate, "Up")
turtle.onkey(player.decelerate, "Down")
turtle.onkey(missile.fire, "space")
turtle.listen()

#Main game loop
while True:
    player.move()
    enemy.move()
    missile.move()
    ally.move()

    #Check for a collision with the player
    if player.is_collision(enemy):
Exemplo n.º 21
0
# Display Game status
game.show_status()

# (SAM)
# Create my sprites
player = Player("ship.gif", "white", 0, -300)
missile = Missile("pew.gif", "yellow", 0, 0) #(EMILY)

# (EMILY)
enemies =[]
for i in range(15):
    enemies.append(Enemy("meteor.gif", "red", 0, random.randint(200,300)))

# (SAM)
# Keyboard bindings
turtle.onkey(player.move_left, "Left")
turtle.onkey(player.move_right, "Right")
turtle.onkey(player.accelerate, "Up")
turtle.onkey(player.decelerate, "Down")
turtle.onkey(missile.fire, "space") #(EMILY)
turtle.listen()

#(SAM)
# Main game loop
while True:
    turtle.update() #(SAM)
    time.sleep(0.05) #(SAM)
    player.move() #(SAM)
    missile.move() #(EMILY)

    for enemy in enemies: #(EMILY)
Exemplo n.º 22
0
        bullet.showturtle()


def isCollision(t1, t2):
    distance = math.sqrt(
        math.pow(t1.xcor() - t2.xcor(), 2) +
        math.pow(t1.ycor() - t2.ycor(), 2))
    if distance < 30:
        return True
    else:
        return False


#Create keyboard binding
turtle.listen()
turtle.onkey(move_left, 'Left')
turtle.onkey(move_right, 'Right')
turtle.onkey(fire_bullet, 'space')

#Main game loop
while True:

    for enemy in enemies:
        #Move the enemy
        x = enemy.xcor()
        x += enemyspeed
        enemy.setx(x)

        #Move the enemy back and down
        if enemy.xcor() > 275:
            #Move all enemies down
Exemplo n.º 23
0
    def move(self):
        self.forward(self.speed)
    def turn_left(self):
        self.left(30)
    def turn_right(self):
        self.left(30)
    def accelerate(self):
        self.speed += 1
    def decelerate(self):
        self.speed -=1
# Khởi tạo đối tượng của lớp siêu anh hùng
player = SuperHero()
# Thiết lập điều khiển nhân vật bằng bàn phím
turtle.listen()
turtle.onkey(player.turn_left(), "Left")
turtle.onkey(player.turn_right(), "Right")
turtle.onkey(player.accelerate(), "Up")
turtle.onkey(player.decelerate(), "Down")
#Class border
class BienVien(turtle.Turtle):
    def __init__(self):
        turtle.Turtle.__init__(self)
        self.penup()
        self.speed(0)
        self.color("white") #thuộc tính màu sắc
        self.pensize(5) #màu biên
    def draw_border(self):
        self.penup()
        self.goto(-300, -300)
        self.pendown()
Exemplo n.º 24
0
    turtle.forward(100)


def left():
    turtle.setheading(180)
    turtle.forward(100)


def right():
    turtle.setheading(0)
    turtle.forward(100)


def leftclick(x, y):
    turtle.color(random.choice(colors))


def rightclick(x, y):
    turtle.stamp()


turtle.listen()

turtle.onkey(up, 'Up')
turtle.onkey(down, 'Down')
turtle.onkey(left, 'Left')
turtle.onkey(right, 'Right')
turtle.onscreenclick(leftclick, 1)
turtle.onscreenclick(rightclick, 3)

turtle.mainloop()
def place5():
    global cur_player
    if (cur_player == 1):
        play1(5)
    elif (cur_player == 2):
        play2(5)

def place6():
    global cur_player
    if (cur_player == 1):
        play1(6)
    elif (cur_player == 2):
        play2(6)

#key listeners
turtle.onkey(place0, '1')
turtle.onkey(place1, '2')
turtle.onkey(place2, '3')
turtle.onkey(place3, '4')
turtle.onkey(place4, '5')
turtle.onkey(place5, '6')
turtle.onkey(place6, '7')

        
#drawing the board        
draw_board(START_X , START_Y)

turtle.listen()
turtle.mainloop()
Exemplo n.º 26
0
game = Game()

#Draw the game border
game.draw_border()

#Show the level and score
game.show_status()

#Create player and enemy objects
player = Player("triangle", "white", 0.0, 0.0)
#enemy = Enemy("circle", "red", 100.0, 0.0)
bullet = Bullet("triangle", "yellow", 0.0, 0.0)
#ally = Ally("square", "blue", 100, 100)

#Keyboard Bindings
turtle.onkey(player.turn_left, "Left")
turtle.onkey(player.turn_right, "Right")
turtle.onkey(player.accelerate, "Up")
turtle.onkey(player.hyperspace, "Down")
turtle.onkey(bullet.fire, "space")
turtle.listen()

#Set up the game
#Create lists for sprites
#Add Enemies
if game.state == "splash":
    enemies = []

    for e in range(6):
        x = random.randint(-200, 200)
        y = random.randint(-200, 200)
Exemplo n.º 27
0
def visLife(foerste,naeste,levende,klik):
    cs = 10 # celleside, global konstant
    tt.Screen()
    tt.speed('fastest')
    tt.hideturtle()
    tt.penup()
    kodefarve = ['white','blue','red','green','black']
    # 0 = død, lige klikantal; 1 = levende, lige klikantal
    # 2 = levende, ulige klikantal; 3 = død, ulige klikantal; 4 = gitter

    # Lærredet bruger koordinater (x,y) og spillet koordinater (i,j)
    # Globale (x0,y0) er placering af tænkt celle (0,0)
    def toXY(i,j):
        return i*cs+x0,j*cs+y0
    def fromXY(x,y):
        return int(floor(float(x-x0)/cs)),int(floor(float(y-y0)/cs))
    
    def tegnGitter(i0,i1,j0,j1):
        """Gitteret har søjler fra i0 til og med i1 og rækker fra
j0 til og med j1.  Først blankstilles lærredet"""
        xmin,ymin = toXY(i0,j0)
        xlen,ylen = (i1-i0+2)*cs,(j1-j0+2)*cs
        tt.clear()
        tt.penup()
        tt.color(kodefarve[4])
        # vandrette linjer
        x,y = xmin-cs/2,ymin
        tt.setheading(0) # øst
        for j in range(j0,j1+2):
            tt.goto(x,y)
            tt.pendown()
            tt.forward(xlen)
            tt.penup()
            y += cs
        # lodrette linjer
        x,y = xmin,ymin-cs/2
        tt.setheading(90) # nord
        for i in range(i0,i1+2):
            tt.goto(x,y)
            tt.pendown()
            tt.forward(ylen)
            tt.penup()
            x += cs
            
    def tegnCelle(i,j,farve):
        x,y = toXY(i,j)
        tt.goto(x+1,y+1)
        tt.setheading(0) # øst
        tt.color(farve)
        tt.fill(True)
        tt.pendown()
        for k in range(4):
            tt.forward(cs-2)
            tt.left(90)
        tt.fill(False)
        tt.penup()

    def tegnGen(i0,i1,j0,j1):
        """Gitteret har søjler fra i0 til og med i1 og rækker fra
j0 til og med j1"""
        for i in range(i0,i1+1):
            for j in range(j0,j1+1):
                skyggegen[(i,j)] = 0 # død
                if levende(i,j):
                    tegnCelle(i,j,kodefarve[1])
                    skyggegen[(i,j)] = 1 # levende

    def skift(x,y):
        """Knyttes til museklik"""
        i,j = fromXY(x,y)
        if (i,j) in skyggegen:
            farvekode = 3 - skyggegen[(i,j)] # vend farve
            skyggegen[(i,j)] = farvekode
            tegnCelle(i,j,kodefarve[farvekode])
            klik(i,j)

    def tast():
        """Knyttes til tast af mellemrum"""
        i0,i1,j0,j1 = naeste()
        skyggegen = {}
        tegnGitter(i0,i1,j0,j1)
        tegnGen(i0,i1,j0,j1)

    def stop():
        """Knyttes til tast af Escape"""
        tt.bye()

    # første generation
    i0,i1,j0,j1 = foerste()
    # beregn basis, dvs. placering af tænkt celle (0,0)
    x0,y0 = -(i0+i1+1)*cs/2,-(j0+j1+1)*cs/2
    skyggegen = {}
    tegnGitter(i0,i1,j0,j1)
    tegnGen(i0,i1,j0,j1)

    # begivendhedsstyring:
    tt.onscreenclick(skift)
    tt.onkey(tast,'space')
    tt.onkey(stop,'Escape')
    tt.listen()
    tt.mainloop()
    t.seth(0)
    t.forward(20)
    
def left():
    t.seth(180)
    t.forward(20)
    
def up():
    t.seth(90)
    t.forward(20)
    
def down():
    t.seth(270)
    t.forward(20)
    
def exit_to_program():
    t.bye()
        
# Linking each function with a keyboard key
t.onkey(up, "w")
t.onkey(left, "a")
t.onkey(right, "d")
t.onkey(down, "s")
t.onkey(exit_to_program, "e")

# turtle listens the commands
t.listen()

# Close execute
t.done()
t.bye()
    def middle_layer_sta1():
        time.sleep(0.5)
        turtle.clearscreen()
        screen_setup()
        station_1()
        sp2 = turtle.Turtle()
        sp2.color('white')
        sp2.penup()
        sp2.speed(0)
        global middle_sta1_pos
        sp2.setpos(middle_sta1_pos)
        sp2.seth(90)
        sp2.showturtle()
        speed = (10)
        b = 2
        def turnleft():
            sp2.left(30)
        def turnright():
            sp2.right(30)
        def forward():
            sp2.forward(speed)
        def backward():
            sp2.backward(speed)
        def zoom1():
            global middle_sta1_pos
            middle_sta1_pos = sp2.pos()
            if sp2.xcor() > -162 and sp2.xcor() < -98 and sp2.ycor() > -112 and sp2.ycor() < -64:
                docking_layer()            
                
        turtle.onkey(forward, 'Up')
        turtle.onkey(turnleft, 'Left')
        turtle.onkey(turnright, 'Right')
        turtle.onkey(backward, 'Down')
        turtle.onkey(top_layer, '-')
        turtle.onkey(zoom1,'=')
        turtle.listen()

        for i in range(1000):
            x = random.randrange(-250, 450)
            h = random.randrange(220, 340)
            ship = turtle.Turtle()
            ship.hideturtle()
            ship.color('gray')
            ship.penup()
            ship.speed(0)
            ship.setpos(x, 260)
            ship.showturtle()
            ship.speed(1)
            ship.seth(h)
            ship.forward(1000)
            if sp2.xcor() > -162 and sp2.xcor() < -98 and sp2.ycor() > -112 and sp2.ycor() < -64:
                break
Exemplo n.º 30
0
        cannon.showturtle()


def isCollision(t1, t2):
    distance = math.sqrt(
        math.pow(t1.xcor() - t2.xcor(), 2) +
        math.pow(t1.ycor() - t2.ycor(), 2))
    if distance < 25:
        return True
    else:
        return False


#create keyboard bindings
turtle.listen()
turtle.onkey(left, "Left")
turtle.onkey(right, "Right")
turtle.onkey(fire, "space")

print(enemieslist)
#game loop
while True:
    # move the enmeyprint(enemieslist)
    for enemy in enemieslist:
        enemy.setx(enemy.xcor() + enemyspeed)

        if enemy.xcor() > 280:
            for e in enemieslist:
                y = e.ycor()
                y -= 40
                e.sety(y)
Exemplo n.º 31
0
def colide(t1,t2):
        d = math.sqrt(math.pow(ugv1.xcor()-goal.xcor(),2) + math.pow(ugv1.ycor()-goal.ycor(),2))
        if d < 20:
                return True
        else:
                return False

def obstacle(t1,t2):
        d = math.sqrt(math.pow(ugv1.xcor()-green.xcor(),2) + math.pow(ugv1.ycor()-green.ycor(),2))
        if d < 30:
                ugv1.rt(30)
        
#Modo escucha de teclado
turtle.listen()
turtle.onkey(turnleft, "Left")
turtle.onkey(turnright, "Right")
turtle.onkey(speedup, "Up")
turtle.onkey(speeddown, "Down")
turtle.onkey(restart, "r")

#Inicio de movimiento
while speed>0:
        obstacle(ugv1,green)
        ugv1.forward(speed)
        
        #Mantener UGV dentro del ambiente
        if ugv1.xcor() > 300 or ugv1.xcor() < -300:
                ugv1.rt(180)

        if ugv1.ycor() > 300 or ugv1.ycor() < -300:
Exemplo n.º 32
0
        bullet.showturtle()


def isCollision(t1, t2):
    distance = math.sqrt(
        math.pow(t1.xcor() - t2.xcor(), 2) +
        math.pow(t1.ycor() - t2.ycor(), 2))
    if distance < 15:
        return True
    else:
        return False


# Keyboard Bindings
turtle.listen()
turtle.onkey(left, "Left")
turtle.onkey(right, "Right")
turtle.onkey(increase, "Up")
turtle.onkey(decrease, "Down")
turtle.onkey(fire_bullet, "space")

while True:
    wn.update()
    player.forward(speed)
    bullet.forward(bulletspeed)
    line1enemy1.fd(line1enemy1speed)
    line1enemy2.fd(line1enemy2speed)
    line1enemy3.fd(line1enemy3speed)
    line1enemy4.fd(line1enemy4speed)
    line1enemy5.fd(line1enemy5speed)
    line1enemy6.fd(line1enemy6speed)
Exemplo n.º 33
0
def middle_layer_sta1():
    time.sleep(0.5)
    turtle.clearscreen()
    screen_setup()
    station_1()
    sp2 = turtle.Turtle()
    sp2.color('white')
    sp2.penup()
    sp2.speed(0)
    sp2.setpos(250, -150)
    sp2.seth(90)
    sp2.showturtle()
    speed = (10)
    b = 2
    def turnleft():
        sp2.left(30)
    def turnright():
        sp2.right(30)
    def forward():
        sp2.forward(speed)
    def backward():
        sp2.backward(speed)
    def zoom1():
        if sp2.xcor() > -162 and sp2.xcor() < -98 and sp2.ycor() > -112 and sp2.ycor() < -64:
            docking_layer()
    
            
    turtle.onkey(forward, 'Up')
    turtle.onkey(turnleft, 'Left')
    turtle.onkey(turnright, 'Right')
    turtle.onkey(backward, 'Down')
    turtle.onkey(top_layer, '-')
    turtle.onkey(zoom1,'=')
    turtle.listen()
Exemplo n.º 34
0
            break


def move_up():
    if caterpillar.heading() == 0 or caterpillar.heading() == 180:
        caterpillar.setheading(90)


def move_down():
    if caterpillar.heading() == 0 or caterpillar.heading() == 180:
        caterpillar.setheading(270)


def move_left():
    if caterpillar.heading() == 90 or caterpillar.heading() == 270:
        caterpillar.setheading(180)


def move_right():
    if caterpillar.heading() == 90 or caterpillar.heading() == 270:
        caterpillar.setheading(0)


t.onkey(start_game, 'space')
t.onkey(move_up, 'Up')
t.onkey(move_right, 'Right')
t.onkey(move_down, 'Down')
t.onkey(move_left, 'Left')
t.listen()
t.mainloop()
Exemplo n.º 35
0
def up():
    tim.setheading(90)
    tim.forward(10)


def down():
    tim.setheading(270)
    tim.forward(10)


def left():
    tim.setheading(180)
    tim.forward(10)


def right():
    tim.setheading(0)
    tim.forward(10)


turtle.listen()

turtle.onkey(
    up,
    "Up")  # This will call the up function if the "Left" arrow key is pressed
turtle.onkey(down, "Down")
turtle.onkey(left, "Left")
turtle.onkey(right, "Right")

turtle.mainloop()  # This will make sure the program continues to run
Exemplo n.º 36
0

#COLLISION BULLET-ENEMY
def isCollision(t1, t2):
    distance = math.sqrt(
        math.pow(t1.xcor() - t2.xcor(), 2) +
        math.pow(t1.ycor() - t2.ycor(), 2))
    if distance < 25:
        return True
    else:
        return False


#CREATE KEYBOARD
turtle.listen()
turtle.onkey(move_left, "Left")
turtle.onkey(move_right, "Right")
turtle.onkey(move_up, "Up")
turtle.onkey(move_down, "Down")
turtle.onkey(fire_bullet, "space")

#MAIN GAME LOOP
while True:

    #CHECK FOR COLLISION BETWEEN PLAYER-ENEMY
    if isCollision(player, enemy):
        os.system("afplay Laugh.wav&")
        player.hideturtle()
        break
    # if isCollision(player, enemy):
    # 	os.system("afplay space_invaders.wav&")
Exemplo n.º 37
0
# functions to play with
def stamp():
  t1.stamp()
  t2.stamp()
def dot():
  t1.dot()
  t2.dot()
def testfun():
  x = t2.pen()
  t2.stamp()
  t2.pendown()
  t2.circle(100)
  t2.pen(x)

# global key event for turtle window
turtle.onkey(dot, "o")
turtle.onkey(stamp, "space")
w.onkey(testfun, "t")
w.onkey(w.bye, "x")

# extra key events for oturtles on window
t2._screen.onkey(t2.testfun,"h")

h.show(turtle._CFG)
print "use turtlekeys to move, v b m o space h t for Actions and x for close the Window"

# bind a callback on time
oldColor = None
def gruen(e):
  global oldColor
  print e
Exemplo n.º 38
0
            myEnemy.setposition(x, y)

        #Check the collision b/w Enemy and Player
        if isCollision(myPlayer, myEnemy):
            myBullet.hideturtle()  #Reset the Bullet
            myEnemy.hideturtle()  #Reset the Enemy
            myPlayer.hideturtle()  #Reset the Player
            print("---> GAME OVER <---")
            #turtle.title("GAME OVER")
            break

            #Bullet loop
        if (bulletState == 'FIRE'):
            y = myBullet.ycor()
            y += bulletSpeed
            myBullet.showturtle()
            myBullet.sety(y)
        if (myBullet.ycor() > 270):
            myBullet.hideturtle()
            bulletState = 'READY'

        #onkey functions inside while
        #they have to work in the middle of the enemy movement
        #onkey functions
        turtle.listen()
        turtle.onkey(moveLeft, "Left")
        turtle.onkey(moveRight, "Right")
        turtle.onkey(bulletFire, "space")

#delay = raw_input("Enter to FINISH")
Exemplo n.º 39
0
def turnleft():
    tim.left(30)


def turnright():
    tim.right(30)


def turnup():
    global speed
    speed += 1


turtle.listen()
turtle.onkey(turnleft, "Left")
turtle.onkey(turnright, "Right")
turtle.onkey(turnup, "Up")

score = 0

while (True):
    tim.forward(speed)

    #bounce
    if tim.xcor() > 240 or tim.xcor() < -240:
        tim.right(180)
    if tim.ycor() > 240 or tim.ycor() < -240:
        tim.left(180)

    #make hit
Exemplo n.º 40
0
        y = player.ycor() + 10
        bullet.setposition(x,y)
        bullet.showturtle()
        bullet_state = "fire"

#check multiple collision using 'pythagoras theoram'
def bulletEncounteredEnemy(t1,t2):
    distance = math.sqrt(math.pow(t1.xcor()-t2.xcor(),2) + math.pow(t1.ycor()-t2.ycor(),2))     # math.pow(a,b), a-base,b-power
    if distance<10:                                                                             # math.sqrt(c)
        return True
    else:
        return False
        
#keyboard binding, key's working
t.listen()                              # listen to keyboard action
t.onkey(move_left,"Left")               # when left key is pressed 'move_left' fn is called
t.onkey(move_right,"Right")             # when right key is pressed 'move_right' fn is called
t.onkey(bfire,"space")                  # when spacebar is pressed 'fire' fn is called

#game loop
while True:
    #enemy movement
    x = enemy.xcor()
    x += enemy_spd
    enemy.setx(x)
    
    #right -->
    if x>280:
        y = enemy.ycor()
        y -= 25                         # when enemy touches right boundry it'll get down by 25 pixels
        enemy.sety(y)
    global i
    step = 100 # Hvor langt turtle vil bevege seg

    # Om vi IKKE kolliderer med linjen
    if not turtlecollide.is_colliding(turtle.xcor()+step, 250):
        print("You may pass!")
        wasd.moveright()
    else:
        # Vi kolliderte med linjen
        print("Thou shall not pass!")

    # For å være litt artig, teller vi
    # antall ganger vi forsøker å gå over linjen.
    # Spillet tar slutt om vi forsøker mer enn 50
    # Ganger.
    i += 1
    if i > 50:
        print("game over")
        exit(0)

# wasd.py har bundet pil opp, ned, høyre og venstre
# men nå overskriver vi keybinden for
# høyre piltast.
# Vi skal nå sjekke at vi ikke kolliderer før vi evnt. beveger oss.
turtle.onkey(checkrightfaceplant, "Right")
turtle.onkey(checkrightfaceplant, "d")


# Listen kjøres
turtle.listen()
turtle.mainloop()
Exemplo n.º 42
0
enemy.shape("triangle")
enemy.penup()
enemy.speed()

#player ship movement
ship_spd = 15


def move_left():
    x = ship.xcor()  # set x coordinate of ship as value of x i.e 0
    x -= ship_spd  # set x = -15 every time we press left key
    if x < -280:  # boundary checking for left side
        x = -280
    ship.setx(x)  # set new x coordinate of ship


def move_right():
    x = ship.xcor()
    x += ship_spd
    if x > 280:  # boundary checking for right side
        x = 280
    ship.setx(x)


# keyboard binding, key's working
t.listen()  # listen to keyboard action
t.onkey(move_left, "Left")  # when left key is pressed 'move_left' fn is called
t.onkey(move_right,
        "Right")  # when right key is pressed 'move_right' fn is called

delay = input("press any key to end!")
Exemplo n.º 43
0
    heading -= 30
    t.setheading(heading)
    draw_text()
def smaller():
    global width
    width = t.width()-2
    t.width(width)
    draw_text()
def bigger():
    global width
    width = t.width()+2
    t.width(width)
    draw_text()
def longer():
    global length
    length=length+25
    draw_text()
def shorter():
    global length
    length=length-25
    draw_text()
turtle.onkey(up, "Up")
turtle.onkey(left, "Left")
turtle.onkey(right, "Right")
turtle.onkey(bigger, "b")
turtle.onkey(smaller, "s")
turtle.onkey(longer, ">")
turtle.onkey(shorter, "<")
draw_text()
turtle.listen()
Exemplo n.º 44
0
        bullet.showturtle()


def isCollision(t1, t2):
    distance = math.sqrt(
        math.pow(t1.xcor() - t2.xcor(), 2) +
        math.pow(t1.ycor() - t2.ycor(), 2))
    if distance < 15:
        return True
    else:
        return False


#Create Keyboard Bindings
turtle.listen()
turtle.onkey(move_left, "Left")
turtle.onkey(move_right, "Right")
turtle.onkey(fire_bullet, "space")

c = 0
#Main Game loop
while True:

    for enemy in enemies:
        #Move the enemy
        x = enemy.xcor()
        x = x + enemyspeed
        enemy.setx(x)

        #Move the enemy back and down
        if enemy.xcor() > 280:
Exemplo n.º 45
0
    speed+=1
def downSpeed():
    global speed
    speed-=1

#플레이어가 장애물을 먹었는가에 대한 함수 구현
def isEaten(t1,t2):
    d=math.sqrt(math.pow(t1.xcor()-t2.xcor(),2) + math.pow(t1.ycor()-t2.ycor(),2))
    if d <10:
        return True
    else:
        return False
    
#키보드 입력 세팅
turtle.listen()
turtle.onkey(pressLeft,"Left")
turtle.onkey(pressRight,"Right")
turtle.onkey(upSpeed, "Up")
turtle.onkey(downSpeed, "Down")
turtle.onkey(wn.bye, "q")

#게임 진행
while True:
    player.forward(speed)
    
    #player가 벽에 부딪히면 뒤를 돌아보게 설정
    if player.xcor() > 290 or player.xcor() < -290:
        player.right(180)
    if player.ycor() > 290 or player.ycor() < -290:
        player.right(180)
    
Exemplo n.º 46
0
# alternate : turtle, twist and octo size
contexts = ((caroline, 15, 100, ),
            (chloe, 60, 30 ),
            (bob, 40, 60 ),
           )
# initialize alternating contexts
cycle = len(contexts)
counter = -1

# the callback triggered when a user clicks in x,y
def clicked(x, y):
    global counter
    counter += 1
    # alternate between the various contexts
    (turtle, twist, size) = contexts[counter % cycle]
    turtle.penup()
    turtle.goto(x, y)
    turtle.pendown()
    turtle.left(twist)
    octo(turtle, size)

# arm callback
turtle.onscreenclick(clicked)

# user can quit by typing 'q'
turtle.onkey(turtle.bye, 'q')
turtle.listen()

# read & dispatch events
turtle.mainloop()
Exemplo n.º 47
0
        change_pen()
        is_drawing = True

# change the pen color - called whenever we put the pen down
def change_pen():
    turtle.pensize(random.randint(1,10))

    # generate random colors
    red = random.randint(1,100) / 100
    green = random.random()
    blue = random.random()

    # assign color
    turtle.pencolor(red, green, blue)

# main program
turtle.title("My Turtle")
turtle.setup(500,500, 0,0)

# bind keys to our functions
turtle.onkey(go_up, "Up")
turtle.onkey(go_down, "Down")
turtle.onkey(go_left, "Left")
turtle.onkey(go_right, "Right")
turtle.onkey(toggle_pen, "p")
turtle.onkey(draw_poly, "q")

# listen for key presses
turtle.listen()
turtle.exitonclick()
    def main(self):
        # Game level loop
        while True:
            # Setting initial point and level state
            points = 0
            nextLevel = False

            # Setting game entities
            self.createWindow()
            player = Player(self.dimension)
            enemies = Enemies(self.nEnemies, self.nEnemiesR, self.color,
                              self.level, self.dimension)

            try:
                # Listen keyboard
                turtle.listen()
                turtle.onkey(player.moveLeft, "Left")
                turtle.onkey(player.moveRight, "Right")
                turtle.onkey(player.fireBullet, "space")
                turtle.onkey(turtle.bye, "Escape")

                self.alertText("level " + str(self.level), 2)
                self.alertText("ready!", 1)
                self.alertText("go", 0.5)

                # Game main loop
                while True:
                    # Enemies position
                    for i in range(self.nEnemies):
                        if (enemies[i].isvisible()):
                            enemyX = enemies[i].xcor()
                            enemyY = enemies[i].ycor()

                            if (enemyX < -(self.dimension / 2) + 40 or enemyX >
                                (self.dimension / 2) - 40):
                                enemies.speed *= -1

                                for j in range(self.nEnemies):
                                    if (enemies[j].isvisible()):
                                        enemyX = enemies[j].xcor(
                                        ) + enemies.speed
                                        enemyY = enemies[j].ycor() - 30
                                        enemies[j].setposition(enemyX, enemyY)
                            else:
                                enemies[i].setposition(enemyX + enemies.speed,
                                                       enemyY)

                    # Bullet position
                    if (player.bulletState == "fire"):
                        bulletY = player.bullet.ycor()
                        bulletY += player.bulletSpeed
                        player.bullet.sety(bulletY)

                        if (bulletY > (self.dimension / 2)):
                            player.bullet.hideturtle()
                            player.bulletState = "ready"

                    # Enemy death
                    for i in range(self.nEnemies):
                        if (enemies[i].isvisible()):
                            rad = 15
                            bulletX, bulletY = player.bullet.xcor(
                            ), player.bullet.ycor()
                            enemyX, enemyY = enemies[i].xcor(
                            ), enemies[i].ycor()
                            playerX, playerY = player.player.xcor(
                            ), player.player.ycor()
                            if (bulletX > enemyX - rad
                                    and bulletX < enemyX + rad
                                    and bulletY > enemyY - rad
                                    and bulletY < enemyY + rad):
                                enemies[i].hideturtle()
                                points += 1
                                if (points == self.nEnemies):
                                    self.alertText("You won!", 4)
                                    turtle.resetscreen()
                                    nextLevel = True
                                    break

                            if (enemyY > playerY - rad
                                    and enemyY < playerY + rad):
                                self.alertText("Game over!", 4)
                                turtle.bye()

                    if (nextLevel):
                        break
            except:
                break

            self.level += 1
Exemplo n.º 49
0
    global speed
    speed +=1

def isCollision(t1,t2): 
    #math를 이용해 거북이가 포인트를 먹었을 때의 변화를 설정하는 함수
    d = math.sqrt(math.pow(t1.xcor()-t2.xcor(),2) +
                  math.pow(t1.ycor()-t2.ycor(),2))
    if d <20:
        return True
    else:
        return False

    
#키보드 입력으로 거북이를 움직임
turtle.listen()
turtle.onkey(turnleft,"Left")
turtle.onkey(turnright,"Right")
turtle.onkey(increasespeed,"Up")



while True:
    player.forward(speed)
    
    #거북이(player)가 벽에 부딪히면 뒤를 돌아보게 설정
    if player.xcor() > 300 or player.xcor() < -300:
        player.right(180)
            
    if player.ycor() > 300 or player.ycor() < -300:
        player.right(180)
     
Exemplo n.º 50
0

def isCollision(t1, t2):
    distance = math.sqrt(
        math.pow(t1.xcor() - t2.xcor(), 2) +
        math.pow(t1.ycor() - t2.ycor(), 2))
    if distance < 18:
        return True
    else:
        return False


# create keyboard bindings
# initializing connection between keyboard commands to player movement in the GUI
turtle.listen()
turtle.onkey(move_left, "Left")
turtle.onkey(move_right, "Right")
turtle.onkey(fire_weapon, "space")

# primary game loop
while True:  # while the game is running, or while the player is actually playing the game

    for enemy in enemies:
        # move the enemy
        x = enemy.xcor()  # initializing the x coordinates of the enemy AI
        x += enemy_speed  # setting the enemy speed
        enemy.setx(x)  # setting the x coordinates to the x values on the GUI

        # need the enemy to reverse once it touches either edge of the board
        if enemy.xcor() > 280:
            for e in enemies:
Exemplo n.º 51
0
def move():
    din = raw_input("Go left or right? ")
    direction = din.strip().lower()
    print "okay then", direction
    if direction == "left":
        turtle.left(90)
        turtle.forward(length)
        dashforward(100)
    if direction == "right":
        turtle.right(90)
        turtle.forward(length)
        hexagon()


turtle.onkey(turtleUp, "Up")  #  90
turtle.onkey(turtleDown, "Down")  # 270
turtle.onkey(turtleLeft, "Left")  # 180
turtle.onkey(turtleRight, "Right")  #  0
turtle.onkey(togglePen, "p")
turtle.onkey(dot, "d")
turtle.onkey(lengthPlus, "bracketright")
turtle.onkey(lengthMinus, "slash")
turtle.onkey(move, "m")


def callback(e):
    print e.keysym, repr(e.char)


w = turtle.Screen()
Exemplo n.º 52
0
    else:  # the rest of the time quit dividing early
        color = "white"
        square(x1, y1, x2, y2, color)


# make the drawing screen like the first quadrant of the xy-plane
width = 600
height = 600
t.setup(width + 2, height + 2, None,
        None)  # resize window, +2 to avoid scroll bars
t.screensize(width, height)  # resize canvas
t.setworldcoordinates(9, 9, width,
                      height)  # reset origin, 9 to avoid automatic border

# boilerplate for fastest drawing and coding
t.speed(0)
t.tracer(100, 1)
t.hideturtle()


def draw():
    # these first two clear the screen and draw a border
    square(5, 5, width - 5, height - 5, "black")
    square(10, 10, width - 10, height - 10, "white")
    divide(10, 10, width - 10, height - 10, 5)


t.onkey(draw, 'f')
t.listen()
Exemplo n.º 53
0
def docking():
    cr = turtle.Turtle()
    cr.hideturtle()
    cr.color('gray')
    cr.speed(0)
    cr.penup()
    cr.setpos(0,250)
    cr.seth(270)
    cr.pendown()
    cr.forward(500)
    cr.penup()
    cr.setpos(450,0)
    cr.seth(180)
    cr.pendown()
    cr.forward(900)
    
    def left():
      global cenx  
      global x
      x = x-10
      cenx = cenx-10
    def right():
      global cenx
      global x
      x = x+10
      cenx = cenx+10
    def up():
      global y
      global ceny
      y = y+10
      ceny = ceny+10
    def down():
      global y
      global ceny
      y = y-10
      ceny = ceny-10
    for i in range(100):
        global r
        global x
        global cens
        ma.setx(cenx)
        ma.sety(ceny)
        al.setx(x)
        al.sety(y)
        al.pendown()
        al.seth(90)
        al.clear()
        ma.clear()
        al.circle(r)
        ma.dot(cens, 'white')
        al.penup()
        r = r+1
        x = x+1
        if cens <= 10:
            cens+0.5
        turtle.onkey(left, 'Left')
        turtle.onkey(right, 'Right')
        turtle.onkey(up, 'Up')
        turtle.onkey(down, 'Down')
        turtle.listen()
        turtle.delay(50)
Exemplo n.º 54
0
        y = player.ycor() + 10
        bullet.setposition(x, y)
        bullet.showturtle()

def isCollision(t1, t2):
    distance = math.sqrt(math.pow(t1.xcor() - t2.xcor(), 2) + math.pow(t1.ycor() - t2.ycor(), 2))
    if distance < 15:
        return True
    else:
        return False

#Create keyboard bindings
turtle.listen()
turtle.onkeypress(move_left, 'Left')
turtle.onkeypress(move_right, 'Right')
turtle.onkey(fire_bullet, 'space')

#Main game loop
while True:

    for enemy in enemies:
        #Move the enemy
        x = enemy.xcor()
        x += enemyspeed
        enemy.setx(x)

        #Move the enemy back and down
        if enemy.xcor() > 280:
            #Move all the enemies down
            for e in enemies:
                y = e.ycor()
#	enemy.setx(x)

	#Move the enemy back and down
#	if enemy.xcor() > 280:
#		y = enemy.ycor()
#		y -= 40
#		enemyspeed *= -1
#		enemy.sety(y)

#	if enemy.xcor() < -280:
#		y = enemy.ycor()
#		y -= 40
#		enemyspeed *= -1
#		enemy.sety(y)

	#Move the bullet
#	if bulletstate == "fire":
#		y = bullet.ycor()
#		y += bulletspeed
#		bullet.sety(y)

	#Check to see if bullet hit top
#	if bullet.ycor() > 275:
#		bullet.hideturtle()
#		bulletstate = "ready"

#Keyboard bindings	
turtle.listen()
turtle.onkey(move_left, "Left")
turtle.onkey(move_right, "Right")
#turtle.onkey(fire_bullet, "space")
Exemplo n.º 56
0
    if delta < 70:
        s = s + 1  #Score
        apple.hideturtle()
        a = random.randrange(-300, 300)
        frequency = 1000  #Sound
        duration = 100  # Sound
        winsound.Beep(frequency, duration)  # Sound

        # Score on the Screen with position (x=150, y=250)
        # Score number position x=230, y=250

        score.goto(150, 250)
        score.clear()
        score.write('Score=', font=('Times New Roman', 20, 'bold'))
        score.goto(230, 250)
        score.write(s, font=('Times New Roman', 20, 'bold'))
        apple.goto(a, 300)
        q = 0

#wn.onclick(bowl.goto)# Control of the bowl position

    def left():
        bowl.fd(-50)

    def right():
        bowl.fd(50)

    turtle.onkey(left, "Left")
    turtle.onkey(right, "Right")
    turtle.listen()
Exemplo n.º 57
0
    speed += 1


def isCollision(t1, t2):
    d = math.sqrt(
        math.pow(t1.xcor() - t2.xcor(), 2) +
        math.pow(t1.ycor() - t2.ycor(), 2))
    if d < 20:
        return True
    else:
        return False


#Set keyboard bindings
turtle.listen()
turtle.onkey(turnleft, "Left")
turtle.onkey(turnright, "Right")
turtle.onkey(inscreasespeed, "Up")

while True:
    player.forward(speed)

    #Boundary Checking x coordinate
    if player.xcor() > 290 or player.xcor() < -290:
        player.right(180)
    #Boundary Checking y coordinate
    if player.ycor() > 290 or player.ycor() < -290:
        player.right(180)

    #Boundary Food Checking x coordinate
    if food.xcor() > 290 or food.xcor() < -290:
Exemplo n.º 58
0
    if math.fabs(y) < 250: jog1.setx(y)  #eixo x


'''
turtle.listen()
turtle.onkey(move, "Up")
turtle.onkey(gira_esquerda, "Left")
turtle.onkey(gira_direita, "Right")
turtle.onkey(sp1,"q")
turtle.onkey(dp1,"w")
turtle.onkey(sp1,"e")
turtle.onkey(dp1,"r")

'''
listen()
onkey(move, "Up")
onkey(gira_esquerda, "Left")
onkey(gira_direita, "Right")
onkey(sp1, "q")
onkey(dp1, "w")
onkey(sp2, "e")
onkey(dp2, "r")

#print("o tamanho do jogador eh",jog1.stretch_wid())

while True:
    obj_2.setheading(jog1.heading())
    a = p3 * math.cos(jog1.heading() * 3.1415 / 180)
    b = p3 * math.sin(jog1.heading() * 3.1415 / 180) - p1
    obj_2.setposition(a, b)
Exemplo n.º 59
0
    h = turtle.window_height()
    if t.ycor() < h/2 - 10:      
        t.seth(90)
        t.forward(10)


def paint():
    t.pendown()

def dont_paint():
    t.penup()
    
    
def spin(x, y):
    t.left(2*360)
    t.right(2*360)
    

t.onclick(spin)
turtle.onscreenclick(move)

turtle.onkey(move_right, 'Right')
turtle.onkey(move_left, 'Left')
turtle.onkey(move_up, 'Up')
turtle.onkey(move_down, 'Down')
turtle.onkey(paint, 'U')
turtle.onkey(dont_paint, 'D')

turtle.listen()

Exemplo n.º 60
0
import turtle
import random


def drunken_move():
    turtle.setheading(random.randint(0, 360))
    turtle.forward(random.randint(00, 50))
    turtle.stamp()


def restart():
    turtle.reset()


turtle.shape('turtle')

turtle.onkey(drunken_move, ' ')
turtle.onkey(restart, 'Escape')
turtle.listen()