import random
import math
import pygame
# Define constants
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
ROBOT_RADIUS = 20
MAX_SPEED = 5
# Initialize pygame
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
class Robot:
def __init__(self):
self.x = SCREEN_WIDTH/2
self.y = SCREEN_HEIGHT/2
self.heading = 0
self.velocity = 0
def drive(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
self.velocity = MAX_SPEED
elif keys[pygame.K_DOWN]:
self.velocity = -MAX_SPEED
else:
if self.velocity > 0:
self.velocity -= 0.05
elif self.velocity < 0:
self.velocity += 0.05
self.x += math.cos(self.heading) * self.velocity
self.y += math.sin(self.heading) * self.velocity
def turn(self, direction):
self.heading += direction * 0.1
robot = Robot()
obstacles = []
for i in range(5):
x = random.randint(0, SCREEN_WIDTH)
y = random.randint(0, SCREEN_HEIGHT)
obstacles.append((x,y))
running = True
while running:
# Draw obstacles
for o in obstacles:
pygame.draw.circle(screen, (255,0,0), o, 20)
# Draw robot
pygame.draw.circle(screen, (0,0,255), (robot.x, robot.y), ROBOT_RADIUS)
# Robot movement
robot.drive()
# Check for obstacle collision
for o in obstacles:
dist = math.sqrt((robot.x-o[0])**2 + (robot.y-o[1])**2)
if dist < ROBOT_RADIUS+20:
robot.turn(1)
# Exit button
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip()
pygame.quit()