Cách tạo kẻ thù trong game Python

Kẻ thù đóng vai trò quan trọng trong việc tạo ra một game thử thách hấp dẫn. Thư viện Arcade của Python mang tới cho bạn cách đơn giản để đưa kẻ thù vào trong game.

Tạo kẻ thù trong game Python

Tạo một game đơn giản

Trước khi bắt đầu, đảm bảo đã cài pip trên thiết bị. Dùng lệnh này để cài thư viện arcade:

pip install arcade

Sau đó, bắt đầu bằng cách tạo một game đơn giản tại nơi người chơi có thể di chuyển sang trái và phải bằng các phím mũi tên.

import arcade

# Kích thước cửa sổ
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

# Thuộc tính người chơi
PLAYER_RADIUS = 25
PLAYER_SPEED = 5

class GameWindow(arcade.Window):
    def __init__(self, width, height):
        super().__init__(width, height)
        arcade.set_background_color(arcade.color.WHITE)
        self.player_x = width // 2

    def on_draw(self):
        arcade.start_render()
        arcade.draw_circle_filled(self.player_x, PLAYER_RADIUS, PLAYER_RADIUS, arcade.color.BLUE)

    def on_key_press(self, key, modifiers):
        if key == arcade.key.LEFT:
            self.player_x -= PLAYER_SPEED
        elif key == arcade.key.RIGHT:
            self.player_x += PLAYER_SPEED

    def update(self, delta_time):
        pass

def main():
    window = GameWindow(SCREEN_WIDTH, SCREEN_HEIGHT)
    arcade.run()

if __name__ == "__main__":
    main()

Tạo kẻ thù đơn giản

Để tạo một kẻ thù giết người chơi khi va chạm, tạo hình tròn khác trên màn hình. Trong hàm on_draw này, bạn có thể vẽ hình tròn kẻ thù và kiểm tra va chạm trong phương thức update. Bạn cũng có thể dùng sprite cho kẻ thù.

# Thêm class GameWindow 

class GameWindow(arcade.Window):
    # ...

    def __init__(self, width, height):
        # ...

        # Enemy attributes
        self.enemy_x = width // 2
        self.enemy_y = height - PLAYER_RADIUS
        self.enemy_radius = 20

    def on_draw(self):
        # ...
        arcade.draw_circle_filled(self.enemy_x, self.enemy_y, self.enemy_radius, arcade.color.RED)

    def update(self, delta_time):
        if self.is_collision(self.player_x, self.player_y, self.enemy_x, self.enemy_y, PLAYER_RADIUS, self.enemy_radius):
            print("Game Over!")
    
    def is_collision(self, x1, y1, x2, y2, radius1, radius2):
        distance_squared = (x1 - x2) ** 2 + (y1 - y2) ** 2
        radius_sum_squared = (radius1 + radius2) ** 2
        return distance_squared <= radius_sum_squared

Làm kẻ thù theo người chơi

Trong một số game, kẻ thù có thể đuổi theo người chơi, thêm kẻ thù năng động vào gameplay. Để tạo một kẻ thù đuổi theo người chơi, bạn cần update vị trí của nó theo vị trí của người chơi. Bất cứ khi nào người chơi di chuyển, kẻ thù sẽ di chuyển theo cùng hướng. Bạn có thể đạt được điều này bằng cách chỉnh sửa phương thức update. Tạo file mới tên enemy-follow-player.py và thêm code với các bản cập nhật bên dưới:

# Thêm class GameWindow 

class GameWindow(arcade.Window):
    # ...

    def update(self, delta_time):
        if self.player_x < self.enemy_x:
            self.enemy_x -= PLAYER_SPEED
        elif self.player_x > self.enemy_x:
            self.enemy_x += PLAYER_SPEED

        if self.is_collision(self.player_x, self.player_y,
                            self.enemy_x, self.enemy_y,
                            PLAYER_RADIUS, ENEMY_RADIUS):
           print("Game Over!")
  
    def is_collision(self, x1, y1, x2, y2, radius1, radius2):
        distance_squared = (x1 - x2) ** 2 + (y1 - y2) ** 2
        radius_sum_squared = (radius1 + radius2) ** 2
        return distance_squared <= radius_sum_squared

Dưới đây là kết quả:

Tạo kẻ thù chơi game Python

Thêm đạn của kẻ thù

Để tạo kẻ thù bắn đạn, tạo class Bullet và một danh sách để theo dõi các đạn hoạt động. Kẻ thù sẽ định kỳ tạo một viên đạn mới và update vị trí của nó. Tạo file mới tên bullets.py và thêm code với bản update bên dưới:

