The car is moving straight. When it hits the window edge it moves backwards then changes direction at an angle of 45 degrees clockwise and keeps moving straight. if it hit the edge of the window again, it would do the same
I've made the code below. I was only able to stop and reverse the car when it hits the edge of the window. How to change the direction of the car, make it go straight, and keep the program running and it will only stop if we close the window?
import pygame, sys
from pygame.locals import *
def base(cX,cY):
screen.fill(whitdull)
pygame.draw.rect(screen,whitdull,[0,0,1050,600],4)
screen.blit(text1,[150,230])
# Copy image to screen:
screen.blit(player_image, [cX,cY])
pygame.display.flip()
clock.tick(ct)
def carMovement(b0XX,b0YY,bDirection):
sX = 5 # 5 pixel/clock Direction right-left
sY = 5 # 5 pixel/clock Direction upward-downward
while True:
# Direction to the right
pX = sX
pY = 0
b0XX = b0XX + pX
b0YY = b0YY + pY
if b0XX == 970:
b0XX = 970 - sX
backward(b0XX,b0YY,Direction)
# Copy image to screen:
base(b0XX,b0YY)
return b0XX,b0YY
def backward(b0XX,b0YY,bDirection):
sX = 5 # 5 pixel/clock Direction right-left
sY = 5 # 5 pixel/clock Direction upward-downward
while b0XX >= 900:
# Direction to the right
pX = sX
pY = 0
b0XX = b0XX - pX
b0YY = b0YY - pY
if b0XX == 900:
b0XX = 900 + sX
base(b0XX,b0YY)
return b0XX, b0YY
# Initialize Pygame
pygame.init()
# Define some colors
white=(250,250,250); whitdull=(247,247,247)
black=(70,70,70) ; blue =(45,127,184)
gold =(248,179,35); green=(0,176,80)
yellow=(254,240,11); gray=(208,206,206)
#Setting font-size
font1 = pygame.font.Font(None,150)
text1 = font1.render("Bom-bom Car",True,white)
# preparing the screen
width = 1050 ; height = 600
screen = pygame.display.set_mode([width, height])
pygame.display.set_caption('Bom-bom Car')
screen.fill(whitdull)
player_image = pygame.image.load("Car-2.jpeg").convert()
#rotasi = pygame.transform.rotate(player_image, -45)
#initial condition
b0X = 0; b0Y = 250; Direction = 2 # initial car position, Direction 2 = to the right
ct = 20
clock = pygame.time.Clock()
# program utama Pygame
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
b0X,b0Y = carMovement(b0X,b0Y,Direction)
base(b0X,b0Y)
# Get the current mouse position (x,y)
player_position = pygame.mouse.get_pos()
xm=player_position[0]
ym=player_position[1]
#end program