【发布时间】:2015-11-24 19:31:50
【问题描述】:
我是编程新手,我正在尝试设置一个模拟,其中一个圆圈以随机模式移动,并被第二个圆圈追逐。最终我希望添加 5 个圆圈作为随机移动的干扰物。
在代码中,我将随机移动的圆圈称为“鼠标”,将追逐的圆圈称为“猫”。
我在网上研究并查看了其他人的代码以获取想法,这是我迄今为止提出的:
from pygame import *
import random
import sys, pygame, math, random
from pygame.locals import *
pygame.init()
background_colour = (255,255,255)
(width, height) = (1024, 768)
screen = pygame.display.set_mode((width, height),pygame.FULLSCREEN)
class Mouse(pygame.sprite.Sprite):
def __init__(self, (x, y), size):
pygame.sprite.Sprite.__init__(self)
self.x = MX
self.y = MY
self.size = 30
self.colour = (0, 0, 0)
self.thickness = 2
self.speed = 2
self.angle = random.uniform(0, math.pi*2)
def display(self):
pygame.draw.circle(screen, self.colour, (int(MX), int(MY)), self.size, self.thickness)
def move(self):
self.x += math.sin(self.angle) * self.speed
self.y -= math.cos(self.angle) * self.speed
class Cat(pygame.sprite.Sprite):
def __init__(self, (x, y), size):
pygame.sprite.Sprite.__init__(self)
self.x = CX
self.y = CY
self.size = 30
self.colour = (0, 0, 0)
self.thickness = 2
self.speed = 2
self.angle = random.uniform(0, math.pi*2)
pixChangeC = 2
def display(self):
pygame.draw.circle(screen, self.colour, (int(CX), int(CY)), self.size, self.thickness)
def move(self):
if MX >= CX:
CX += pixChangeC
else:
CX -= pixChangeC
if MY >= CY:
CY += pixChangeC
else:
CY -= pixChangeC
def main():
pygame.display.set_caption('Chase')
mouse = Mouse()
cat = Cat()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
screen.fill(background_colour)
mouse.display()
mouse.move()
cat.display()
cat.move()
pygame.display.flip()
不幸的是,当我尝试像这样运行代码时,我收到以下错误消息:
" 文件 "C:...",第 75 行,在 鼠标.display() AttributeError: 'module' 对象没有属性 'display'"
我在网上找不到关于哪里出错的答案,所以如果有人有一些建议/想法,我将不胜感激!
【问题讨论】:
-
看起来你的缩进也有点不对劲。也许这只是一个拙劣的复制粘贴工作。
running = True下的所有内容都是main()块的一部分吗?按照以下答案中的建议将您的实例更改为myMouse和myCat会更清楚,并且可以帮助避免这种情况。至少会使逻辑调试更容易。
标签: python pygame attributeerror