Почему эти объекты так быстро отскакивают от экрана? Как мне их замедлить - PullRequest
3 голосов
/ 22 мая 2019

У меня есть эти блоки, которые я сделал, которые находятся в классе Enemy_Block.Когда я пытаюсь перемещать их, они любят телепортироваться по экрану.Как мне замедлить эти вражеские блоки.Пожалуйста, помогите, спасибо.

Я пытался поместить этот цикл for, который порождает вражеские блоки внутри и снаружи цикла.Вот и все.

from random import randint
from pygame.locals import *
import pygame
import sys

# intalize Pygame
pygame.init()

# Making User Controled Block
class User_Block:
    def __init__(self):
        self.x_cor = 300
        self.y_cor = 300
        self.length = 20
        self.width = 20
        self.color = GREEN
        self.move_x = 0
        self.move_y = 0
        self.rect = pygame.draw.rect(screen,self.color,[self.x_cor,self.y_cor,self.length,self.width],0)

    def draw(self):
        pygame.draw.rect(screen,self.color,[self.x_cor,self.y_cor,self.length,self.width],0)
        self.y_cor += self.move_y
        self.x_cor += self.move_x
        if self.x_cor == x_size - self.width:
            self.x_cor = 0
            self.move_x = 0
        elif self.x_cor == 0 - self.length:
            self.x_cor = x_size
            self.move_x = 0
        elif self.y_cor == y_size - self.width:
            self.y_cor = 0
            self.move_y = 0
        elif self.y_cor == 0 - self.length:
            self.y_cor = y_size
            self.move_y = 0
        self.rect = pygame.draw.rect(screen,self.color,[self.x_cor,self.y_cor,self.length,self.width],0)

# Making Enemys
class Enemy_Block:
    def __init__(self):
        self.x_cor = randint(100,500)
        self.y_cor = randint(100,500)
        self.length = randint(10,100)
        self.width = randint(10,100)
        self.color = (255,0,255)
        self.x_vel = randint(-5,5)
        self.y_vel = randint(-5,5)
        pygame.draw.rect(screen,self.color,[self.x_cor,self.y_cor,self.length,self.width],5)

    def move_random(self):
        if self.y_cor > y_size or self.y_cor < 0:
            self.y_vel = -self.y_vel
        elif self.x_cor > x_size or self.x_cor < 0:
            self.x_vel = -self.x_vel
        self.y_cor += self.y_vel
        self.x_cor += self.x_vel
        pygame.draw.rect(screen,self.color,[self.x_cor,self.y_cor,self.length,self.width],5)

# Set Up Screen
x_size = 1200
y_size = 700
screen = pygame.display.set_mode((x_size, y_size))

# Varible Used "while" Loop
done = False

# Setting Caption of Pygame Tab
pygame.display.set_caption("Block Rush Game")

# Colors
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
GREEN = (0,255,0)

# User Controled Block
Block = User_Block()

# Enemys
Enemy_List = []
for i in range(10):
    Enemy = Enemy_Block()
    Enemy_List.append(Enemy)

# Most important code here
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    #Moving Character
    if event.type == pygame.KEYDOWN:
        if event.key == K_w:
            Block.move_y = -5
        elif event.key == K_s:
            Block.move_y = 5
        elif event.key == K_a:
            Block.move_x = -5
        elif event.key == K_d:
            Block.move_x = 5
    elif event.type == pygame.KEYUP:
        if event.key == K_w or event.key == K_s:
            Block.move_y = 0
        elif event.key == K_a or event.key == K_d:
            Block.move_x = 0
    # Fill the Screen Black
    screen.fill(BLACK)
    # Activate draw function in Block
    Block.draw()
    #Spawn Enemy Blocks
    Enemy_List = []
    for i in range(10):
        Enemy = Enemy_Block()
        Enemy_List.append(Enemy)

    # FPS
    Clock = pygame.time.Clock()
    Clock.tick(60)

    # Keep Updating the Screen
    pygame.display.update()
pygame.quit()

Ожидаемый результат - игра создаст десять вражеских блоков, которые движутся по экрану довольно медленно, потому что моя скорость низкая.В результате блоки как бы телепортируются по экрану, потому что они движутся так быстро.

Ответы [ 2 ]

3 голосов
/ 22 мая 2019

Есть 2 вопроса. Во-первых, в вашем основном игровом цикле вы постоянно порождаете новых врагов, а во-вторых, вы не говорите своим врагам двигаться

Итак, в вашем основном цикле измените:

Enemy_List = []
for i in range(10):
    Enemy = Enemy_Block()
    Enemy_List.append(Enemy)

до:

for e in Enemy_List:
    e.move_random()

Вы уже создали 10 своих врагов за пределами основного цикла, так что вам не нужно продолжать их возрождать. Вместо этого вы можете просто вызывать move_random() на каждом из них, чтобы перемещать их по экрану

1 голос
/ 22 мая 2019

Это кажется нежелательным:

            Enemy_List = []
            for i in range(10):
                Enemy = Enemy_Block()
                Enemy_List.append(Enemy)

Вы производите новые случайно инициализированные блоки противника каждый раз в цикле событий.Вы хотите инициировать только один раз, прежде чем цикл событий начинается, и затем позволить им move_random() в цикле.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...