コード例 #1
0
ファイル: Turtle Run Game.py プロジェクト: hubls/p2_201611092
def play():           # 게임을 실제로 플레이 하는 함수.
    global score
    global playing
    t.forward(10)       # 주인공 거북이 10만큼 앞으로 이동합니다.
    if random.randint(1, 5) == 3: # 1~5사이에서 뽑은 수가 3이면(20%확률)
        ang = te.towards(t.pos())
        te.sethading(ang)        # 악당 거북이가 주인공 거북이를 바라봅니다
    speed = score + 5            # 점수에 5를 더해서 속도를 올립니다.
                                 # 점수가 올라가면 빨라집니다.
                                 
    if speed > 15:               # 속도가 15를 넘지는 않도록 합니다
        speed = 15
    te.forward(speed)
    
    if t.distance(te) < 12:      # 주인공과 악당의 거리가 12보다 작으면
                                 # 게임을 종료합니다.  
        
        text = "Score : " + str(score)
        message("Game Over", text)
        playing = False
        score = 0
    
    
    if t.distance(ts) < 12:      # 주인공과 먹이의 거리가 12보다 작으면(가까우면)
        score = score + 1        # 점수를 올립니다.
        t.write(score)           # 점수를 화면에 표시합니다.
        star_x = random.randint(-230, 230)
        star_y = random.randint(-230, 230)
        ts.goto(star_x, star_y)  # 먹이를 다른 곳으로 옮깁니다.
        
    if playing:
        t.ontimer(play, 100)     # 게임 플레이 중이면 0.1초후
コード例 #2
0
ファイル: main.py プロジェクト: etiennedub/battleship
def main():
    """
    Tous les phase du battleship passe par le main()
    et il sert de boucle principal car il est appelé à
    tous les 0.5 secondes
    """
    if i.phase == "PlaceShip":
        i.placeShip()
    elif i.phase == "Attack": # Nom fictif
        i.attack()
    elif i.phase == "win":
        print('Vous avez gagné!')
        turtle.goto(0,0)
        turtle.pencolor('black')
        turtle.write('Vous avez gagné!',align="center",font=("Arial",70, "normal"))
        i.phase = "exit"
    elif i.phase == "lose":
        print('Vous avez perdu!')
        turtle.goto(0,0)
        turtle.pencolor('black')
        turtle.write('Vous avez perdu!',align="center",font=("Arial",70, "normal"))
        i.phase = "exit"
    elif i.phase == "exit":
        turtle.exitonclick()
        return None
    else:
        print('out')

    turtle.ontimer(main,500)
コード例 #3
0
ファイル: gameOfLife.py プロジェクト: Nagoogin/game-of-life
    def perform_step():
        board.step()
        board.display()

        if continuous:
            # calls function in question after t milliseconds
            turtle.ontimer(perform_step, 25)
コード例 #4
0
def spawn_trash():
    if game_over:
        return
    #-10 is needed so that the snake can crash into the trash
    trash.setpos(random.randint(int(MIN_X/20)+1, int(MAX_X)/20-1)*20, 
                 random.randint(int(MIN_Y)/20+1, int(MAX_Y)/20-1)*20)

    #keep track of trash stamps
    stamp = trash.stamp()
    trash_stamps.append(stamp)

    #keep track of trash positions for each stamp
    trash_positions.append(trash.pos()) 
#    positions.append((trash.pos()[0]+10, trash.pos()[1]+10))
#    positions.append((trash.pos()[0]+10, trash.pos()[1]-10))
#    positions.append((trash.pos()[0]-10, trash.pos()[1]-10))
#    positions.append((trash.pos()[0]-10, trash.pos()[1]+10))
#    trash_positions[stamp] = positions

    #keep reverse mapping of position to stamp id
#    for position in positions:
#        trash_position_values[position] = stamp

    global trash_count
    trash_count += 1

    if trash_count > MAX_TRASH:
        trigger_game_over()

    calculate_score()
    turtle.ontimer(spawn_trash, trash_step_time)
コード例 #5
0
ファイル: main-2.py プロジェクト: golubaca/python-examples
def move_t1():
    # first turtle moves a little
    t1.left(10)  
    t1.forward(10)
    
    # repeat it after 100ms
    turtle.ontimer(move_t1, 100)
コード例 #6
0
    def play(self):
        cannon = LaserCannon()
        turtle.ontimer(self.add_alien,2000)
        turtle.listen()

        # Start the event loop.
        turtle.mainloop()
コード例 #7
0
ファイル: main-2.py プロジェクト: golubaca/python-examples
def move_t2():
    # second turtle moves a little
    t2.right(10)  
    t2.forward(10)
    
    # repeat it after 100ms
    turtle.ontimer(move_t2, 100)
コード例 #8
0
def despawn_power_up():
    global power_up_present
    if power_up_present:
        power_up_present = False
        recycle_positions.pop()
        power_up_turtle.clearstamps()
        turtle.ontimer(spawn_power_up, power_up_step_time)
コード例 #9
0
ファイル: logoclok.py プロジェクト: slott56/HamCalc-2.1
def hands( freq=166 ):
    """Draw three hands.

    :param freq: Frequency of refresh in milliseconds.
    """
    global running
    now= datetime.datetime.now()
    time= now.time()
    h, m, s, ms = time.hour, time.minute, time.second, int(time.microsecond/1000)

    # Erase old hands.
    while turtle.undobufferentries():
        turtle.undo()

    # Draw new hands.
    hand( h*5+m/60+s/3600, .6*R, 3 )
    hand( m+s/60, .8*R, 2 )
    hand( s+ms/1000, .9*R, 1 )

    # Draw date and time
    turtle.penup(); turtle.home()
    turtle.goto( 0, -120 ); turtle.write( now.strftime("%b %d %H:%M:%S"), align="center", font=("Helvetica", 24, "normal") )

    # Reschedule hands function
    if running:
        # Reset timer for next second (including microsecond tweak)
        turtle.ontimer( hands, freq-(ms%freq) )
コード例 #10
0
 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)
コード例 #11
0
 def __init__(self, init_heading, speed):
     super(Bomb, self).__init__(speed)
     self.color('red','red')
     self.shape('circle')
     self.shapesize(0.4, 0.4)
     self.setheading(init_heading)
     self.up()
     # Start the bomb moving
     turtle.ontimer(self.move,100)
コード例 #12
0
 def move(self):
     self.forward(self.speed)
     if self.out_of_bounds():
         self.remove()
     else:
         turtle.ontimer(self.move,200)
     if self.end_of_screen():
         points(1)
         global score
コード例 #13
0
def flashing_block():
    global STAMP_ID
    global BLOCK_POS
    
    t.clearstamp(STAMP_ID)
    nx,ny = BLOCK_POS
    t.setpos(nx,ny)
    STAMP_ID = t.stamp()
    
    t.ontimer(flashing_block,100)
コード例 #14
0
def power_up():
    print('RECYCLE TIME!')
    global can_recycle, move_step_time, POWER_UP_TIME
    can_recycle = True
        
    snake.pencolor("yellow")
    snake.fillcolor('yellow')
    move_step_time = int(move_step_time * 2/3)
    
    turtle.ontimer(power_down, POWER_UP_TIME) #power down after POWER_UP_TIME seconds    
コード例 #15
0
def spawn_food():
    if game_over:
        return
    food.goto(random.randint(int(MIN_X/20)+1,int(MAX_X)/20-1)*20, 
                random.randint(int(MIN_Y)/20+1, int(MAX_Y)/20-1)*20)
    food_positions.append(food.pos())
    food_stamps.append(food.stamp())
    turtle.ontimer(spawn_food, food_step_time)
    if len(food_stamps) > 5:
        food.clearstamp(food_stamps.pop(0))
        food_positions.pop(0)
コード例 #16
0
def spawn_trash():
    if game_over:
        return
    trash.goto(random.randint(int(MIN_X/20)+1, int(MAX_X)/20-1)*20 - 10, 
                 random.randint(int(MIN_Y)/20+1, int(MAX_Y)/20-1)*20 - 10)
    trash.stamp()
    trash_positions.append((trash.pos()[0]+10, trash.pos()[1]+10))
    trash_positions.append((trash.pos()[0]+10, trash.pos()[1]-10))
    trash_positions.append((trash.pos()[0]-10, trash.pos()[1]-10))
    trash_positions.append((trash.pos()[0]-10, trash.pos()[1]+10))
    
    turtle.ontimer(spawn_trash, trash_step_time)
コード例 #17
0
def move_step():
    global current_direction
    current_direction = temp_current_direction
    if detect_collision():
        trigger_game_over()
    else:
        snake.clearstamp(snake_stamps.pop(0))
        calculate_next_pos()
        snake_positions.pop(0)
        add_segment_to_front()

        turtle.ontimer(move_step, move_step_time)
