I was learning python turtle module.
And I was trying to make a simple pong game.
Here is the code:
import turtle
import win32api
wind = turtle.Screen()
wind.title("Pong game")
wind.bgcolor("black")
wind.setup(width=800, height=500)
wind.tracer(0) # stops window from updating automaticly
# racket1
racket1 = turtle.Turtle()
racket1.speed(0)
racket1.penup()
racket1.color("blue")
racket1.shape("square")
racket1.goto(-370, 0)
racket1.shapesize(stretch_wid=5, stretch_len=1)
# racket2
racket2 = turtle.Turtle()
racket2.speed(0)
racket2.penup()
racket2.color("red")
racket2.shape("square")
racket2.goto(370, 0)
racket2.shapesize(stretch_wid=5, stretch_len=1)
# ball
ball = turtle.Turtle()
ball.speed(0)
ball.penup()
ball.color("white")
ball.shape("circle")
ball.goto(0, 0)
ball.dx = 0.2
ball.dy = 0.2
# score writer
scw = turtle.Turtle()
scw.penup()
scw.speed(0)
scw.hideturtle()
scw.goto(0, 210)
scw.color("white")
scw.write("Blue: 0 Red: 0", font=("Arial", 24, "bold"), align="center")
# racket 1 functions
def racket1_up():
y = racket1.ycor()
if y < 200:
y += 0.3
racket1.sety(y)
def racket1_down():
y = racket1.ycor()
if y > -200:
y -= 0.3
racket1.sety(y)
# racket 2 functions
def racket2_up():
y = racket2.ycor()
if y < 200:
y += 0.3
racket2.sety(y)
def racket2_down():
y = racket2.ycor()
if y > -200:
y -= 0.3
racket2.sety(y)
# scores
p1 = 0
p2 = 0
while True:
wind.update()
# ball move
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
# border check
if ball.ycor() > 239: #240
ball.dy *= -1
if ball.ycor() < -239: #-240
ball.dy *= -1
if ball.xcor() > 389: #390
ball.goto(0, 0)
p1 += 1
ball.dx *= -1
scw.clear()
scw.write(f"Blue: {p1} Red: {p2}", font=("Arial", 24, "bold"), align="center")
if ball.xcor() < -389: #-390
ball.goto(0, 0)
p2 += 1
ball.dx *= -1
scw.clear()
scw.write(f"Blue: {p1} Red: {p2}", font=("Arial", 24, "bold"), align="center")
# ball and madareb collision
if ball.xcor() > 350 and ball.ycor() < racket2.ycor()+60 and ball.ycor() > racket2.ycor()-60:
ball.dx *= -1
if ball.xcor() < -350 and ball.ycor() < racket1.ycor()+60 and ball.ycor() > racket1.ycor()-60:
ball.dx *= -1
# racket 1 movement
w = win32api.GetKeyState(0x57)
s = win32api.GetKeyState(0x53)
if w < 0:
racket1_up()
if s < 0:
racket1_down()
# racket 2 movement
u = win32api.GetKeyState(0x26)
d = win32api.GetKeyState(0x28)
if u < 0:
racket2_up()
if d < 0:
racket2_down()
The game worked properly but the ball speed changes, I think that this is due to the change of the processing speed changes.
So is it possible to make the speed not change with the changing of the processing speed?