首页 > 解决方案 > Pygame Cass Function for creating platforms without manually creating every single platform

问题描述

I am creating a platform game and I am trying to shorten my code by creating a class for the platforms. However, my code doesn't run and I am unsure on what the error that's displayed.

My code:

import pygame,sys,time,random
pygame.init()

#COLOUR
light_red=(255,99,71)

res_x,res_y=800,600
display = pygame.display.set_mode((res_x,res_y))
display.fill(black)
pygame.display.update()
clock=pygame.time.Clock()
fps=60

class Rect:
        def __int__(self,color,x,y,l,h,th):
                self.color=color
                self.x=x
                self.y=y
                self.l=l
                self.h=h
                self.th=th


rect1=pygame.draw.rect(display,Rect('light_red','random.randrange(0,150)','150','300','50','5'))



 pygame.display.update()

The error shown:

    rect1=pygame.draw.rect(display,Rect('light_red','random.randrange(0,150)','150','300','50','5'))
TypeError: Rect() takes no arguments

标签: pythonpython-3.xclasspygame

解决方案


  1. You've misspelled __init__ in your Rect class.

  2. pygame.draw.rect takes a surface, a color and a rect-style object which can be a pygame.Rect, a list or a tuple with four elements. Your custom Rect class won't work, but you could pass a tuple:

    rect = Rect(light_red, random.randrange(0,150), 150, 300, 50, 5)
    rect1n = pygame.draw.rect(display, rect.color, (rect.x, rect.y, rect.l, rect.h))
    
  3. The arguments should not be strings:

    Rect(light_red, random.randrange(0,150), 150, 300, 50, 5)
    
  4. You could just give your Rect a draw method in which you call pygame.draw.rect (also give it a self.rect attribute instead of the separate self.x, etc. attributes):

    class Rect:
        def __init__(self,color,x,y,l,h,th):
            self.color = color
            self.th = th
            # Just create a pygame.Rect object to store the attributes.
            self.rect = pygame.Rect(x, y, l, h)
    
        def draw(self, surface):
            pygame.draw.rect(display, self.color, self.rect)
    
    rect = Rect(light_red, random.randrange(0,150), 150, 300, 50, 5)
    
    # Then draw it like this in the while loop.
    rect.draw(display)
    

I recommend checking out how pygame sprites and sprite groups work and then turn your platform class into a pygame.sprite.Sprite subclass. If you want to see a simple platformer example with sprites and groups, take a look at this answer.


Also, better choose another name for your Rect class, since there's already the pygame.Rect class.


推荐阅读