python - 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
解决方案
You've misspelled
__init__
in yourRect
class.pygame.draw.rect
takes a surface, a color and a rect-style object which can be apygame.Rect
, a list or a tuple with four elements. Your customRect
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))
The arguments should not be strings:
Rect(light_red, random.randrange(0,150), 150, 300, 50, 5)
You could just give your
Rect
adraw
method in which you callpygame.draw.rect
(also give it aself.rect
attribute instead of the separateself.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.
推荐阅读
- python - 无法使用 conda 安装 Pygame
- javascript - 如何在 svelte 中的 for 循环迭代之间更新 DOM?
- ios - 在 Swift UITextFieldDelegate 中如何在编辑文本时触发动作?
- python - 如何在 kubeflow 管道中定义管道级卷以跨组件共享?
- java - 我可以在 Java 的循环中为一系列值创建变量名吗?
- awk - 识别 awk 字段分隔符中的反斜杠
- python - 如何使用 tf.keras.preprocessing.image.smart_resize(image, IMAGE_SIZE)?
- d3.js - d3.scaleBand 中的填充
- oracle-apex - 是否所有使用 20.1 之前的版本开发的应用程序都易受攻击?
- junit5 - 如何按特定顺序运行 Jupiter 测试类?