Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert my function into an array without it being called?

Tags:

python

pygame

I have this pygame code which has some functions, I want to be able to put the functions apple1() and apple2() in the list without it being called immediately and then be able to call it from the list.

This is what i tried:

 #for all the apple
 def apple1():
   pygame.draw.rect(screen,COLOR.GREEN, [ posR,posU, apblock, apblock])

 def apple2():
   pygame.draw.rect(screen,COLOR.RED, [ posiR,posiU, apblock, apblock])

 def random_apple():
   array = [apple1(),apple2()]
   i = random.randrange(0,1)

   x = array[i]
   return x

 def time_apple():
     while time == True:
        random_apple()
        time.sleep(5)
like image 972
Curtis Crentsil Avatar asked Jun 25 '26 03:06

Curtis Crentsil


1 Answers

Remove the parentheses from their names.

Also, I think you'll either want to use randrange(0,2) or randint(0,1).

def random_apple():
   array = [apple1,apple2]
   i = random.randrange(0,2)

   x = array[i]
   return x()

Edit: For a slightly more Pythonic solution, obviating the need for the random_apple function, you might consider:

# import as needed
import random
import pygame
import time

#for all the apple
def apple1():
  pygame.draw.rect(screen,COLOR.GREEN, [ posR,posU, apblock, apblock])

def apple2():
  pygame.draw.rect(screen,COLOR.RED, [ posiR,posiU, apblock, apblock])

def time_apple():
  while time == True:
    random.choice([apple1, apple2])()
    time.sleep(5)
like image 52
sloppypasta Avatar answered Jun 26 '26 16:06

sloppypasta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!