コード例 #18
0
ファイル: snake_v1.py プロジェクト: bonoxu/planeGames
def move():
    global x, y, Vsnake, t, cherry
    t = t + 1
    turtle.forward(Vsnake)
    turtle.stamp();

    if cherry > 0:
        cherry = cherry - 1
    else:
        turtle.clearstamps(1)


    turtle.ontimer(move, 100)
コード例 #19
0
def spawn_power_up():
    if game_over:
        return
    global power_up_present, can_recycle
    if not (power_up_present or can_recycle):
        chance = random.random()
        if chance <= power_up_chance:
            power_up_present = True
            power_up_turtle.setpos(random.randint(int(MIN_X/20)+1,int(MAX_X)/20-1)*20, 
                    random.randint(int(MIN_Y)/20+1, int(MAX_Y)/20-1)*20)
            power_up_turtle.stamp()
            recycle_positions.append(power_up_turtle.pos())
            turtle.ontimer(despawn_power_up,10000)
    turtle.ontimer(spawn_power_up, power_up_step_time)
コード例 #20
0
 def update(self):
     # update all spiros
     nComplete = 0
     for spiro in self.spiros:
         # update
         spiro.update()
         # count completed ones
         if spiro.drawingComplete:
             nComplete+= 1
     # if all spiros are complete, restart
     if nComplete == len(self.spiros):
         self.restart()
     # call timer
     turtle.ontimer(self.update, self.deltaT)
コード例 #21
0
def spawn_food():
    if game_over:
        return
    global food_remaining
    food.setpos(random.randint(int(MIN_X/20)+1,int(MAX_X)/20-1)*20, 
                random.randint(int(MIN_Y)/20+1, int(MAX_Y)/20-1)*20)
    food_positions.append(food.pos())
    food_stamps.append(food.stamp())
    turtle.ontimer(spawn_food, food_step_time)
    if len(food_stamps) > min(5, food_remaining):
        food.clearstamp(food_stamps.pop(0))
        food_positions.pop(0)
  
    if food_remaining == 0:
        trigger_game_over()
コード例 #22
0
def left_block():
    '''
    Makes a block move to the left, 
    until it disappears off the screen
    '''
    global STAMP_ID
    global BLOCK_POS
    
    t.clearstamp(STAMP_ID)
    BLOCK_POS = (BLOCK_POS[0] - 10,BLOCK_POS[1])
    nx,ny = BLOCK_POS
    t.setpos(nx,ny)
    STAMP_ID = t.stamp()
    
    t.ontimer(left_block,100)
コード例 #23
0
 def __init__(self, N):
     # timer value in milliseconds
     self.deltaT = 10
     # get window dimensions
     self.width = turtle.window_width()
     self.height = turtle.window_height()
     # create spiro objects
     self.spiros = []
     for i in range(N):
         # generate random parameters
         rparams = self.genRandomParams()
         # set spiro params
         spiro = Spiro(*rparams)
         self.spiros.append(spiro)
     # call timer
     turtle.ontimer(self.update, self.deltaT)
コード例 #24
0
ファイル: ball_test.py プロジェクト: bonoxu/planeGames
def move():
    global x, y, Vx, Vy, g

    x = x + Vx
    if -(ylimit*0.95) < y < (ylimit*0.95):
        Vy = Vy + g/2 - b*Vy
    y = y + Vy

    if not -xlimit < x < xlimit:
        Vx = -Vx
    if not -ylimit < y < ylimit:
        Vy = -Vy

    turtle.goto(x, y)

    turtle.ontimer(move, 1)
コード例 #25
0
ファイル: diadungeon.py プロジェクト: zerosyntax/zerogames
    def move(self):
        if self.direction == "up":
            deltax = 0
            deltay = UNIT_SIZE
        elif self.direction == "dn":
            deltax = 0
            deltay = 0 - UNIT_SIZE
        elif self.direction == "lt":
            deltax = 0 - UNIT_SIZE
            deltay = 0
            self.shape(self.shape_left)
        elif self.direction == "rt":
            deltax = UNIT_SIZE
            deltay = 0
            self.shape(self.shape_right)
        else:  # For completeness of logic here even though it looks like
                # a direction will always be set and this else block may
                # never be hit. Maybe in the future monsters can stand
                # still, meaning they have no direction and in that case
                # we might want this else block. Even then we might not
                # explicitly need it for the code to work but it is more
                # correct to have it in place.
            deltax = 0
            deltay = 0

        if self.nearby(player):
            if player.xcor() < self.xcor():
                self.direction = "lt"
            elif player.xcor() > self.xcor():
                self.direction = "rt"
            elif player.ycor() < self.ycor():
                self.direction = "dn"
            elif player.ycor() > self.ycor():
                self.direction = "up"
            # NOTE: The above is biased such that horizantal following always
            # occurs before vertical following

        newx = self.xcor() + deltax
        newy = self.ycor() + deltay

        if (newx, newy) not in walls:
            self.goto(newx, newy)
        else:
            self.direction = random.choice(["up", "dn", "lt", "rt"])

        turtle.ontimer(self.move, t=random.randint(100, self.max_pause))
コード例 #26
0
ファイル: Spiro.py プロジェクト: georgevine/Python_Playground
 def __init__(self, N):
     #set value of timer in millis
     self.deltaT = 10
     #get window dimensions
     self.width = turtle.window_width()
     self.height = turtle.window_height()
     #create spiros
     self.spiros = []
     for i in range(N):
         #generate random parameters
         rparams = self.genRandomParams()
         #set spiro parameters
         spiro = Spiro(*rparams)
         #add new spiro to array
         self.spiros.append(spiro)
     #set the ontimer method to call update() every deltaT millis
     turtle.ontimer(self.update, self.deltaT)
コード例 #27
0
def countdown():
    font=24
    global clock
    timer.clear()
    timer.write(str(clock),font=('ariel',font,'bold'))
    clock-=1
    turtle.ontimer(countdown,1000)
    if clock==5:
        global font
        font=40
        timer.pencolor('red')
        #timer.write(time,font=('ariel',font,'bold')
    elif clock==-1:
        timer.clear()
        timer.write('GAME OVER',font=('ariel',70,'bold'))
        time.sleep(1)
        turtle.bye()
        exit()
        turtle.outimer(countdown)
コード例 #28
0
    def __init__(self, speed):
        super(Alien, self).__init__(speed)
        self.tracer(0)
        self.up()
        self.shape('turtle')

        # The initial position is near the top of the screen
        self.goto(random.randint(-199,199), 190)
        # The initial heading is downwards
        self.setheading(random.randint(250,280))
        self.tracer(1)

        # Filter the global alien list for only those aliens that are alive
        Alien.alientList = [x for x in Alien.alienList if x.alive]
        # Add ourself to the list
        self.alive = True
        Alien.alienList.append(self)

        # Register the initial movement event
        turtle.ontimer(self.move,200)
コード例 #29
0
ファイル: turtle_时钟.py プロジェクト: W7297911/test
def Tick():
    # 绘制表针的动态显示
    t = datetime.today()
    second = t.second + t.microsecond * 0.000001
    minute = t.minute + second / 60.0
    hour = t.hour + minute / 60.0
    secHand.setheading(6 * second)
    minHand.setheading(6 * minute)
    hurHand.setheading(30 * hour)
    
    turtle.tracer(False)
    printer.forward(65)
    printer.write(Week(t), align="center", font=("Courier", 14, "bold"))
    printer.back(130)
    printer.write(Date(t), align="center", font=("Courier", 14, "bold"))
    printer.home()
    turtle.tracer(True)
    
    # 100ms后继续调用tick
    turtle.ontimer(Tick, 100)
コード例 #30
0
ファイル: py_moorhuhnRoman.py プロジェクト: s-kimmer/tesp2016
    def step(self):

#        print("stepcrosshair")


        if self.rot == 2:
            clickX = np.int(self.u + self.screenWidth+1)
            clickY = np.int(self.v+22)
        
            clickX = max(self.screenWidth + 10, clickX)
            clickX = min(clickX, self.screenWidth + WINWIDTH - 20)
            clickY = max(30, clickY)
            clickY = min(WINHEIGHT, clickY)
            click(clickX, clickY)
#            click(clickX, clickY)
#        else:
#            win32api.SetCursorPos((clickX,clickY))

        if self.goon:
            turtle.ontimer(self.getpos, 40)

        self.setposition((self.u - WINWIDTH/2), -(self.v - WINHEIGHT/2))
コード例 #31
0
ファイル: ping.py プロジェクト: evgeny-vlasov/pythonSchool
    turtle.delay(8)
    ball.setx(X + pdx)
    ball.sety(Y + pdy)
    X = ball.xcor()
    Y = ball.ycor()
    Xpr1 = pr1.xcor()
    Ypr1 = pr1.ycor()
    deltaX1 = abs(Xpr1 - X)
    deltaY1 = abs(Ypr1 - Y)
    if deltaX1 < 18 and deltaY1 < 40:
        if X > -200:
            score1 += 1
            s1.undo()
            s1.write(score1, font=FONT)
        pdx = -pdx
    if X < -290:
        score1 = score1 - 1
        s1.undo()
        s1.write(score1, font=FONT)
        pdx = -pdx
    if X > 290:
        pdx = -pdx
    if Y < -290:
        pdy = -pdy
    if Y > 290:
        pdy = -pdy
    turtle.ontimer(move, 5)


