在python中同时生成同一对象的多个实例 [英] Spawning multiple instances of the same object concurrently in python

查看:81
本文介绍了在python中同时生成同一对象的多个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我是一个初学者程序员,从python开始,然后开始在pygames中制作游戏.游戏基本上是在任意位置以圆圈形式生成的,单击时会为您提供分数.最近,当我想同时在同一对象的多个实例(在本例中为圆)中生成时,遇到了一个障碍.我已经尝试过诸如sleep()之类的东西以及其他一些与计数器相关的代码,但是它总是导致产生下一个圆圈,从而覆盖前一个圆圈(即程序在第1圈中产生,但是当第2圈出现时,第1圈消失了).有谁知道解决这个问题的方法?非常感谢您的帮助!

  import pygame随机导入导入时间pygame.init()窗口= pygame.display.set_mode((800,600))class circle():def __init __(自身,颜色,x,y,半径,宽度,):self.color =颜色self.x = xself.y = yself.radius = 半径self.width =宽度def平局(自我,胜利,轮廓=无):pygame.draw.circle(win,self.color,(self.x,self.y,self.radius,self.width),0)运行=真运行时:window.fill((0,0,0))pygame.draw.circle(窗口,(255,255,255),(random.randint(0,800),random.randint(0,600)),20,20)time.sleep(1)pygame.display.update()对于pygame.event.get()中的事件:如果event.type == pygame.QUIT:运行=假pygame.quit()放弃() 

解决方案

它不能那样工作. time.sleep

 导入pygame,随机pygame.init()窗口= pygame.display.set_mode((300,300))类对象:def __init __():self.radius = 50self.x = random.randrange(self.radius,window.get_width()-self.radius)self.y = random.randrange(self.radius,window.get_height()-self.radius)self.color = pygame.Color(0)self.color.hsla =(random.randrange(0,360),100,50,100)object_list = []time_interval = 200#200毫秒== 0.2秒next_object_time = 0运行=真时钟= pygame.time.Clock()运行时:clock.tick(60)对于pygame.event.get()中的事件:如果event.type == pygame.QUIT:运行=错误current_time = pygame.time.get_ticks()如果current_time>next_object_time:next_object_time + = time_intervalobject_list.append(Object())window.fill(0)对于object_list [:]中的对象:pygame.draw.circle(窗口,object.color,(object.x,object.y),round(object.radius))object.radius-= 0.2如果object.radius<1:object_list.remove(对象)pygame.display.flip()pygame.quit()出口() 


另一种选择是使用

 导入pygame,随机pygame.init()窗口= pygame.display.set_mode((300,300))类对象:def __init __():self.radius = 50self.x = random.randrange(self.radius,window.get_width()-self.radius)self.y = random.randrange(self.radius,window.get_height()-self.radius)self.color = pygame.Color(0)self.color.hsla =(random.randrange(0,360),100,50,100)object_list = []time_interval = 200#200毫秒== 0.2秒timer_event = pygame.USEREVENT + 1pygame.time.set_timer(timer_event,time_interval)运行=真时钟= pygame.time.Clock()运行时:clock.tick(60)对于pygame.event.get()中的事件:如果event.type == pygame.QUIT:运行=错误elif event.type == timer_event:object_list.append(Object())window.fill(0)对于object_list [:]中的对象:pygame.draw.circle(窗口,object.color,(object.x,object.y),round(object.radius))object.radius-= 0.2如果object.radius<1:object_list.remove(对象)pygame.display.flip()pygame.quit()出口() 

Hey I'm a beginner programmer who is starting with python and am starting out by making a game in pygames. The game basically spawns in circles at random positions, and when clicked give you points. Recently i've hit a roadblock when I want to spawn in multiple instances of the same object(in this case circles) at the same time. I've tried stuff like sleep() and some other code related to counters, but it always results in the next circle spawned overriding the previous one(i.e the program spawns in circle 1, but when circle 2 comes in, circle 1 disappears). Anyone know a solution to this? Would really appreciate your help!

import pygame
import random
import time

pygame.init()

window = pygame.display.set_mode((800,600))

