Create 10 instances of an object (Python)

edited November 2016 in Python Mode

Hello Forum,

I got a question: First off: I'm using Python Mode. I'm trying to instantiate an object 10 times, but whatever i do ends up in the ellipses getting a tremendous speed boost. The idea is: Create 10 ellipses all spawning on different locations and with different velocity. Is this possible using lists? Here is the code, creating 1 instance of the object:

from BallTab import Ball

def setup():
    global myFirstBall
    size(800, 800)
    myFirstBall = Ball(random(50, 750), random(50, 750), 2, 3, 100)


def draw():
    global myFirstBall
    background(69, 69, 69) 
    myFirstBall.display()
    myFirstBall.move()
    if myFirstBall.y > 750:
        myFirstBall.ys = -2
    if myFirstBall.x > 750:
        myFirstBall.xs = -3
    if myFirstBall.y < 50:
        myFirstBall.ys = 2
    if myFirstBall.x < 50:
        myFirstBall.xs = 3

BallTab:

class Ball(object):
    def __init__(self, xPos, yPos, xSpeed, ySpeed, radius):
        self.x = xPos
        self.y = yPos
        self.xs = xSpeed
        self.ys = ySpeed
        self.r = radius

    def display(self):
        ellipse(self.x, self.y, self.r, self.r)

    def move(self):
        self.x += self.xs
        self.y += self.ys