turtle.ontimer(move, 5)
コード例 #32
0
def move_snake():
    my_pos = snake.pos()
    x_pos=my_pos[0]
    y_pos=my_pos[1]




    if direction==RIGHT:
        snake.goto(x_pos + SQUARE_SIZE, y_pos)
        print("you moved right!")

    elif direction==LEFT:
        snake.goto(x_pos - SQUARE_SIZE, y_pos)
        print("you moved left!")

    elif direction==UP:
        snake.goto(x_pos, SQUARE_SIZE + y_pos)
        print("you moved up!")

    elif direction==DOWN:
        snake.goto(x_pos ,y_pos - SQUARE_SIZE )
        print("you moved down!")
    #####################the move of the snake
    my_pos=snake.pos()
    pos_list.append(my_pos)
    new_stamp = snake.stamp()
    stamp_list.append(new_stamp)
    global c,food_stamp,food_pos
    ## how the snake stamps disapper
    
    if snake.pos() in food_pos:
        food_ind=food_pos.index(snake.pos())
        food.clearstamp(food_stamp[food_ind])
        food_pos.pop(food_ind)
        food_stamp.pop(food_ind)
        print("you have eaten the food")
        make_food()
    ##how to eat food
        c = c + 1
        score.clear()
        score.write("score = "+ str (c))
        

        
        
    else :
        old_stamp = stamp_list.pop(0)
        snake.clearstamp(old_stamp)
        pos_list.pop(0)
    
    new_pos = snake.pos()
    new_x_pos = new_pos[0]
    new_y_pos = new_pos[1]
#clear stamp
    if new_x_pos >= RIGHT_EDGE:
        print("you hit the right edge! game over!")
        quit()
    
    elif new_x_pos <= LEFT_EDGE:
        print("you hit the left edge! game over!")
        quit()

    elif new_y_pos >= UP_EDGE:
        print("you hit the up edge! game over!")
        quit()

    elif new_y_pos <= DOWN_EDGE:
        print("you hit the down edge! game over!")
        quit()

    if pos_list[-1] in pos_list[0:-1]:
        
        print("you ate yourself")
        quit()
##when you hit edges you die
    turtle.ontimer(move_snake,TIME_STEP)
コード例 #33
0
def move_snake():

    global direction
    my_pos = snake.pos()
    x_pos = my_pos[0]
    y_pos = my_pos[1]

    if direction == RIGHT:
        snake.goto(x_pos + square_size, y_pos)
        print("You moved right!")
    elif direction == LEFT:
        snake.goto(x_pos - square_size, y_pos)
        print("You moved left!")
    elif direction == UP:
        snake.goto(x_pos, y_pos + square_size)
        print("You moved up!")
    elif direction == DOWN:
        snake.goto(x_pos, y_pos - square_size)
        print("You moved down!")

    # stamp and record the snake's head
    my_pos = snake.pos()
    pos_list.append(my_pos)
    new_stamp = snake.stamp()
    stamp_list.append(new_stamp)

    # if the snake is eating food
    if snake.pos() in food_pos:
        food_ind = food_pos.index(snake.pos())
        food.clearstamp(food_stamps[food_ind])
        food_pos.pop(food_ind)
        score.append(food_ind)
        food_stamps.pop(food_ind)
        print("You have eaten a food!")
        make_food()
        turtle.clear()
        turtle.goto(200, 200)
        turtle.write(len(score), font=("Arial", 30))
        turtle.goto(-300, 0)
    else:
        # cleartsamps the tail and makes storage edits
        old_stamp = stamp_list.pop(0)
        snake.clearstamp(old_stamp)
        pos_list.pop(0)

    new_pos = snake.pos()
    new_x_pos = new_pos[0]
    new_y_pos = new_pos[1]

    if new_x_pos >= RIGHT_EDGE:
        turtle.goto(0, 0)
        turtle.write("The red snake hit the right edge! game over!",
                     font=("Ariel", 30),
                     align="center")
        time.sleep(2)
        quit()

    elif new_x_pos <= LEFT_EDGE:
        turtle.goto(0, 0)
        turtle.write("The red snake hit the left edge! game over!",
                     font=("Ariel", 30),
                     align="center")
        time.sleep(2)
        quit()

    elif new_y_pos >= UP_EDGE:
        turtle.goto(0, 0)
        turtle.write("The red snake hit the up edge! game over!",
                     font=("Ariel", 30),
                     align="center")
        time.sleep(2)
        quit()

    elif new_y_pos <= DOWN_EDGE:
        turtle.goto(0, 0)
        turtle.write("The red snake hit the down edge! game over!",
                     font=("Ariel", 30),
                     align="center")
        time.sleep(2)
        quit(pos_list)

    if pos_list[-1] in pos_list[0:-1]:
        turtle.goto(0, 0)
        turtle.write("The red snake hit yourself!",
                     font=("Ariel", 30),
                     align="center")
        time.sleep(2)
        quit()

    turtle.ontimer(move_snake, TIME_STEP)
コード例 #34
0
 def after(self, function, milliseconds):
     turtle.ontimer(function, milliseconds)
コード例 #35
0
def end_timer():
    show_trash()
    show_caleb()
    print(caleb_hole + trash_hole)
    turtle.ontimer(end_timer, 3000)
コード例 #36
0
ファイル: lab_7.py プロジェクト: ofirn21-meet/meet2019y1lab7
def move_snake():
    my_pos = snake.pos()
    x_pos = my_pos[0]
    y_pos = my_pos[1]
    SQUARE_SIZE = 20

    #If snake.direction is up, then we want the snake to change
    #it’s y position by SQUARE_SIZE
    if snake.direction == "Up":

        snake.goto(x_pos, y_pos + SQUARE_SIZE)
        print("You moved up!")
    elif snake.direction == "Down":
        snake.goto(x_pos, y_pos - SQUARE_SIZE)
        print("You moved down!")
    elif snake.direction == "Left":
        snake.goto(x_pos - SQUARE_SIZE, y_pos)
        print("You moved left!")
    elif snake.direction == "Right":
        snake.goto(x_pos + SQUARE_SIZE, y_pos)
        print("You moved right!")
        #Make the snake stamp a new square on the screen
        #Hint - use a single function to do this
    new_stamp()
    turtle.ontimer(move_snake, TIME_STEP)
    ######## SPECIAL PLACE - Remember it for Part 5

    #If snake is on top of food item
    if snake.pos() in food_pos:
        food_index = food_pos.index(snake.pos())  #What does this do?
        food.clearstamp(food_stamps[food_index])  #Remove eaten food stamp
        food_pos.pop(food_index)  #Remove eaten food position
        food_stamps.pop(food_index)  #Remove eaten food stamp
        print("You have eaten the food!")
        SQUARE_SIZE = SQUARE_SIZE * 2

    #HINT: This if statement may be useful for Part 8

    #remove the last piece of the snake (Hint Functions are FUN!)
    remove_tail()
    #Grab position of snake
    new_pos = snake.pos()
    new_x_pos = new_pos[0]
    new_y_pos = new_pos[1]

    # The next three lines check if the snake is hitting the
    # right edge.
    if new_x_pos >= RIGHT_EDGE:
        print("You hit the right edge! Game over!")
        quit()
    elif new_x_pos <= LEFT_EDGE:
        print("You hit the left edge! Game over!")
        quit()
    elif new_y_pos >= UP_EDGE:
        print("You hit the up edge! Game over!")
        quit()
    elif new_y_pos <= DOWN_EDGE:
        print("You hit the right edge! Game over!")
        quit()
    if len(food_stamps) <= 6:
        make_food()

    for i in range(len(pos_list)):
        for j in range(len(pos_list)):
            if pos_list[i] == pos_list[j] and i != j:
                print("you ate yourself")
                quit()
コード例 #37
0
def scor():
    turtle.goto(400, 270)
    turtle.color("White")
    turtle.write("score: " + str(score), ("Arial", "normal"))
    turtle.ontimer(scor, TIME_STEP)
コード例 #38
0
    new_pos = snake.pos()
    new_x_pos = new_pos[0]
    new_y_pos = new_pos[1]

    # The next three lines check if the snake is hitting the 
    # right edge.
    if new_x_pos >= RIGHT_EDGE:
         print("You hit the right edge! Game over!")
         quit()
    elif new_x_pos <= LEFT_EDGE:
        print("You hit the left edge! Game over!")
        quit()
    elif new_y_pos <= DOWN_EDGE:
        print("You hit the down edge! Game over!")
        quit()
    elif new_y_pos >= UP_EDGE:
        print("You hit the up edge! Game over!")
        quit()

    if len(food_stamps) <= 6 :
        make_food()
    

    turtle.ontimer(move_snake,TIME_STEP)
    
