python - 如何放置这些船舶图像?

标签 python pygame

我是Python初学者。如何将这些对象放置在窗口后半部分的字典 self.x 中。 这是我的一些代码:

win_w = int(input("Enter the number of pixels corresponding to the width of the game window: "))
win_h = int(input("Enter the number of pixels corresponding to the height of the game window: "))
win = pygame.display.set_mode((win_w, win_h))
centre_of_win = win_w * 0.5

ships = ['ship1.png', 'ship2.png', 'ship3.png']

class Enemy_Ships:

    def __init__(self):
        self.x = {'ship1.png': 50, 'ship2.png': 75, 'ship3.png': 100}
        self.y = 25
        self.xmax = random.uniform(centre_of_win, win_w)
        self.ymax = random.randint(0, win_h)
        self.color = (0, 100, 100)

    def drawing_enemy(self, ships):
        for element in ships:
            rect = pygame.Rect(self.xmax, self.ymax, 50, 25)
            pygame.draw.rect(win, self.color, rect, 1, win_w)

enemy = Enemy Ships()

Enemy_Ships.drawing_enemy(ships)
pygame.display.update()

我想将这些图像随机放置在 centre_of_win 和 win w(最大宽度)之间

最佳答案

要放置船只,RNG 应放置在 Drawing_enemy 方法的 for 循环内(否则,只会创建一个随机位置)。

此外,对于每艘放置的船只都会进行检查以查看 whether it collides与之前放置的船只。

import random
import pygame
from pygame import KEYDOWN, K_ESCAPE, QUIT

pygame.init()

win_w, win_h = 800, 500

win = pygame.display.set_mode((win_w, win_h))
centre_of_win = win_w * 0.5

ships = ["ship1.png", "ship2.png", "ship3.png"]


class Enemy_Ships:
    def __init__(self):
        self.x = {"ship1.png": 50, "ship2.png": 75, "ship3.png": 100}
        self.y = 25
        self.color = (0, 100, 100)

    def drawing_enemy(self, ships):
        placed_ships = []
        for ship in ships:
            # get ship width from self.x dictionary
            width = self.x[ship]
            # define random numbers for each ship individually,
            # repeat if ships would collide
            is_colliding = True
            while is_colliding:
                x = random.uniform(centre_of_win, win_w - width)
                y = random.randint(0, win_h)
                # generate ship, check collision with placed ships
                rect = pygame.Rect(x, y, width, self.y)
                is_colliding = any(
                    rect.colliderect(previous_ship) for previous_ship in placed_ships
                )
            placed_ships.append(rect)
            pygame.draw.rect(win, self.color, rect, 1, win_w)


enemy = Enemy_Ships()

enemy.drawing_enemy(ships)
pygame.display.update()

running = True
while running:
    for event in pygame.event.get():
        if event.type == KEYDOWN and event.key == K_ESCAPE:
            running = False
        elif event.type == QUIT:
            running = False

enter image description here

设计备注:

总的来说,Enemy_Ships 类的目的并不完全是“干净的”。它定义了船舶的宽度和图像,但是在绘制它们时,对生成的矩形的访问会丢失。我建议只实现一个 EnemyShip 类,然后用一个简单的函数实例化该类,然后绘制。

最后,我不会使用诸如 ship1.png 之类的船舶标识字符串,而是使用 Enums ,这可以防止由于拼写错误而导致的错误:

import random
from enum import Enum

import pygame
from pygame import KEYDOWN, K_ESCAPE, QUIT

pygame.init()

win_w, win_h = 800, 500

win = pygame.display.set_mode((win_w, win_h))
centre_of_win = win_w * 0.5


class EnemyShip:
    def __init__(
        self, x: int, y: int, width: int, height: int, color: tuple[int] = (0, 100, 100)
    ):
        self.rect = pygame.Rect(x, y, width, height)
        self.color = color


class ShipType(Enum):
    SMALL = 50
    MID = 75
    BIG = 100


def create_enemies(ship_types: list[ShipType], height: int = 25) -> list[EnemyShip]:
    placed_ships = []
    for ship in ship_types:
        width = ship.value
        is_colliding = True
        while is_colliding:
            x = int(random.uniform(centre_of_win, win_w - width))
            y = random.randint(0, win_h)
            # generate ship, check collision with placed ships
            enemy = EnemyShip(x, y, width, height)
            is_colliding = any(
                enemy.rect.colliderect(previous_ship.rect)
                for previous_ship in placed_ships
            )
        placed_ships.append(enemy)
    return placed_ships


ships = [ShipType.SMALL, ShipType.MID, ShipType.BIG]

enemies = create_enemies(ships)
for enemy in enemies:
    pygame.draw.rect(win, enemy.color, enemy.rect, 1, win_w)
pygame.display.update()

running = True
while running:
    for event in pygame.event.get():
        if event.type == KEYDOWN and event.key == K_ESCAPE:
            running = False
        elif event.type == QUIT:
            running = False

关于python - 如何放置这些船舶图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77566596/

相关文章:

python - 为什么pygame会为我卡住?

python - pub/sub 数据库和客户端编程的数据库有什么区别?

python - 使用python,你如何选择一个csv文件的随机行?

python - 如何使用函数显示对象的属性值

python - 类 'int' 未定义 '__getitem__' ,因此 '[]' 运算符不能在其实例上使用

Python pygame 崩溃,修复似乎不起作用

python - 如何使用 pygame 找到 python 中文件的确切位置?

python - Selenium 无法通过 Xpath 查找元素?

python - 理解位置参数的直观方法不应该跟在关键字参数之后

python - 如何使用pygame播放音乐(Python)