Square Bounce Simulation
Square Simulation
This project contains a square simulation developed using Python and Pygame. The square is placed at a random starting position on a track and moves at a specific speed. When the square hits the edges of the track, it changes its direction.
Installation
Clone or download this project to your computer:
1
git clone https://github.com/AhmetBeratKocyigit/Kare-Simulasyonu
To install the Pygame library, use the following command:
1
pip install pygame
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import pygame
import sys
import random
import math
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
SIDE_LENGTH = 50
WIDTH = 600
HEIGHT = 400
SPEED = 10
def draw_course(screen):
screen.fill(WHITE)
pygame.draw.rect(screen, BLACK, (50, 50, WIDTH - 100, HEIGHT - 100), 2)
def draw_square(screen, x, y):
pygame.draw.rect(screen, BLACK, (x, y, SIDE_LENGTH, SIDE_LENGTH))
# Kareyi hareket ettirme
def move_square(x, y, angle):
angle %= 360
rad = math.radians(angle)
x += SPEED * math.cos(rad)
y -= SPEED * math.sin(rad)
return x, y
def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Kare Simülasyonu")
clock = pygame.time.Clock()
x = random.randint(50, WIDTH - SIDE_LENGTH - 50)
y = random.randint(50, HEIGHT - SIDE_LENGTH - 50)
angle = random.randint(0, 359)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
x, y = move_square(x, y, angle)
if x <= 50 or x >= WIDTH - SIDE_LENGTH - 50 or y <= 50 or y >= HEIGHT - SIDE_LENGTH - 50:
if x <= 50:
if 180 <= angle <= 270:
angle = 180 - angle
else:
angle = 540 - angle
elif x >= WIDTH - SIDE_LENGTH - 50:
if 0 <= angle <= 90:
angle = 180 - angle
else:
angle = 540 - angle
elif y <= 50:
angle = 360 - angle
elif y >= HEIGHT - SIDE_LENGTH - 50:
angle = 360 - angle
screen.fill(WHITE)
draw_course(screen)
draw_square(screen, x, y)
pygame.display.flip()
clock.tick(30)
if __name__ == "__main__":
main()
The square simulation will start. The square will begin at a random position within the track and will move at a specific speed. When the square hits the edges of the track, it will change its direction.
Features
- The square is placed in a random position.
- The square moves at a specific speed.
- The square changes direction when it hits the edges of the track.
This post is licensed under CC BY 4.0 by the author.