move_snake()    



turtle.mainloop()
コード例 #39
0
def move_basket():
    global angle, score, obj_pos
    basket.forward(10)

    basket_pos = basket.pos()
    basket_x = basket_pos[0]
    basket_y = basket_pos[-1]

    for i in block_pos:
        d = distance(basket.pos(), i)
        if d < 20:
            #print("ddd")
            block_index = block_pos.index(i)
            block_stamper.clearstamp(block_stamps[block_index])
            block_pos.pop(block_index)
            block_stamps.pop(block_index)

            angle = bounce(angle)


##            block_ind = block_pos.index(obj.pos()) #remove eaten food stamps
##            block.clearstamp(block_stamps[block_ind])
##            block_pos.pop(block_ind)
##            block_stamps.pop(block_ind)

# Hitting the platform
    obj_x = obj.pos()[0]
    obj_y = obj.pos()[1]
    v1 = (obj_x + LENGHT / 2 * SQUARE_SIZE, obj_y)
    v2 = (obj_x - LENGHT / 2 * SQUARE_SIZE, obj_y)
    v3 = (obj_x, obj_y + SQUARE_SIZE)
    v4 = (obj_x, obj_y - SQUARE_SIZE)

    RIGHT_edge = obj_x + LENGHT / 2 * SQUARE_SIZE
    LEFT_edge = obj_x - LENGHT / 2 * SQUARE_SIZE
    UPPER_edge = obj_y + SQUARE_SIZE
    LOWER_edge = obj_y - SQUARE_SIZE
    basket_x = basket.pos()[0]
    basket_y = basket.pos()[1]
    if basket_x <= RIGHT_edge and basket_x >= LEFT_edge and basket_y <= UPPER_edge and basket_y >= LOWER_edge:
        angle = bounce(angle)

    if basket_x >= RIGHT_EDGE:
        angle = bounce(angle)
        #print('hello')

    if basket_x <= LEFT_EDGE:
        angle = bounce(angle)

    if basket_y >= UP_EDGE:
        angle = bounce(angle)

    if obj.pos() == basket_y and basket_x:
        angle = bounce(angle)

    if basket_y <= DOWN_EDGE:
        quit()

    # check if the basket hit any blocks
    if basket.pos() in block_pos:
        #block should disappear
        score = score + 1
        angle = bounce(angle)
    turtle.ontimer(move_basket, TIME_STEP)
コード例 #40
0
wh_sq = Wh_Sq()
player = Player()
set_up(level_1)


#
#
## Keyboard
trt.listen()
trt.onkey(player.go_up,"Up")
trt.onkey(player.go_down,"Down")
trt.onkey(player.go_right,"Right")
trt.onkey(player.go_left,"Left")

for enemy in enemies:
		trt.ontimer(enemy.move,t=250)
		
test = True
while test:
	for treasure in treasures:
		if player.isCollision(treasure):
			print "YOU WIN"
			treasures.remove(treasure)
			treasure.destroy()
			test = False
	for enemy in enemies:
		if player.isCollision(enemy):
			print "Game over"
			player.goto(ini_x,ini_y)
			
	
コード例 #41
0
def move_player():
    global village, if_player_food, direction, gdirection
    my_pos = turtle.pos()
    x_pos = my_pos[0]
    y_pos = my_pos[1]
    def ghostChase():
        if direction == RIGHT:
            enemy.goto(x_pos + (1.5*SQUARE_SIZE), y_pos)
        #print("you moved to the right!")
        elif direction == LEFT:
            enemy.goto(x_pos - (1.5*SQUARE_SIZE), y_pos)
        #print("you moved to the left!")
        elif direction == UP:
            enemy.goto(x_pos, y_pos + (1.5*SQUARE_SIZE))
        #print("you moved UP")
        elif direction == DOWN:
            enemy.goto(x_pos, y_pos - (1.5*SQUARE_SIZE))
        turtle.ontimer(ghostChase, TIME_STEP)
                
            
        
    
    if direction == RIGHT:
        turtle.goto(x_pos + (1.5*SQUARE_SIZE), y_pos)
        #print("you moved to the right!")
    elif direction == LEFT:
        turtle.goto(x_pos - (1.5*SQUARE_SIZE), y_pos)
        #print("you moved to the left!")
    elif direction == UP:
        turtle.goto(x_pos, y_pos + (1.5*SQUARE_SIZE))
        #print("you moved UP")
    elif direction == DOWN:
        turtle.goto(x_pos, y_pos - (1.5*SQUARE_SIZE))
        #print("you moved DOWN")
    my_pos = turtle.pos()
    pos_list.append(my_pos)
    #print(pos_list[-1])
    global TIME_STEP
    global count
        
    #limiting the player in the border
    if x_pos > SIZE_X/2:
        turtle.ht()
        turtle.goto(-SIZE_X/2 + 10, y_pos)
        turtle.st()
    elif x_pos <= -SIZE_X/2:
        turtle.ht()
        turtle.goto(SIZE_X/2, y_pos)
        turtle.st()

    elif y_pos > SIZE_Y/2:
        turtle.ht()
        turtle.goto(x_pos, -SIZE_Y/2+2)
        turtle.st()

    elif y_pos <= -SIZE_Y/2:
        turtle.ht()
        turtle.goto(x_pos, SIZE_Y/2-2)
        turtle.st()
    if if_player_food == True:
        enemy.shape("ghost.gif")
        turtle.shape("player_F.gif")
    elif if_player_food == False:
        enemy.shape("ghost_F.gif")
        turtle.shape("player.gif")
    if -30 <enemy.pos()[0] - turtle.pos()[0] < 30 and -30 < enemy.pos()[1] - turtle.pos()[1] < 30 and if_player_food == False:
        
        
        village.st()
        enemy.goto(0,0)
        time.sleep(0.5)

        #updating player with food status
        if_player_food = True

            

    
    if -40 <enemy.pos()[0] - turtle.pos()[0] < 40 and -40 < enemy.pos()[1] - turtle.pos()[1] < 40 and if_player_food == True:
        score.clear()
        count -=100
        scores.append(count)
        score.pencolor("white")

        score.write("score: "+str(count),font=("Arial", 28, "normal"))
        if_player_food = False
        enemy.goto(0,0)
        time.sleep(0.2)

    if (-15 <village.pos()[0] - turtle.pos()[0] < 15 and -15 < village.pos()[1] - turtle.pos()[1] < 15) and if_player_food == True:
        

            



            score.clear()
            count +=100
            scores.append(count)
            score.pencolor("white")
            score.write("score: "+str(count),font=("Arial", 28, "normal"))
            
            enemy.shape("ghost_F.gif")
            turtle.shape("player.gif")
            if_player_food = False
    if count < 0:
        turtle.goto(0,0)
        turtle.pencolor("white")
        turtle.write("Ghost won!", font = ("Ariel", 28,"normal"))
        time.sleep(5)
        quit()
    
    if count == 1000:
        turtle.goto(0,0)
        turtle.pencolor("white")
        turtle.write("PLayer won!", font = ("Ariel", 28,"normal"))
        time.sleep(5)
        quit()
        



    turtle.ontimer(move_player,TIME_STEP)
コード例 #42
0
 def __animation_loop(self):
     if self.simulation_running:
         self.tick()
     turtle.ontimer(self.__animation_loop, self.delay)
コード例 #43
0
ファイル: snake.py プロジェクト: rushdi21-meet/meet2019y1lab7
def move_snake():
    global i
    global TIME_STEP
    my_pos = snake.pos()
    x_pos = my_pos[0]
    y_pos = my_pos[1]

    #If snake.direction is up, then we want the snake to change
    #it’s y position by SQUARE_SIZE
    if snake.direction == "Up":
        snake.goto(x_pos, y_pos + SQUARE_SIZE)
        print("You moved up!")
    elif snake.direction == "Down":
        snake.goto(x_pos, y_pos - SQUARE_SIZE)
        print("You moved down!")
    #4. Write the conditions for RIGHT and LEFT on your own
    elif snake.direction == "Right":
        snake.goto(x_pos + SQUARE_SIZE, y_pos)
        print("You moved right!")
    elif snake.direction == "Left":
        snake.goto(x_pos - SQUARE_SIZE, y_pos)
        print("You moved left!")
        #Add new lines to the end of the function
    #Grab position of snake
    new_pos = snake.pos()
    new_x_pos = new_pos[0]
    new_y_pos = new_pos[1]

    # The next three lines check if the snake is hitting the
    # right edge.
    if new_x_pos >= RIGHT_EDGE:
        print("You hit the right edge! Game over!")
        quit()
    # The next two lines check if the snake is hitting the
    # left edge.
    if new_x_pos <= LEFT_EDGE:
        print("You hit the left edge! Game over!")
        quit()
    # The next one lines check if the snake is hitting the
    # top edge.
    if new_y_pos >= UP_EDGE:
        print("You hit the top edge! Game over!")
        quit()
    # The next 0 lines check if the snake is hitting the
    #bottom edge.
    if new_y_pos <= DOWN_EDGE:
        print("You hit the bottom edge! Game over!")
        quit()
    if snake.pos() in pos_list[:-1]:
        quit()
    # You should write code to check for the left, top, and bottom edges.
    #####WRITE YOUR CODE HERE
    #Make the snake stamp a new square on the screen
    #Hint - use a single function to do this
    print(new_stamp())
    ######## SPECIAL PLACE - Remember it for Part 5
    #If snake is on top of food item
    if snake.pos() in food_pos:
        snake.color(random.choice(snake_color))
        food_index = food_pos.index(snake.pos())  #What does this do?
        food.clearstamp(food_stamps[food_index])  #Remove eaten food stamp
        food_pos.pop(food_index)  #Remove eaten food position
        food_stamps.pop(food_index)  #Remove eaten food stamp
        print("You have eaten the food!")
        print(new_stamp())
        i += 1

    if snake.pos() in poison_pos:
        poison_index = poison_pos.index(snake.pos())  #What does this do?
        poison.clearstamp(
            poison_stamps[poison_index])  #Remove eaten food stamp
        poison_pos.pop(poison_index)  #Remove eaten food position
        poison_stamps.pop(poison_index)  #Remove eaten food stamp
        print("You have eaten the the poison lol!!")
        remove_tail()

    if snake.pos() in super_1_pos:
        snake.color(random.choice(snake_color))
        super_1_index = super_1_pos.index(snake.pos())  #What does this do?
        super_1.clearstamp(
            super_1_stamps[super_1_index])  #Remove eaten food stamp
        super_1_pos.pop(super_1_index)  #Remove eaten food position
        super_1_stamps.pop(super_1_index)  #Remove eaten food stamp
        print("You have eaten the  superfood!, good for you")
        print(new_stamp())
        print(new_stamp())
        print(new_stamp())
        print(new_stamp())
        print(new_stamp())
        TIME_STEP -= 10

    if len(pos_list) == 0:
        quit()

    #HINT: This if statement may be useful for Part 8

#Don't change the rest of the code in move_snake() function:
#If you have included the timer so the snake moves
#automatically, the function should finish as before with a
#call to ontimer()
    turtle.ontimer(move_snake, TIME_STEP)  #<--Last line of function
    #remove the last piece of the snake (Hint Functions are FUN!)
    print(remove_tail())
    if len(food_stamps) <= 5:

        make_food()
    if len(poison_stamps) <= 2:

        make_poison()
        remove_tail()
        TIME_STEP += 50

    if i % 5 == 0 and len(super_1_stamps) <= 0:

        super_1_food()
コード例 #44
0
def ShowTime():

    tim = datetime.today() # 今天的日期2018-01-11

    curr = datetime.now()  # 日期-时间(精确到微秒,小数点后6位) 如 2018-01-11 20:19:34.794000
    curr_hour = curr.hour
    curr_minute = curr.minute
    curr_second = curr.second

    # t.pencolor("black")

    # t.tracer(False) #不显示绘制的过程,直接显示绘制结果

    # 绘指针(时针和分针)
    # t.home()  # 回到起始状态
    # t.lt(90)  # 起始指向是12,即0点,此时角度是90度

    # t.rt(tim.hour * 30)  # 向右转的角度

    # hourPoint.setheading(curr_hour%12 * 30*-1+180)  #因为此版本没有使用logo模式,所以默认是逆时针旋转,所以需要乘以-1
    #或者用
    hourPoint.setheading(180-(curr_hour % 12 * 30 +30 / 60 * curr_minute))  # 因为此版本没有使用logo模式,所以默认是逆时针旋转,

    # 时针的粗细3 长度80
    # t.pensize(3)
    # t.pd()  # 落笔
    # t.fd(80)

    #-- makePoint("HourPoint",80,3,"black")

    # 分针
    # t.up()  # 起笔

    # t.home()  # 回到起始状态
    # t.lt(90)  # 起始指向是12,即0点,此时角度是90度

    # t.rt(tim.minute * 6)  # 向右转的角度

    # minPoint.setheading(curr_minute * 6*-1+180)#因为此版本没有使用logo模式,所以默认是逆时针旋转,所以需要乘以-1
    # 或者用
    minPoint.setheading(180-curr_minute * 6)  # 因为此版本没有使用logo模式,所以默认是逆时针旋转

    # 分针的粗细2 长度110
    # t.pensize(2)
    # t.pd()  # 落笔
    # t.fd(110)

    #-- makePoint("MinutePoint", 110, 2, "black")

    # 秒针
    # t.up()  # 起笔

    # t.pencolor("red")

    # t.home()  # 回到起始状态
    # t.lt(90)  # 起始指向是12,即0点,此时角度是90度

    # t.rt(tim.second * 6)  # 向右转的角度

    # secPoint.setheading(curr_second * 6*-1+180)#因为此版本没有使用logo模式,所以默认是逆时针旋转,所以需要乘以-1
    # 或者用
    secPoint.setheading(180-curr_second * 6)  # 因为此版本没有使用logo模式,所以默认是逆时针旋转

    # 秒针的粗细1 长度140
    # t.pensize(1)
    # t.pd()  # 落笔
    # t.fd(140)

    #-- makePoint("secondPoint", 110, 1, "red")

    # t.pu()  # 抬起笔


    t.tracer(False) # 不显示绘制的过程,直接显示绘制结果

    fontWriter.reset()  #重置笔  #方向和位置等状态也回到起始状态(所以fontWriter的隐藏状态又消失了)
    #reset后需要重新设置笔的光标的隐藏
    fontWriter.hideturtle()

    #与上面的相同实现的写法
    # fontWriter.clear() #清空笔的历史笔迹,方向和位置等状态不改变,笔的隐藏状态依旧存在,所以不用再写fontWriter.hideturtle()

    fontWriter.pu()  # 抬起笔


    # 写日期
    fontWriter.setx(0)
    fontWriter.sety(-50)
    # 定位到(0,-50)
    fontWriter.pd()  # 放下笔
    """
    turtle.write(s [,font=("font-name",font_size,"font_type")])
    """
    # t.write("2019 12 06",font=('Arial', 15, 'normal')) #默认从左边开始写
    fontWriter.write(Date(tim), align="center", font=("Courier", 15, "bold"))  #字体自动居中
    fontWriter.pu()  # 抬起笔

    # 写时间
    fontWriter.setx(0)
    fontWriter.sety(-70)
    # 定位到(0,-70)
    fontWriter.pd()  # 放下笔
    fontWriter.write(str(tim.hour) + ":" + str(tim.minute) + ":" + str(tim.second), align="center", font=("Courier", 15, "bold"))
    fontWriter.pu()  # 抬起笔

    # 写星期
    fontWriter.setx(0)
    fontWriter.sety(60)
    # 定位到(0,60)
    fontWriter.pd()  # 放下笔
    fontWriter.write(Week(tim), align="center", font=("Courier", 15, "bold"))
    fontWriter.pu()  # 抬起笔


    t.tracer(True)

    # 1000ms后继续调用tick ,即1秒
    t.ontimer(ShowTime, 100)
コード例 #45
0
def move_snake():
    my_pos = snake.pos()
    x_pos = my_pos[0]
    y_pos = my_pos[1]
    if direction == RIGHT:
        snake.goto(x_pos + SQUARE_SIZE, y_pos)
    elif direction == LEFT:
        snake.goto(x_pos - SQUARE_SIZE, y_pos)

    elif direction == UP:
        snake.goto(x_pos, y_pos + SQUARE_SIZE)
    elif direction == DOWN:
        snake.goto(x_pos, y_pos - SQUARE_SIZE)
    global food_stamps, food_pos, x

    if not snake.pos() in food_pos:
        my_pos = snake.pos()
        pos_list.append(my_pos)
        new_stamp = snake.stamp()
        stamp_list.append(new_stamp)
        old_stamp = stamp_list.pop(0)
        snake.clearstamp(old_stamp)
        pos_list.pop(0)
    elif snake.pos() in food_pos:
        my_pos = snake.pos()
        pos_list.append(my_pos)
        new_stamp = snake.stamp()
        stamp_list.append(new_stamp)
        food_ind = food_pos.index(snake.pos())
        food.clearstamp(food_stamps[food_ind])
        food_pos.pop(food_ind)
        food_stamps.pop(food_ind)
        print('you have eaten the food')
        make_food()
        x = x + 1
        score1.goto(0, 0)
        score1.clear()
        score1.write('SCORE:' + str(x), False, "left", ("Arial", 16, "normal"))
    else:
        food.clearstamp(food_stamps[food_ind])
        food_pos.pop(food_ind)
        food_stamps.pop(food_ind)
        print('you have eaten the food')
        make_food()

    new_pos = snake.pos()
    new_x_pos = new_pos[0]
    new_y_pos = new_pos[1]
    if new_x_pos >= RIGHT_EDGE:
        print('you hit the right edge!game over!')
        quit()
    elif new_x_pos <= LEFT_EDGE:
        print('you hit the left edge!game over!')
        quit()
    elif new_y_pos >= UP_EDGE:
        print('you hit the up edge!game over!')
        quit()
    elif new_y_pos <= DOWN_EDGE:
        print('you hit the down edge!game over!')
        quit()

    if new_pos in pos_list[0:-1]:
        print('you eat yourself!game over')
        quit()

    turtle.ontimer(move_snake, TIME_STEP)