class circle():
    def __init__(self, color, x, y, radius, width,):
        self.color = color
        self.x = x
        self.y = y
        self.radius = radius
        self.width = width

    def draw(self, win, outline=None):
        pygame.draw.circle(win, self.color, (self.x, self.y, self.radius, self.width), 0)

run=True
while run:
    window.fill((0, 0, 0))
    pygame.draw.circle(window, (255, 255, 255), (random.randint(0, 800),random.randint(0, 600)), 20, 20)
    time.sleep(1)
    pygame.display.update()

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            run=False
            pygame.quit()
            quit()

解决方案

It does not work that way. time.sleep, pygame.time.wait() or pygame.time.delay is not the right way to control time and gameplay within an application loop. The game does not respond while you wait. The application loop runs continuously. You have to measure the time in the loop and spawn the objects according to the elapsed time.
pygame.Surface.fill clears the entire screen. Add the newly created objects to a list. Redraw all of the objects and the entire scene in each frame.
See also Time, timer event and clock


You have 2 options. Use pygame.time.get_ticks() to measure the time. Define a time interval after which a new object should appear. Create an object when the point in time is reached and calculate the point in time for the next object:

object_list = []
time_interval = 500 # 500 milliseconds == 0.1 seconds
next_object_time = 0 

while run:
    # [...]
    
    current_time = pygame.time.get_ticks()
    if current_time > next_object_time:
        next_object_time += time_interval
        object_list.append(Object())

Minimal example:

import pygame, random
pygame.init()
window = pygame.display.set_mode((300, 300))

class Object:
    def __init__(self):
        self.radius = 50
        self.x = random.randrange(self.radius, window.get_width()-self.radius)
        self.y = random.randrange(self.radius, window.get_height()-self.radius)
        self.color = pygame.Color(0)
        self.color.hsla = (random.randrange(0, 360), 100, 50, 100)

object_list = []
time_interval = 200 # 200 milliseconds == 0.2 seconds
next_object_time = 0 

run = True
clock = pygame.time.Clock()
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    
    current_time = pygame.time.get_ticks()
    if current_time > next_object_time:
        next_object_time += time_interval
        object_list.append(Object())
    
    window.fill(0)
    for object in object_list[:]:
        pygame.draw.circle(window, object.color, (object.x, object.y), round(object.radius))
        object.radius -= 0.2
        if object.radius < 1:
            object_list.remove(object)
    pygame.display.flip()

pygame.quit()
exit()


The other option is to use the pygame.event module. Use pygame.time.set_timer() to repeatedly create a USEREVENT in the event queue. The time has to be set in milliseconds. e.g.:

object_list = []
time_interval = 500 # 500 milliseconds == 0.1 seconds
timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, time_interval)

Note, in pygame customer events can be defined. Each event needs a unique id. The ids for the user events have to be between pygame.USEREVENT (24) and pygame.NUMEVENTS (32). In this case pygame.USEREVENT+1 is the event id for the timer event.

Receive the event in the event loop:

while run:
    for event in pygame.event.get():
        if event.type == timer_event:
            object_list.append(Object())

The timer event can be stopped by passing 0 to the time argument of pygame.time.set_timer.

Minimal example:

import pygame, random
pygame.init()
window = pygame.display.set_mode((300, 300))

class Object:
    def __init__(self):
        self.radius = 50
        self.x = random.randrange(self.radius, window.get_width()-self.radius)
        self.y = random.randrange(self.radius, window.get_height()-self.radius)
        self.color = pygame.Color(0)
        self.color.hsla = (random.randrange(0, 360), 100, 50, 100)

object_list = []
time_interval = 200 # 200 milliseconds == 0.2 seconds
timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, time_interval)

run = True
clock = pygame.time.Clock()
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == timer_event:
            object_list.append(Object())
    
    window.fill(0)
    for object in object_list[:]:
        pygame.draw.circle(window, object.color, (object.x, object.y), round(object.radius))
        object.radius -= 0.2
        if object.radius < 1:
            object_list.remove(object)
    pygame.display.flip()

pygame.quit()
exit()

这篇关于在python中同时生成同一对象的多个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