我一直在尝试使用def on_mouse_click
来更改另一个对象的值。我正在使用pyglet制作游戏。它看起来像这样:
import random, math, time
import pyglet
from pyglet.gl import *
window = pyglet.window.Window(640, 480, visible=False, caption="Pong")
window.set_location(window.screen.width/2 - window.width/2, window.screen.height/2 - window.height/2)
batch = pyglet.graphics.Batch()
class Ball(pyglet.sprite.Sprite):
def __init__(self):
pattern = pyglet.image.SolidColorImagePattern((139, 90, 43, 120))
image = pyglet.image.create(8,8,pattern)
image.anchor_x, image.anchor_y = 20, 0
pyglet.sprite.Sprite.__init__(self, image, batch=batch)
def reset(self):
self.x, self.y = 0 ,0
angle = random.random()*math.pi/2
self.vx, self.vy = math.sin(angle)*300, math.cos(angle)*300
@window.event
def on_resize(width, height):
glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, 800, 0, 600, -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
return pyglet.event.EVENT_HANDLED
keymap = pyglet.window.key.KeyStateHandler()
window.push_handlers(keymap)
states = []
class PausedState:
def update(self, dt):
if keymap[pyglet.window.key.SPACE]:
states.pop()
class GameState:
def __init__(self):
self.b = Ball()
self.b.reset()
def update(self, dt):
@window.event
def on_mouse_press(x, y, button, modifiers):
self.b.angle = 0
self.b.x += self.b.vx *dt
self.b.y += self.b.vy *dt
@window.event
def on_draw():
window.clear()
batch.draw()
def update(dt):
if len(states):
states[-1].update(dt)
else:
pyglet.app.exit()
states.append(GameState())
states.append(PausedState())
pyglet.clock.schedule_interval(update, 1.0/60.0)
window.clear()
window.flip()
window.set_visible(True)
pyglet.app.run()
我收到的错误是global 'self is not defined'
。我希望通过单击鼠标左键来改变球的角度。提前致谢! :)
答案 0 :(得分:0)
您是否尝试声明像下面这样的setter方法? :
#in your class
def setB(new_b):
self.b = new_b