Jump to content

Coding

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 2409:40d4:4047:6d05:8000:: (talk) at 14:51, 2 December 2024. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Coding may refer to:import pygame import sys import random

  1. Initialize Pygame

pygame.init()

  1. Screen dimensions

SCREEN_WIDTH = 400 SCREEN_HEIGHT = 600 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) clock = pygame.time.Clock()

  1. Colors

WHITE = (255, 255, 255) BLACK = (0, 0, 0) GREEN = (0, 255, 0)

  1. Game Variables

gravity = 0.5 bird_movement = 0 bird_rect = pygame.Rect(50, 300, 30, 30) # (x, y, width, height)

  1. Pipes

pipe_width = 50 pipe_height = 300 pipe_gap = 150 pipe_list = [] pipe_timer = pygame.USEREVENT pygame.time.set_timer(pipe_timer, 1200)

  1. Score

score = 0

def create_pipe():

   height = random.randint(150, SCREEN_HEIGHT - pipe_gap - 150)
   bottom_pipe = pygame.Rect(SCREEN_WIDTH, height + pipe_gap, pipe_width, SCREEN_HEIGHT)
   top_pipe = pygame.Rect(SCREEN_WIDTH, height - pipe_height, pipe_width, SCREEN_HEIGHT)
   return bottom_pipe, top_pipe

def move_pipes(pipes):

   for pipe in pipes:
       pipe.centerx -= 5
   return [pipe for pipe in pipes if pipe.right > 0]

def draw_pipes(pipes):

   for pipe in pipes:
       pygame.draw.rect(screen, GREEN, pipe)

def check_collision(pipes):

   for pipe in pipes:
       if bird_rect.colliderect(pipe):
           return True
   if bird_rect.top <= 0 or bird_rect.bottom >= SCREEN_HEIGHT:
       return True
   return False

def display_score():

   font = pygame.font.Font(None, 36)
   text = font.render(f"Score: {score}", True, BLACK)
   screen.blit(text, (10, 10))
  1. Main Game Loop

running = True while running:

   screen.fill(WHITE)
   for event in pygame.event.get():
       if event.type == pygame.QUIT:
           running = False
       if event.type == pygame.KEYDOWN:
           if event.key == pygame.K_SPACE:
               bird_movement = -8
       if event.type == pipe_timer:
           pipe_list.extend(create_pipe())
   # Bird movement
   bird_movement += gravity
   bird_rect.centery += bird_movement
   pygame.draw.rect(screen, BLACK, bird_rect)
   # Pipes
   pipe_list = move_pipes(pipe_list)
   draw_pipes(pipe_list)
   # Collision check
   if check_collision(pipe_list):
       running = False
   # Score
   pipe_list = [pipe for pipe in pipe_list if pipe.centerx > bird_rect.centerx and not pipe.centerx < bird_rect.centerx]
   score += 1 if any(pipe.centerx == bird_rect.centerx for pipe in pipe_list) else 0
   display_score()
   # Update the display
   pygame.display.update()
   clock.tick(30)

pygame.quit() sys.exit()

Computer science

Other uses

See also