コード例 #46
0
def move_snake():
    my_pos = snake.pos()
    x_pos = my_pos[0]
    y_pos = my_pos[1]
    new_pos = snake.pos()
    new_x_pos = new_pos[0]
    new_y_pos = new_pos[1]

    #4. Write the conditions for UP and DOWN on your own
    ##### YOUR CODE HERE

    if direction == RIGHT:
        snake.goto(x_pos + SQUARE_SIZE, y_pos)
        print("You moved right!")
    elif direction == LEFT:
        snake.goto(x_pos - SQUARE_SIZE, y_pos)
        print("You moved left!")
    elif direction == UP:
        snake.goto(x_pos, y_pos + SQUARE_SIZE)
        print("you moved up!")
    elif direction == DOWN:
        snake.goto(x_pos, y_pos - SQUARE_SIZE)
        print("you moved down!")
    if new_x_pos >= RIGHT_EDGE:
        print("You hit the right edge! Game over!")
        quit()
    elif new_y_pos >= TOP_EDGE:
        print("You hit the top edge! Game over!")
        quit()
    elif new_y_pos <= BOTTOM_EDGE:
        print("You hit the bottom edge! Game over!")
        quit()
    elif new_x_pos <= LEFT_EDGE:
        print("You hit the left edge! Game over!")
        quit()
    if snake.pos() in pos_list:
        print("you ate your self!")
        quit()
    ######## SPECIAL PLACE - Remember it for Part 5
    global food_stamps, food_pos
    #If snake is on top of food item
    if snake.pos() in food_pos:
        food_ind = food_pos.index(snake.pos())  #What does this do?
        food.clearstamp(food_stamps[food_ind])  #Remove eaten food
        #stamp
        food_pos.pop(food_ind)  #Remove eaten food position
        food_stamps.pop(food_ind)  #Remove eaten food stamp
        print("You have eaten the food!")
    else:
        old_stamp = stamp_list.pop(0)
        snake.clearstamp(old_stamp)
        pos_list.pop(0)
    if len(food_stamps) <= 6:
        make_food()

    #HINT: This if statement may be useful for Part 8

    ...
    #Don't change the rest of the code in move_snake() function:
    #If you have included the timer so the snake moves
    #automatically, the function should finish as before with a
    #call to ontimer()

    #Stamp new element and append new stamp in list
    #Remember: The snake position changed - update my_pos()

    my_pos = snake.pos()
    pos_list.append(my_pos)
    new_stamp = snake.stamp()
    stamp_list.append(new_stamp)

    ######## SPECIAL PLACE - Remember it for Part 5
    #pop zeroth element in pos_list to get rid of last the last
    #piece of the tail

    turtle.ontimer(move_snake, TIME_STEP)
コード例 #47
0
def move_snake():
    my_pos = snake.pos()
    x_pos = my_pos[0]
    y_pos = my_pos[1]

    if direction == RIGHT:
        snake.goto(x_pos + SQUARE_SIZE, y_pos)

    elif direction == LEFT:
        snake.goto(x_pos - SQUARE_SIZE, y_pos)

    elif direction == UP:
        snake.goto(x_pos, y_pos + SQUARE_SIZE)

    elif direction == DOWN:
        snake.goto(x_pos, y_pos - SQUARE_SIZE)
    #4. Write the conditions for UP and DOWN on your own
    ##### YOUR CODE HERE

    #Stamp new element and append new stamp in list
    #Remember: The snake position changed - update my_pos()

    my_pos = snake.pos()
    pos_list.append(my_pos)
    new_stamp = snake.stamp()
    stamp_list.append(new_stamp)
    ######## SPECIAL PLACE - Remember it for Part 5
    #pop zeroth element in pos_list to get rid of last the last
    #piece of the tail
    old_stamp = stamp_list.pop(0)
    snake.clearstamp(old_stamp)
    pos_list.pop(0)
    #Add new lines to the end of the function
    #Grab position of snake
    new_pos = snake.pos()
    new_x_pos = new_pos[0]
    new_y_pos = new_pos[1]

    # The next three lines check if the snake is hitting the
    # right edge.
    if new_x_pos >= RIGHT_EDGE:
        print('You hit the right edge! Game over!')
        quit()

    ######## SPECIAL PLACE - Remember it for Part 5
    global food_stamps, food_pos
    #If snake is on top of food item
    if snake.pos() in food_pos:
        food_ind = food_pos.index(snake.pos())  #What does this do?
        food.clearstamp(food_stamps[food_ind])  #Remove eaten food
        #stamp
        food_pos.pop(food_ind)  #Remove eaten food position
        food_stamps.pop(food_ind)  #Remove eaten food stamp
        print('You have eaten the food!')

    #HINT: This if statement may be useful for Part 8
    #Don't change the rest of the code in move_snake() function:
    #If you have included the timer so the snake moves
    #automatically, the function should finish as before with a
    #call to ontimer()
    if len(food_stamps) <= 6:
        make_food()
    turtle.ontimer(move_snake, 300)
コード例 #48
0
def move_snake():
    my_pos = snake.pos()
    x_pos = my_pos[0]
    y_pos = my_pos[1]
    
    if direction==RIGHT:
        snake.goto(x_pos + SQUARE_SIZE, y_pos)
        print("You moved right!")
    elif direction==LEFT:
        snake.goto(x_pos - SQUARE_SIZE, y_pos)
        print("You moved left!")
    elif direction==UP:
        snake.goto(x_pos, y_pos + SQUARE_SIZE)
        print("You moved left!")
    elif direction == DOWN:
        snake.goto(x_pos, y_pos - SQUARE_SIZE)

    new_pos = snake.pos()
    new_x_pos= new_pos[0]
    new_y_pos= new_pos[1]
    if new_x_pos >= RIGHT_EDGE:
        print("You hit the right edge! Game over!")
        line.write("Game over! you are a Loser!", align = "center", font = ("david" ,30, "normal"))
        time.sleep(3)
        quit()
    elif new_x_pos <= LEFT_EDGE:
        print("You hit the right edge! Game over!")
        line.write("Game over! you are a Loser!", align = "center", font = ("david" ,30, "normal"))
        time.sleep(3)
        quit()
    elif new_y_pos >= UP_EDGE:
        print("You hit the right edge! Game over!")
        line.write("Game over! you are a Loser!", align = "center", font = ("david" ,30, "normal"))
        time.sleep(3)
        quit()
    elif new_y_pos <= DOWN_EDGE:
        print("You hit the right edge! Game over!")
        line.write("Game over! you are a Loser!", align = "center", font = ("david" ,30, "normal"))
        time.sleep(3)
        quit()

    if snake.pos() in pos_list:
        line.write("Didn't your parents tell you not to eat yourself?!", align = "center", font = ("david" ,30, "normal"))
        time.sleep(3)
        quit()
        print("stupid you, didn't your parents tell you not to eat yourself?!!!")


    #4. Write the conditions for UP and DOWN on your own
    ##### YOUR CODE HERE

    #Stamp new element and append new stamp in list
    #Remember: The snake position changed - update my_pos()

    my_pos=snake.pos()
    pos_list.append(my_pos)
    new_stamp = snake.stamp()
    stamp_list.append(new_stamp)
    ######## SPECIAL PLACE - Remember it for Part 5
    global food_stamps, food_pos, score
    if snake.pos() in food_pos:
        food_ind=food_pos.index(snake.pos())
        food.clearstamp(food_stamps[food_ind])

        food_pos.pop(food_ind)
        food_stamps.pop(food_ind)
        print("you have eaten the food!")
        score = score+10
        print(score)
        scores.pendown()
        scores.clear()
        scores.write((score), align = "center", font = ("david", 20, "normal"))
        global TIME_STEP
        TIME_STEP = TIME_STEP-1
        
        
    elif snake.pos() in rock_pos:
        line.write("this is a rock, can't you see?", align = "center", font = ("david" ,30, "normal"))
        time.sleep(3)
        quit()
        
    else:
        old_stamp = stamp_list.pop(0)
        snake.clearstamp(old_stamp)
        pos_list.pop(0)

    if len (food_stamps) <=3:
        make_food()

    rock_generator = random.randint(0, 100)
    if rock_generator == 5:
        make_rock()
    turtle.ontimer(move_snake,TIME_STEP)
