[파이썬] pygame 플레이어 대 플레이어 대결

pygame logo

Introduction

In this blog post, we will explore how to create a player versus player (PVP) battle game using pygame, a popular Python library for game development. We will learn how to set up the game window, control player movement, and implement the game logic for the battle.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of Python programming language and pygame library. If you haven’t installed pygame yet, you can install it using pip:

pip install pygame

Setting up the game window

First, let’s import the necessary libraries and initialize the pygame module.

import pygame
from pygame.locals import *

# Initialize pygame
pygame.init()

# Set up the game window
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("PVP Battle Game")

Creating the players

Next, let’s create the players for our game. We will define a Player class that will represent each player. Each player will have attributes like position, speed, and sprite.

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()

        self.image = pygame.Surface((50, 50))
        self.image.fill((255, 0, 0))  # Red color for player 1
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.speed = 5

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[K_LEFT]:
            self.rect.x -= self.speed
        if keys[K_RIGHT]:
            self.rect.x += self.speed
        if keys[K_UP]:
            self.rect.y -= self.speed
        if keys[K_DOWN]:
            self.rect.y += self.speed

Game loop

Now, let’s set up the game loop which will continuously run the game logic and update the display.

running = True
clock = pygame.time.Clock()

player1 = Player(100, 100)
player2 = Player(700, 500)

while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False

    # Update players
    player1.update()
    player2.update()

    # Draw players
    screen.fill((255, 255, 255))  # Clear the screen
    screen.blit(player1.image, player1.rect)
    screen.blit(player2.image, player2.rect)
    pygame.display.flip()

    # Limit the frame rate
    clock.tick(60)

pygame.quit()

Conclusion

In this blog post, we have learned how to create a basic player versus player (PVP) battle game using pygame in Python. We covered setting up the game window, creating players, and implementing the game logic in the game loop. Now, you can further enhance the game by adding features like collisions, shooting, or power-ups.

Feel free to experiment and modify the code to create your own unique PVP battle game. Happy coding!