J
J
Jungles2020-07-19 14:17:25
Python
Jungles, 2020-07-19 14:17:25

Where is the bug in turtle?

import turtle
from random import randint
from random import choice
window = turtle.Screen()
#border - граница
border = turtle.Turtle()
border.speed(0)
border.up()
border.goto(200,200)
border.down()
border.color('blue')
border.pensize(5)
border.hideturtle()
border.goto(200,-200)
border.goto(-200,-200)
border.goto(-200,200)
border.goto(200,200)

bub_id = []
bub_spd = []

def create_ball():
    ball = turtle.Turtle()
    ball.hideturtle()
    ball.color(choice(['green','yellow','blue']))
    ball.shape('circle')
    ball.up()
    y_range = randint(-185,185)
    x_range = randint(-185,185)
    ball.goto(x_range,y_range)
    ball.showturtle()
    dx = randint(2,3)
    dy = randint(2,3)
    bub_spd.append([dx,dy])
    bub_id.append(ball)
n = 0
while True:
    n+=1
    if n < 2:
       create_ball()
    for i in range(len(bub_id)):
        a = bub_id[i].position()
        x= a[0]
        y= a[1]
        dx = bub_spd[i][0]
        dy = bub_spd[i][1]
        if (x + dx) > 195 or (x+dx) < -195:
            dx = -dx
        if (y + dy) > 195 or (y + dy) < -195:
            dy = -dy
        bub_id[i].goto(x+dx,y+dy)
window.mainloop()

For some reason, the first ball, instead of changing direction upon collision, begins to behave inappropriately. And as a result, it is "attracted" to the corner

, here is the code that shows the idea of ​​​​the game
import turtle
window = turtle.Screen()

border = turtle.Pen()
border.speed(0)
border.up()
border.hideturtle()
border.pensize(5)
border.color(randomcolor())
border.goto(300,300)
border.down()
border.goto(300,-300)
border.goto(-300,-300)
border.goto(-300,300)
border.goto(300,300)

ball = turtle.Pen()
ball.shape("circle")
ball.up()
dx = 2
dy = 23
while True:
    x,y = ball.position()
    if x+dx>=300 or  x+dx<=-300:
        dx = -dx
    if y+dy>=300 or  y+dy<=-300:
        dy = -dy
    ball.goto(x+dx,y+dy)
window.mainloop()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kozhevin, 2020-07-19
@Jungles

Do not save new ball coordinates

while True:
    n+=1
    if n < 2:
       create_ball()
    for i in range(len(bub_id)):
        a = bub_id[i].position()
        x= a[0]
        y= a[1]
        dx = bub_spd[i][0]
        dy = bub_spd[i][1]
        if (x + dx) > 195 or (x+dx) < -195:
            dx = -dx
        if (y + dy) > 195 or (y + dy) < -195:
            dy = -dy
#
        bub_spd[i][0] = dx
        bub_spd[i][1] = dy
#
        bub_id[i].goto(x+dx,y+dy)
window.mainloop()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question