コード例 #49
0
def move_snake():
    my_pos = snake.pos()
    x_pos = my_pos[0]
    y_pos = my_pos[1]

    if direction == RIGHT:
        snake.goto(x_pos + SQUARE_SIZE, y_pos)
        print("you moved RIGHT!")
    elif direction == LEFT:
        snake.goto(x_pos - SQUARE_SIZE, y_pos)
        print("you moved LEFT!")

    elif direction == UP:
        snake.goto(x_pos, y_pos + SQUARE_SIZE)
        print("you moved UP!")
    else:
        snake.goto(x_pos, y_pos - SQUARE_SIZE)
        print("you moved DOWN!")

    new_pos = snake.pos()
    new_x_pos = new_pos[0]
    new_y_pos = new_pos[1]

    if new_x_pos >= RIGHT_EDGE:
        print("you hit the right edge! GAME OVER!")
        quit()

    elif new_x_pos <= LEFT_EDGE:
        print("you hit the left edge! GAME OVER!")
        quit()

    elif new_y_pos >= UP_EDGE:
        print("you hit the up edge! GAME OVER!")
        quit()

    elif new_y_pos <= DOWN_EDGE:
        print("you hit the down edge! GAME OVER!")
        quit()

    my_pos = snake.pos()
    pos_list.append(my_pos)
    new_stamp = snake.stamp()
    stamp_list.append(new_stamp)
    global food_stamps, food_pos
    if snake.pos() in food_pos:
        food_ind = food_pos.index(snake.pos())
        food.clearstamp(food_stamps[food_ind])
        food_pos.pop(food_ind)
        food_stamps.pop(food_ind)
        print("you have eaten the food!")
        make_food()
    else:
        old_stamp = stamp_list.pop(0)
        snake.clearstamp(old_stamp)
        pos_list.pop(0)

    if snake.pos() in pos_list[0:-1]:
        print("Game over!")
        quit()

    turtle.ontimer(move_snake, TIME_STEP)
コード例 #50
0
 def to_goal(self, goal):
     y = goal[1]
     while self.ycor() < y:
         turtle.ontimer(self.up(), t = 100)
     while self.ycor() > y:
         turtle.ontimer(self.down(), t = 100)
コード例 #51
0
ファイル: MazeGame.py プロジェクト: ps20alucas/python
#Set up the level
setup_maze(levels[1])

#Keyboard Binding
turtle.listen()
turtle.onkey(player.go_left, "Left")
turtle.onkey(player.go_right, "Right")
turtle.onkey(player.go_up, "Up")
turtle.onkey(player.go_down, "Down")

#Turn off screen up dates
wn.tracer(0)

#Start moving enemies
for enemy in enemies:
    turtle.ontimer(enemy.move, t=250)

#Main Game Loop
while True:
    #Check for player collision with treasure
    #Iterate through treasure list
    for treasure in treasures:
        if player.is_collision(treasure):
            #Add the treasure gold to the player gold
            player.gold += treasure.gold
            print ("Player Gold: {}".format(player.gold))
            #Destroy the treasure
            treasure.destroy()
            #Remove the treasure from the treasures list
            treasures.remove(treasure)
コード例 #52
0
    def move(self):

        if self.next == 'dairy':
            # change customer's color
            self.color("blue")
            #move to dairy area "m"
            self.goal = random.choice(dairy)
            self.to_hallway(self.goal)
            #set node to next
            self.node = self.next
            self.next = random.choices(['checkout','dairy','drinks','fruit','spices'],probability_dist.loc[self.node])[0]

        elif self.next == 'spices':
            # change customer's color
            self.color("red")
            #move to spices area "s"
            self.goal = random.choice(spices)
            self.to_hallway(self.goal)
            #set node to next
            self.node = self.next
            self.next = random.choices(['checkout','dairy','drinks','fruit','spices'],probability_dist.loc[self.node])[0]

        elif self.next == 'drinks':
            # change customer's color
            self.color("purple")
            #move to drinks area "d"
            self.goal = random.choice(drinks)
            self.to_hallway(self.goal)
            #set node to next
            self.node = self.next
            self.next = random.choices(['checkout','dairy','drinks','fruit','spices'],probability_dist.loc[self.node])[0]

        elif self.next == 'fruit':
            # change customer's color
            self.color("green")
            #move to fruit area "f"
            self.goal = random.choice(fruit)
            self.to_hallway(self.goal)
            #set node to next
            self.node = self.next
            self.next = random.choices(['checkout','dairy','drinks','fruit','spices'],probability_dist.loc[self.node])[0]

        elif self.next == 'checkout':
            # change customer's color
            self.color("pink")
            #move to checkout area "o"
            self.goal = random.choice(checkout)
            self.to_hallway(self.goal)

            self.goal = random.choice(exit)
            turtle.ontimer(self.down(), t = 100)

            self.along_hallway(self.goal)
            # set node to next
            self.node = self.goal
            # walk off screen
            for i in range(4):
                turtle.ontimer(self.down(), t = 100)
            self.next = None


            # self.next = random.choice(['dairy','spices','drinks','fruit','checkout'])

        else:
            # do nothing on exit
            pass
コード例 #53
0
 def perform_step():
     board.step()
     board.display()
     # In continuous mode, we set a timer to display another generation after 25 millisenconds.
     if board.continuous:
         turtle.ontimer(perform_step, 25)
コード例 #54
0
def move_snake():
    global direction
    my_pos = snake.pos()
    x_pos= my_pos[0]
    y_pos= my_pos[1]
    if direction == RIGHT:
        snake.goto(x_pos + SQUARE_SIZE, y_pos)
        print("You moved right!")
    elif direction == LEFT:
        snake.goto(x_pos - SQUARE_SIZE, y_pos)
        print("You moved left")
    elif direction == UP:
        snake.goto(x_pos, y_pos + SQUARE_SIZE)
    elif direction == DOWN:
        snake.goto(x_pos, y_pos - SQUARE_SIZE)
        
    new_pos = snake.pos()
    new_x_pos = new_pos[0]
    new_y_pos = new_pos[1]
    
    if new_x_pos >= RIGHT_EDGE:
        print ("You hit the right edge! Game over!")
        quit()
    if new_x_pos <= LEFT_EDGE:
        print ("You hit the left edge! Game over!")
        quit()
    if new_y_pos >= UP_EDGE:
        print ("You hit the up edge! Game over!")
        quit()
    if new_y_pos <= DOWN_EDGE:
        print ("You hit the down edge! Game over!")
        quit()
    if new_pos in pos_list[:-1]:
        print("You die! Game over")
        quit()
       
    my_pos=snake.pos()
    pos_list.append(my_pos)
    #pos_list.pop(0)
    new_stamp = snake.stamp()
    stamp_list.append(new_stamp)
    global food_stamps , food_pos,x
    if snake.pos() in food_pos:
        food_ind = food_pos.index (snake.pos())
        food.clearstamp (food_stamps[food_ind])
        food_pos.pop(food_ind)
        food_stamps.pop(food_ind)
        print("You have eaten the food!")
        make_food()
        stamp_list.append(new_stamp)
        pos_list.append(snake.pos())
        x=x+1
        score.clear()
        score.write ("score: " + str(x))
        
    else:
        old_stamp=stamp_list.pop(0)
        snake.clearstamp(old_stamp)
        pos_list.pop(0)
        
            
        

    turtle.ontimer(move_snake,TIME_STEP)