# Thêm class GameWindow 

class Bullet:
def __init__(self, x, y, radius, speed):
self.x = x
self.y = y
self.radius = radius
self.speed = speed

def update(self):
self.y -= self.speed

class GameWindow(arcade.Window):
# ...

def __init__(self, width, height):
# ...

# Thuộc tính kẻ thù
self.bullets = []
self.bullet_radius = 5
self.bullet_speed = 3
self.bullet_cooldown = 60 # Số khung giữa các lần bắn đạn
self.bullet_timer = 0

def on_draw(self):
# ...
for bullet in self.bullets:
arcade.draw_circle_filled(bullet.x, bullet.y,
self.bullet_radius, arcade.color.BLACK)

def update(self, delta_time):
# ...

self.bullet_timer += 1
if self.bullet_timer >= self.bullet_cooldown:
self.bullets.append(Bullet(self.enemy_x, self.enemy_y - self.enemy_radius,
self.bullet_radius, self.bullet_speed))
self.bullet_timer = 0

for bullet in self.bullets:
bullet.update()
if self.is_collision(self.player_x, self.player_y, self.enemy_x,
self.enemy_y, PLAYER_RADIUS, ENEMY_RADIUS):
print("Game Over!")

def is_collision(self, x1, y1, x2, y2, radius1, radius2):
distance_squared = (x1 - x2) ** 2 + (y1 - y2) ** 2
radius_sum_squared = (radius1 + radius2) ** 2
return distance_squared <= radius_sum_squared

Kết quả:

Kẻ thù bắn đạn

Thêm chỉ số máu cho kẻ thù

Trong nhiều game, kẻ thù còn có chỉ số máu (HP) cho phép chúng chịu nhiều đòn đánh trước khi bị đánh bại. Thêm chỉ số này có thể giới thiệu các thành phần gameplay chiến lược, đồng thời mang lại cảm giác tiến bộ và thử thách. Tạo một file mới tên health-point.py và thêm code này với các update bên dưới:

# Kích thước cửa sổ
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

# Thuộc tính người chơi
PLAYER_RADIUS = 25
PLAYER_SPEED = 5

# Thuộc tính kẻ thù
ENEMY_RADIUS = 20
ENEMY_HEALTH = 100

class GameWindow(arcade.Window):
    def __init__(self, width, height):
        super().__init__(width, height)
        arcade.set_background_color(arcade.color.WHITE)
        self.player_x = width // 2
        self.player_y = height // 2
        self.enemy_x = width // 2
        self.enemy_y = height - PLAYER_RADIUS
        self.enemy_health = ENEMY_HEALTH
        print(self.enemy_health)
    def on_draw(self):
        arcade.start_render()
        arcade.draw_circle_filled(self.player_x,
                                  self.player_y,
                                  PLAYER_RADIUS,
                                  arcade.color.BLUE)
        if self.enemy_health > 0:
            arcade.draw_circle_filled(self.enemy_x,
                                      self.enemy_y,
                                      ENEMY_RADIUS,
                                      arcade.color.RED)

    def update(self, delta_time):
        if self.is_collision(self.player_x, self.player_y,
                             self.enemy_x, self.enemy_y,
                             PLAYER_RADIUS, ENEMY_RADIUS):
            self.enemy_health -= 10
            print(self.enemy_health)

Hằng số ENEMY_HEALTH có giá trị 100 để biểu thị điểm máu ban đầu của kẻ thù. Khi người chơi va chạm với kẻ thù, họ có thể bị trừ một số điểm dựa trên chỉ số máu của địch. Để cập nhật chỉ số máu, bạn có thể in một đối tượng văn bản self.health_text hiện sức khỏe hiện tại của kẻ thù.

Bằng cách kết hợp chỉ số sức khỏe của địch, bạn có thể giới thiệu một cấp thử thách và chiến thuật cho người chơi. Giá trị máu được hiện cung cấp phản hồi trực quan và cho phép người chơi theo dõi máu còn lại của địch.

Ngoài ra, bạn có thể mở rộng code bằng cách thêm logic và hình ảnh, như hiện thanh máu hoặc các điều kiện đánh bại khi máu của địch bằng 0.

Thêm kẻ thù vào game có thể nâng cao đáng kể trải nghiệm gameplay với những thử thách khó và thôi thúc cảm giác chinh phục của người chơi. Hi vọng hướng dẫn này giúp bạn phát triển game thú vị hơn bằng Python.

Thứ Năm, 22/06/2023 16:45
51 👨 172
0 Bình luận
Sắp xếp theo
    ❖ Python