Python
(파이썬) 장애물 피하기 게임 소스
코딩ABC
2024. 1. 9. 11:08
반응형
사용자가 캐릭터를 조종하여 떨어지는 장애물을 피하는 간단한 게임을 만들어 보겠습니다.
이 예에서 사용자는 키보드의 좌우 화살표 키를 이용해서 떨어지는 장애물을 피할 수 있습니다.
장애물이 화면 하단에 도달할 때마다 점수가 증가합니다. 플레이어가 장애물과 충돌하면 게임이 종료됩니다. 더 많은 기능, 그래픽, 사운드를 추가하여 이 게임을 사용자 정의하고 확장할 수 있습니다.
아래의 코드를 실행하기 위해서는"pygame" 모듈이 설치되어 있어야 하며, 이 모듈의 설치 방법은 화면 하단에 링크되어 있습니다.
코드는 다음과 같습니다.
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Set up display
width, height = 600, 400
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Dodger Game")
# Set up colors
white = (255, 255, 255)
black = (0, 0, 0)
# Set up player
player_size = 50
player_x = width // 2 - player_size // 2
player_y = height - player_size - 10
player_speed = 5
# Set up obstacles
obstacle_size = 50
obstacle_speed = 5
obstacle_frequency = 25
obstacles = []
# Set up font
font = pygame.font.Font(None, 36)
# Function to draw the player
def draw_player(x, y):
pygame.draw.rect(screen, white, (x, y, player_size, player_size))
# Function to draw obstacles
def draw_obstacles(obstacles):
for obstacle in obstacles:
pygame.draw.rect(screen, white, obstacle)
# Function to display the score
def display_score(score):
score_text = font.render("Score: " + str(score), True, white)
screen.blit(score_text, (10, 10))
# Main game loop
clock = pygame.time.Clock()
score = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_x > 0:
player_x -= player_speed
if keys[pygame.K_RIGHT] and player_x < width - player_size:
player_x += player_speed
# Spawn obstacles
if random.randrange(obstacle_frequency) == 0:
obstacle_x = random.randint(0, width - obstacle_size)
obstacle_y = -obstacle_size
obstacles.append(pygame.Rect(obstacle_x, obstacle_y, obstacle_size, obstacle_size))
# Move and remove obstacles
for obstacle in obstacles:
obstacle.y += obstacle_speed
if obstacle.y > height:
obstacles.remove(obstacle)
score += 1
# Check for collisions with obstacles
player_rect = pygame.Rect(player_x, player_y, player_size, player_size)
for obstacle in obstacles:
if player_rect.colliderect(obstacle):
pygame.quit()
sys.exit()
# Clear the screen
screen.fill(black)
# Draw the player, obstacles, and score
draw_player(player_x, player_y)
draw_obstacles(obstacles)
display_score(score)
# Update the display
pygame.display.flip()
# Control the frame rate
clock.tick(60)
"pygame" 모듈 설치하는 방법
(파이썬) pip install, 모듈 설치하는 방법
파이썬에서 모듈을 설치할 때 pip 프로그램을 사용하는데, 보통 책에는 아래와 같이 설명되어 있습니다. "pygame" 모듈을 설치하는 예를 들어 보겠습니다. pip install pygame 그러나 명령프롬프트(cmd. co
coding-abc.kr
반응형