コード例 #55
0
def move_snake1():

    global direction1
    my_pos1 = snake1.pos()
    x_pos1 = my_pos1[0]
    y_pos1 = my_pos1[1]

    if direction1 == RIGHT1:
        print("player2 is moving")
        snake1.goto(x_pos1 + square_size, y_pos1)
        print("You moved right!")
    elif direction1 == LEFT1:
        snake1.goto(x_pos1 - square_size, y_pos1)
        print("You moved left!")
    elif direction1 == UP1:
        snake1.goto(x_pos1, y_pos1 + square_size)
        print("You moved up!")
    elif direction1 == DOWN1:
        snake1.goto(x_pos1, y_pos1 - square_size)
        print("You moved down!")

    # stamp and record the snake's head
    my_pos1 = snake1.pos()
    pos_list1.append(my_pos1)
    new_stamp1 = snake1.stamp()
    stamp_list1.append(new_stamp1)

    # if the snake is eating food
    if snake1.pos() in food_pos:
        food_ind1 = food_pos.index(snake1.pos())
        food.clearstamp(food_stamps[food_ind1])
        food_pos.pop(food_ind1)
        score1.append(food_ind1)
        food_stamps.pop(food_ind1)
        print("You have eaten a food!")
        make_food()
        turtle1.clear()
        turtle1.goto(-200, 200)
        turtle1.color("green")
        turtle1.write(len(score1), font=("Arial", 30), align="center")
        turtle1.goto(-300, 0)
    else:
        # cleartsamps the tail and makes storage edits
        old_stamp1 = stamp_list1.pop(0)
        snake1.clearstamp(old_stamp1)
        pos_list1.pop(0)

    new_pos1 = snake1.pos()
    new_x_pos1 = new_pos1[0]
    new_y_pos1 = new_pos1[1]

    if new_x_pos1 >= RIGHT_EDGE:
        turtle.goto(0, 0)
        turtle.color("green")
        turtle.write("The green snake hit the right edge! game over!",
                     font=("Ariel", 30),
                     align="center")
        time.sleep(2)
        quit()

    elif new_x_pos1 <= LEFT_EDGE:
        turtle.goto(0, 0)
        turtle.color("green")
        turtle.write("The green snake hit the left edge! game over!",
                     font=("Ariel", 30),
                     align="center")
        time.sleep(2)
        quit()

    elif new_y_pos1 >= UP_EDGE:
        turtle.goto(0, 0)
        turtle.color("green")
        turtle.write("The green snake hit the up edge! game over!",
                     font=("Ariel", 30),
                     align="center")
        time.sleep(2)
        quit()

    elif new_y_pos1 <= DOWN_EDGE:
        turtle.goto(0, 0)
        turtle.color("green")
        turtle.write("The green snake hit the down edge! game over!",
                     font=("Ariel", 30),
                     align="center")
        time.sleep(2)
        quit(pos_list)

    if pos_list1[-1] in pos_list1[0:-1]:
        turtle.goto(0, 0)
        turtle.color("green")
        turtle.write("The green snake hit himself!",
                     font=("Ariel", 30),
                     align="center")
        time.sleep(2)
        quit()

    turtle.ontimer(move_snake1, TIME_STEP1)
コード例 #56
0
ファイル: gif.py プロジェクト: Ackeraa/rabit
 def run(self):
     print('Begin to draw and Capturing pictures...')
     self.__save()
     turtle.ontimer(self.__draw, 500)
     turtle.done()
コード例 #57
0
ファイル: gif.py プロジェクト: Ackeraa/rabit
 def __draw(self):
     turtle.hideturtle()
     self.__func()
     turtle.ontimer(self.__stop, 500)
     turtle.down()
コード例 #58
0
def tekrar():
    print(leftC)
    if (leftC):
        player1.setx(player1.xcor() - p_speed)
    if (rightC):
        player1.setx(player1.xcor() + p_speed)
    if (leftC2):
        player2.setx(player2.xcor() - p_speed)
    if (rightC2):
        player2.setx(player2.xcor() + p_speed)

    if (p1bullet.ycor() < 330):
        p1bullet.sety(p1bullet.ycor() + 40)
    else:
        if (p1bullet.xcor() - player2.xcor() < 20
                and p1bullet.xcor() - player2.xcor() > -20
                and p1bullet.isvisible()):
            #p2 mermi yedi
            border.clear()
            line1.clear()
            player1.ht()
            player2.ht()
            p1bullet.ht()
            p2bullet.ht()
            turtle.color("blue")
            turtle.write("GAME OVER BLUE TURTLE WON!",
                         align="center",
                         font=("Arial", 26, "normal"))
            time.sleep(3)
            turtle.bye()
        else:
            p1bullet.ht()
    if (p2bullet.ycor() > -330):
        p2bullet.sety(p2bullet.ycor() - 40)
    else:
        if (p2bullet.xcor() - player1.xcor() < 20
                and p2bullet.xcor() - player1.xcor() > -20
                and p2bullet.isvisible()):
            #p1 mermi yedi
            border.clear()
            line1.clear()
            player1.ht()
            player2.ht()
            p1bullet.ht()
            p2bullet.ht()
            turtle.color("red")
            turtle.write("GAME OVER RED TURTLE WON!",
                         align="center",
                         font=("Arial", 26, "normal"))
            time.sleep(3)
            turtle.bye()
        else:
            p2bullet.ht()
    if not (-350 < player2.xcor() < 350):
        border.clear()
        line1.clear()
        player1.ht()
        player2.ht()
        p1bullet.ht()
        p2bullet.ht()
        turtle.color("BLUE")
        turtle.write("GAME OVER RED TURTLE HAS GONE OUT OF FRAME!",
                     align="center",
                     font=("Arial", 20, "normal"))
        turtle.ht()
        time.sleep(3)
        turtle.bye()
    if not (-350 < player1.xcor() < 350):
        border.clear()
        line1.clear()
        player1.ht()
        player2.ht()
        p1bullet.ht()
        p2bullet.ht()
        turtle.color("red")
        turtle.write("GAME OVER BLUE TURTLE HAS GONE OUT OF FRAME!",
                     align="center",
                     font=("Arial", 20, "normal"))
        turtle.ht()
        time.sleep(3)
        turtle.bye()
    turtle.ontimer(tekrar, 1)
コード例 #59
0
def falling_food():
    global food_delay, m, n, delay_num
    food_destroy = []
    eaten_food = []
    for food in food_list:
        x_pos = food.pos()[0]
        y_pos = food.pos()[1]
        if y_pos >= bottom:
            y_pos = y_pos - step
            food.goto(x_pos,y_pos)
            boat_x = catcher.pos()[0]
            boat_y = catcher.pos()[1]
            if (x_pos >=  boat_x - 50 ) and (x_pos <=  boat_x + 50 ) and (y_pos >=  boat_y - 50 ) and (y_pos <=  boat_y + 20 ):
                ind = food_list.index(food)
                eaten_food.append(ind)
        else:
            ind = food_list.index(food)
            food_destroy.append(ind)

    for ind in food_destroy:
        old_food = food_list.pop(ind)
        old_food.hideturtle()
        del old_food
        m=m+1
        turtle_drops.clear()
        turtle_drops.write('drops: '+str(m), font=('Arial',30,('bold','italic')))

    for ind in eaten_food:
        old_food = food_list.pop(ind)
        old_food.hideturtle()
        del old_food
        n=n+1
        turtle_score.clear()
        turtle_score.write("score:"+str(n),font=("Arial",30,("bold","italic")) )
        #after score=25 food falls faster
        if n==25:
            delay_num = 5
            fast_turtle.write('Now faster!', font=('Arial',30,('bold')))
            time.sleep(1)
            fast_turtle.clear()
        if n==40:
            delay_num = 3
            fast_turtle.hideturtle()
            fast_turtle.penup()
            fast_turtle.goto(-70,0)
            fast_turtle.write('Now super fast!', font=('Arial',30,('bold')))
            time.sleep(1)
            fast_turtle.clear()
        if n==50:
            delay_num = 2
            fast_turtle.hideturtle()
            fast_turtle.penup()
            fast_turtle.goto(-70,0)
            fast_turtle.write('extremely fast!!', font=('Arial',30,('bold')))
            time.sleep(1)
            fast_turtle.clear()
    if food_delay <= delay_num:
        food_delay += 1
    else:
        food_delay = 0
        create_food()

    if m == 5:
        print('game over!')
        turtle.write('game over!',font=('Arial',30,('bold')))
        time.sleep(3)
        print ('you droped 5!')
        quit()

    #falling trash
    global trash_delay, delay_num_t, trash_list
    for trash in trash_list:
        x_pos = trash.pos()[0]
        y_pos = trash.pos()[1]
        if y_pos >= bottom:
            y_pos = y_pos - step
            trash.goto(x_pos,y_pos)
            boat_x = catcher.pos()[0]
            boat_y = catcher.pos()[1]
            if (x_pos >=  boat_x - 50 ) and (x_pos <=  boat_x + 50 ) and (y_pos >=  boat_y - 50 ) and (y_pos <=  boat_y + 20 ):
                turtle.write('game over!',font=('Arial',30,('bold')))
                time.sleep(3)
                quit()
        else:
            trash.hideturtle()
            
    if  trash_delay <= delay_num_t:
        trash_delay += 1
    else:
        trash_delay = 0
        create_trash()
##    create_trash()

    turtle.ontimer(falling_food,100)
コード例 #60
0
turtle.listen()
turtle.onkey(player.lt, "Left")
turtle.onkey(player.rt, "Right")
turtle.onkey(player.up, "Up")
turtle.onkey(player.dn, "Down")

turtle.onkey(player.lt, "a")
turtle.onkey(player.rt, "d")
turtle.onkey(player.up, "w")
turtle.onkey(player.dn, "s")

window.tracer(0)

for monster in monsters:
    turtle.ontimer(monster.move, t=250)

loop = True
try:
    while (loop is True):
        for treasure in treasures:
            if player.collision(treasure):
                player.score += treasure.value
                print("Player gold pieces: {}".format(player.score))
                treasure.dispose()
                treasures.remove(treasure)

        for monster in monsters:
            if player.collision(monster):
                print "You died a horrible death " \
                    "at the hands of a {}!".format(monster.type)