首页 > 解决方案 > 如何在pygame上显示随机精灵颜色

问题描述

我希望能够创建一个函数,如果玩家收集到一个点,他们将在 4 种颜色选项中变为随机颜色。一旦精灵与主循环中的点发生碰撞,我计划调用 changeColour() 函数,因此精灵会改变颜色,但我无法让精灵改变颜色。(注意:这是使用 pygame 的代码的一部分)


/// the function used for the colours

def randomColour(): # function for random colour 
    rand = random.randint(0,3) # random number from 0-3 
    if(rand == 0): # different numbers will return different colours
        return PURPLE # 0 returns purple
    elif(rand == 1): 
        return RED # 1 returns Red
    elif(rand == 2):
        return TEAL # 2 returns Teal
    elif(rand == 3):
        return YELLOW # 3 rerurns Yellow

r_colour = randomColour()


/// this cube class is whats used to create the player sprite and food item



class cube(object):  
    rows = 20 # used to make grdis and draw later
    w = 500 # will using squares , this will also be use to calculate space
    def __init__(self,start,dirnx=1,dirny=0,color=(r_colour)):
        self.pos = start
        self.dirnx = 1 # so that player sprite can always be moving 
        self.dirny = 0
        self.color = color # the color of the cube 

    def draw(self, surface, eyes=False): # draws the cube object used for both the player and the snack
        dis = self.w // self.rows
        i = self.pos[0] 
        j = self.pos[1]
        
        pygame.draw.rect(surface, self.color, (i*dis+1,j*dis+1, dis-2, dis-2))
        if eyes: # eyes for the player sprite to be drawn on
            centre = dis//2
            radius = 3 
            circleMiddle = (i*dis+centre-radius,j*dis+8) # two circles drawn on as eyes / size of eyes 
            circleMiddle2 = (i*dis + dis -radius*2, j*dis+8) 
            pygame.draw.circle(surface, (WHITE), circleMiddle, radius) # draws eyes 
            pygame.draw.circle(surface, (WHITE), circleMiddle2, radius)



/// player object 

class player(object): # new class which will contain the contents of the player
    body = []
    turns = {}
    def __init__(self , color, pos):
        self.color = randomColour()
        self.head = cube(pos) # uses the position of the player to navigate 
        self.body.append(self.head)
        self.dirnx = 0 
        self.dirny = 1 # starts off with movement / player always moving.


def draw(self, surface): # draw the player onto the screen
        for i, c in enumerate(self.body):
            if i ==0: # draws the eyes of the player sprite so player can identify the sprite 
                c.draw(surface, True)


/// redraw window function and the main loop 

def redrawWindow(surface): # this will let the screen get updated every time its called
    global rows, width, p, snack
    surface.fill((BLACK)) # Fills the screen with colour black
    p.draw(surface)
    snack.draw(surface) # draws snack item
    drawGrid(width,rows, surface) # Will draw our grid lines
    pygame.display.update()


def main():
    global width, rows, p, snack
    width = 500
    rows = 20
    win = pygame.display.set_mode((width, width)) # draws the window for the game
    pygame.display.set_caption("Colour Run") # changes name of the window
    p = player((randomColour()), (10,10)) # the player 
    snack = cube(randomSnack(rows, p), color=(0,0,255)) # the point to be collected 
    run = True # marks runas true so game state will be running 

    clock = pygame.time.Clock()
    
    while run: 
        pygame.time.delay(50) #
        clock.tick(8) #
        p.move() # allows for the player to move 
        if p.body[0].pos == snack.pos: # checks if player has collided with the point 
            p.changeColour() # changes the colour of the sprite /// trying to use this 
            snack = cube(randomSnack(rows, p), color=(0,0,255)) # respawns the point 


/// note this isnt the whole code only part of it

标签: pythonfunctioncolorspygamesprite

解决方案


我对 pygames 没有太多经验,所以这里可能缺少一些东西,但是您的 Player 类没有 .changeColour() 方法?

如果这是问题,那么您可以添加这样的方法:

class player(object): # new class which will contain the contents of the player
    body = []
    turns = {}
    def __init__(self , color, pos):
        self.color = randomColour()
        self.head = cube(pos) # uses the position of the player to navigate 
        self.body.append(self.head)
        self.dirnx = 0 
        self.dirny = 1 # starts off with movement / player always moving.
   
    def changeColour(self):
        self.color = randomColour()

你也可以像这样清理你的 randomColour() 函数:

def randomColour():
    rand = random.randint(0,3)
    colors = (PURPLE, RED, TEAL, YELLOW)
    return colors[rand]

请注意,您的函数可以返回与您的 Player 更改之前的颜色相同的颜色。


推荐阅读