Answers

  • edited November 2016 Answer ✓

    @juicy -- Yes, adding things to lists is trivial in python. Just use loop over the range/xrange and use mylistname.append(myobject). Or use a list comprehension.

    From Creating a list of objects in Python:

    class MyClass(object):
        def __init__(self, number):
            self.number = number
    
    my_objects = []
    
    for i in range(100):
        my_objects.append(MyClass(i))
    
    # later
    
    for obj in my_objects:
        print obj.number
    

    From other Creating a list of objects in Python:

    class SimpleClass(object):
        pass
    simplelist = []
    for count in xrange(4):
        x = SimpleClass()
        x.attr = count
        simplelist.append(x)
    
  • It works now, thank you very much! If anyone wants to see the finished code, leave a reply!

  • Glad it worked out, @juicy!

    Yes, I would love to see the finished code. I also think sharing your Python example with the forum would help new Processing.py learners.

  • Hi Juicy

    I am newbie here at Phyton, so I'd like to watch the fiinished code if you don't mind

    Thanks

  • edited November 2016

    Hi @jeremydouglass & @laimperiestro!

    Given that @juicy didn't posted his final code yet, I remembered I had a very similar sketch from the previous old forum:
    https://forum.Processing.org/one/topic/nullpointerexeption-with-an-arraylist

    Its old online link too: :bz
    http://studio.ProcessingTogether.com/sp/pad/export/ro.9oyKfI9kOIa77/latest

    Made some refactoring in order to modernize it a bit more. 1st the Java Mode version:

    /**
     * Clickable Spawning Balls (v3.1)
     * by  drov.fr  (2013/Jun)
     * mod GoToLoop (2013/Dec)
     * refactor ver (2016/Nov/27)
     *
     * forum.Processing.org/two/discussion/19200/
     * create-10-instances-of-an-object-python#Item_5
     *
     * forum.Processing.org/one/topic/nullpointerexeption-with-an-arraylist
     * forum.Processing.org/two/discussion/2171/effect-in-processing#Item_3
     *
     * studio.ProcessingTogether.com/sp/pad/export/ro.9oyKfI9kOIa77/latest
     * p5js.SketchPad.cc/sp/pad/view/ro.CwHWpJ$SP1EN8i/latest
     */
    
    import java.util.List;
    final List<Ball> balls = new ArrayList<Ball>();
    
    static final color BG = 0;
    static final boolean NO_JS = 1/2 != 1/2.;
    
    void setup() {
      size(600, 400, NO_JS? FX2D : JAVA2D);
      smooth(3);
      frameRate(60);
      ellipseMode(CENTER);
      fill(Ball.COLOUR);
      noStroke();
    }
    
    void draw() {
      background(BG);
      for (final Ball b : balls)  b.script();
      if (NO_JS)  getSurface().setTitle( "# Balls: " + balls.size() );
    }
    
    void mousePressed() {
      if (mouseButton != CENTER)  balls.add( new Ball() );
      else {
        final int len = balls.size();
        if (len != 0)  balls.remove(len - 1);
      }
    }
    
    final class Ball {
      static final byte  DIAM = 20, RAD = DIAM >> 1;
      static final byte  MIN_SPD = 1, MAX_SPD = 5 + 1;
      static final color COLOUR  = #FFFF00;
    
      short x, y;
      byte  spX, spY;
    
      Ball() {
        x = (short) mouseX;
        y = (short) mouseY;
    
        spX = (byte) random(MIN_SPD, MAX_SPD);
        if (random(1) < .5)  spX *= -1;
    
        spY = (byte) ( random(MIN_SPD, MAX_SPD) *
          (random(1) < .5? -1 : 1) );
      }
    
      void script() {
        bump();
        show();
      }
    
      void bump() {
        if ( (x += spX) < RAD | x > width - RAD )  spX *= -1;
        y += spY *= y < RAD | y > height - RAD? -1 : 1;
      }
    
      void show() {
        ellipse(x, y, DIAM, DIAM);
      }
    }
    

    And finally, the corresponding Python Mode, so you all can compare them: :-bd

    """
     ' Clickable Spawning Balls (v3.1.1)
     ' by  drov.fr  (2013/Jun)
     ' mod GoToLoop (2013/Dec)
     ' Python ver.  (2016/Nov/27)
     '
     ' https://forum.Processing.org/two/discussion/19200/
     ' create-10-instances-of-an-object-python#Item_5
     '
     ' https://forum.Processing.org/one/topic/nullpointerexeption-with-an-arraylist
     ' https://forum.Processing.org/two/discussion/2171/effect-in-processing#Item_3
     '
     ' http://studio.ProcessingTogether.com/sp/pad/export/ro.9oyKfI9kOIa77/latest
     ' http://p5js.SketchPad.cc/sp/pad/view/ro.CwHWpJ$SP1EN8i/latest
    """
    
    balls, BG = [], 0
    
    def setup():
        size(600, 400, FX2D)
        smooth(3), frameRate(60)
        ellipseMode(CENTER), fill(Ball.COLOUR), noStroke()
    
    
    def draw():
        background(BG)
        for b in balls: b.script()
        this.getSurface().setTitle('# Balls: ' + `len(balls)`)
    
    
    def mousePressed():
        if mouseButton != CENTER: balls.append( Ball() )
        else: len(balls) and balls.pop()
    
    
    class Ball:
        DIAM = 20
        RAD = DIAM >> 1
        MIN_SPD, MAX_SPD = 1, 5+1
        COLOUR = 0xffFFFF00
    
        def __init__(b):
            b.x, b.y = mouseX, mouseY
    
            b.spX = int( random( Ball.MIN_SPD, Ball.MAX_SPD ) )
            if random(1) < .5: b.spX *= -1
    
            b.spY = int( random( Ball.MIN_SPD, Ball.MAX_SPD ) *
                       ( random(1) < .5 and -1 or 1 ) )
    
    
        def script(b): b.bump(), b.show()
    
        def bump(b):
            b.x += b.spX
            if b.x < Ball.RAD or b.x > width - Ball.RAD: b.spX *= -1
    
            b.spY *= (b.y < Ball.RAD or b.y > height - Ball.RAD) and -1 or 1
            b.y += b.spY
    
    
        def show(b): ellipse(b.x, b.y, Ball.DIAM, Ball.DIAM)
    
  • Sorry for the late response. Been kind of busy! Here is my completed code (NOTE: Python):

    Main:

    from BallTab import Ball
    
    def setup():
        global myFirstList
        size(800, 800)
        myFirstList = []
    
        for _ in range(0, 10):
            xPos = random(50, 750)
            yPos = random(50, 750)
            xSpeed = random(0, 5)
            ySpeed = random(0, 5)
            radius = 100
            col =  color(random(0, 255), random(0, 255), random(0, 255))
            print col
            myFirstList.append(Ball(xPos, yPos, xSpeed, ySpeed, radius, col))
    
    
    def draw():
        global myFirstList
        background(69, 69, 69) 
    
        for _ in range(0, len(myFirstList)):
            myFirstList[_].move()
            myFirstList[_].display()
    

    Tab: BallTab:

    class Ball(object):
        def __init__(self, xPos, yPos, xSpeed, ySpeed, radius, col):
            self.x = xPos
            self.y = yPos
            self.xs = xSpeed
            self.ys = ySpeed
            self.r = radius
            self.col = col
    
        def display(self):
            fill(self.col)
            ellipse(self.x, self.y, self.r, self.r)
    
        def move(self):
            self.x += self.xs
            self.y += self.ys
            if self.y > 750:
                self.ys = -2
            if self.x > 750:
                self.xs = -3
            if self.y < 50:
                self.ys = 2
            if self.x < 50:
                self.xs = 3
    
  • edited November 2016

    Since I've already coded versions for Java & Python modes, why not for p5.js as well? :-bd
    http://p5js.SketchPad.cc/sp/pad/view/ro.CwHWpJ$SP1EN8i/latest

    /**
     * Clickable Spawning Balls (v3.1)
     * by  drov.fr  (2013/Jun)
     * mod GoToLoop (2013/Dec)
     * refactor ver (2016/Nov/30)
     *
     * forum.Processing.org/two/discussion/19200/
     * create-10-instances-of-an-object-python#Item_8
     *
     * forum.Processing.org/one/topic/nullpointerexeption-with-an-arraylist
     * forum.Processing.org/two/discussion/2171/effect-in-processing#Item_3
     *
     * p5js.SketchPad.cc/sp/pad/view/ro.CwHWpJ$SP1EN8i/latest
     * studio.ProcessingTogether.com/sp/pad/export/ro.9oyKfI9kOIa77/latest
     */
    
    "use strict";
    
    const balls = [];
    let bg;
    
    function setup() {
      createCanvas(600, 400).mouseClicked(() => {
        if (mouseButton != CENTER)  balls.push( new Ball );
        else balls.length && --balls.length;
      });
    
      frameRate(60).ellipseMode(CENTER).blendMode(REPLACE);
      fill(Ball.COLOUR).noStroke();
    
      bg = color(0);
    }
    
    function draw() {
      background(bg);
      for (let b of balls)  b.script();
      document.title = '# Balls: ' + balls.length;
    }
    
    class Ball {
      constructor() {
        this.x = mouseX, this.y = mouseY;
    
        this.spX = ~~random( Ball.MIN_SPD, Ball.MAX_SPD );
        random(1) < .5 && (this.spX *= -1);
    
        this.spY = ( ~~random( Ball.MIN_SPD, Ball.MAX_SPD ) *
                   ( random(1) < .5 && -1 || 1 ) );
      }
    
      script() {
        this.bump(), this.show();
      }
    
      bump() {
        (this.x += this.spX)<Ball.RAD | this.x>width-Ball.RAD && (this.spX *= -1);
        this.y += this.spY *= this.y<Ball.RAD | this.y>height-Ball.RAD && -1 || 1;
      }
    
      show() {
        ellipse(this.x, this.y, Ball.DIAM, Ball.DIAM);
      }
    }
    
    Ball.DIAM = 20, Ball.RAD = Ball.DIAM >> 1;
    Ball.MIN_SPD = 1, Ball.MAX_SPD = 5 + 1;
    Ball.COLOUR = 'yellow';
    
  • Thanks to you both. Having a side-by-side examples of multiple objects in Java mode, Python mode, and p5.js seems really useful -- a kind of "Rosetta Stone" for the learning community.

Sign In or Register to comment.