Advertisement
sriyanto

main

Feb 10th, 2024 (edited)
849
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.12 KB | None | 0 0
  1. #Main game loop
  2. running = True
  3. while running:
  4.     screen.fill(WHITE)
  5.  
  6.     # Event handling
  7.     for event in pygame.event.get():
  8.         if event.type == pygame.QUIT:
  9.             running = False
  10.  
  11.     # Player control
  12.     keys = pygame.key.get_pressed()
  13.     if keys[pygame.K_LEFT]:
  14.         car_x -= car_speed
  15.     if keys[pygame.K_RIGHT]:
  16.         car_x += car_speed
  17.  
  18.     # Boundary checking for player car
  19.     if car_x < 0:
  20.         car_x = 0
  21.     elif car_x > WIDTH - car_width:
  22.         car_x = WIDTH - car_width
  23.  
  24.     # Generate obstacles
  25.     if random.randrange(0, 100) < obstacle_frequency:
  26.         obstacle_x = random.randrange(0, WIDTH - obstacle_width)
  27.         obstacle_y = -obstacle_height
  28.         obstacles.append([obstacle_x, obstacle_y])
  29.  
  30.     # Generate coins
  31.     if random.randrange(0, 100) < coin_frequency:
  32.         coin_x = random.randrange(0, WIDTH - coin_width)
  33.         coin_y = -coin_height
  34.         coins.append([coin_x, coin_y])
  35.  
  36.     # Move obstacles and coins
  37.     for obstacle in obstacles:
  38.         obstacle[1] += obstacle_speed
  39.         screen.blit(obstacle_img, (obstacle[0], obstacle[1]))
  40.         if obstacle[1] > HEIGHT:
  41.             obstacles.remove(obstacle)
  42.             score -= 10
  43.  
  44.     for coin in coins:
  45.         coin[1] += obstacle_speed
  46.         screen.blit(coin_img, (coin[0], coin[1]))
  47.         if coin[1] > HEIGHT:
  48.             coins.remove(coin)
  49.  
  50.     # Collision detection
  51.     car_rect = pygame.Rect(car_x, car_y, car_width, car_height)
  52.     for obstacle in obstacles:
  53.         obstacle_rect = pygame.Rect(obstacle[0], obstacle[1], obstacle_width, obstacle_height)
  54.         if car_rect.colliderect(obstacle_rect):
  55.             obstacles.remove(obstacle)
  56.             score -= 50
  57.  
  58.     for coin in coins:
  59.         coin_rect = pygame.Rect(coin[0], coin[1], coin_width, coin_height)
  60.         if car_rect.colliderect(coin_rect):
  61.             coins.remove(coin)
  62.             score += 10
  63.  
  64.     # Display score
  65.     display_text("Score: " + str(score), BLACK, 10, 10)
  66.  
  67.     # Draw player car
  68.     screen.blit(car_img, (car_x, car_y))
  69.  
  70.     pygame.display.flip()
  71.     clock.tick(60)
  72.  
  73. pygame.quit()
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement