Основная проблема с вашим кодом, которую я вижу, - 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()