Когда я сталкиваюсь с двумя черепахами, Python зависает и падает - PullRequest
0 голосов
/ 10 февраля 2019
import turtle
import os
import math

ms = turtle.Screen()
ms.bgcolor("grey")
ms.title("ok")

ground = turtle.Turtle()
ground.speed(0)
ground.color("black")
ground.penup()
ground.setposition(-500, -500)
ground.shape("square")
ground.shapesize(20, 200)

player = turtle.Turtle()
player.shape("square")
player.color("blue")
player.penup()
player.speed(0)
player.setposition(-450, -280)

playerspeed = 15

prop = turtle.Turtle()
prop.speed(0)
prop.shape("square")
prop.penup()
prop.color("red")
prop.setposition(-200, -50)

def move_left():
    x = player.xcor()
    x-= playerspeed
    if x <-460:
        x = - 460
    player.setx(x)

def move_right():
    x = player.xcor()
    x+= playerspeed
    if x >460:
        x =  460
    player.setx(x)

def move_down():
    y = player.ycor()
    y-= playerspeed
    if y <-290:
        y = - 290
    player.sety(y)

def move_up():
    y = player.ycor()
    y+= playerspeed
    if y >290:
        y =  290
    player.sety(y)

turtle.listen()
turtle.onkey(move_left, "Left")
turtle.onkey(move_right, "Right")
turtle.onkey(move_up, "Up")
turtle.onkey(move_down, "Down")

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

while True:
    if isCollision(player, prop):
        player.setposition(100, 100)

Если я изменю расстояние на > 10, оно будет работать, но не так, как я хочу.Я хочу изменить положение player, когда prop и player находятся на расстоянии 10 пикселей или меньше друг от друга.Я перепробовал большинство вещей, о которых знаю, но я все еще новичок в Python или любом другом языке программирования.

Но я не знаю, что может привести к его зависанию и падению - любая помощь приветствуется.

1 Ответ

0 голосов
/ 10 февраля 2019

Основная проблема с вашим кодом, которую я вижу, - while True:, которую не следует использовать в среде, основанной на событиях.Создав плотный цикл, вы можете предотвратить обработку событий (нажатие клавиши, перемещение курсора, закрытие окна).

Ниже приведена переделка кода с использованием события таймера вместо while True:.Я также параметризовал его, так как каждый пользователь черепахи видит окно по умолчанию другого размера в зависимости от размеров своего экрана.Поэтому вам нужно либо использовать setup() для принудительного использования окна фиксированного размера, либо настроить свой код на размер окна.Теперь он подстраивается под размер окна.Я также заставил prop переместиться в случайное место при столкновении, чтобы сделать игру более увлекательной для меня.И я бросил твой код расстояния в пользу собственной реализации turtle:

from turtle import Screen, Turtle, mainloop
from random import randint

PLAYER_SPEED = 15
GROUND_HEIGHT = 100
PROXIMITY = 10
CURSOR_SIZE = 20

def move_left():
    x = player.xcor() - PLAYER_SPEED

    if x < CURSOR_SIZE - width/2:
        x = CURSOR_SIZE - width/2

    player.setx(x)

def move_right():
    x = player.xcor() + PLAYER_SPEED

    if x > width/2 - CURSOR_SIZE:
        x = width/2 - CURSOR_SIZE

    player.setx(x)

def move_down():
    y = player.ycor() - PLAYER_SPEED

    if y < CURSOR_SIZE/2 + GROUND_HEIGHT - height/2:
        y = CURSOR_SIZE/2 + GROUND_HEIGHT - height/2

    player.sety(y)

def move_up():
    y = player.ycor() + PLAYER_SPEED

    if y > height/2 - CURSOR_SIZE:
        y = height/2 - CURSOR_SIZE

    player.sety(y)

def isCollision(t1, t2):
    return t1.distance(t2) < PROXIMITY

def random_position():
    x = randint(CURSOR_SIZE - width//2, width//2 - CURSOR_SIZE)
    y = randint(CURSOR_SIZE + GROUND_HEIGHT - height//2, height//2 - CURSOR_SIZE)

    return x, y

def check():
    if isCollision(player, prop):
        prop.setposition(random_position())

    ms.ontimer(check, 100)

ms = Screen()
ms.bgcolor('grey')
ms.title("ok")

width, height = ms.window_width(), ms.window_height()

ground = Turtle('square')
ground.shapesize(GROUND_HEIGHT / CURSOR_SIZE, width / CURSOR_SIZE)
ground.speed('fastest')
ground.penup()
ground.sety(GROUND_HEIGHT/2 - height/2)

player = Turtle('square')
player.speed('fastest')
player.color('blue')
player.penup()
player.setposition(CURSOR_SIZE/2 - width/2, GROUND_HEIGHT + CURSOR_SIZE/2 - height/2)

prop = Turtle('square')
prop.speed('fastest')
prop.color('red')
prop.penup()
prop.setposition(random_position())

ms.onkey(move_left, 'Left')
ms.onkey(move_right, 'Right')
ms.onkey(move_up, 'Up')
ms.onkey(move_down, 'Down')
ms.listen()

check()

mainloop()
...