[英]Compositing a class and calling it's functions. How to pick the correct instance?
So Im writing a pygame game and the code is kinda big but I will explain what my problem is. 所以我正在写一个pygame游戏,代码有点大,但是我会解释我的问题是什么。 I can also post the code if needed.
如果需要,我也可以发布代码。
So I have a PlayerData
class and a EventManager
class in pygame, with Python 3.3.2. 所以我在pygame中有一个使用Python 3.3.2的
PlayerData
类和一个EventManager
类。 PlayerData
class have 3 methods, self.move_left(self)
, self.move_right(self)
that changes the position vector depending on the keyboard input, (specificaly x coordinates since it's 2D). PlayerData
类具有3种方法, self.move_left(self)
, self.move_right(self)
根据键盘输入更改位置矢量(特别是x坐标,因为它是2D)。 The 3rd method is self.update_pos(self)
. 第三种方法是
self.update_pos(self)
。 It takes the position vector, and assign it to the player rect.left/rect.top. 它获取位置矢量,并将其分配给播放器rect.left / rect.top。 The movement functions have a flag parameter, I use it in the
EventManager
class. 运动函数有一个标志参数,我在
EventManager
类中使用它。
So far this is clear and decent for the player class. 到目前为止,对于玩家阶层来说,这是显而易见的。 Here comes the problem.
问题来了。 In my
EventManager
class I have a for loop that checks for keys pressed/released. 在我的
EventManager
类中,我有一个for循环,用于检查按下/释放的键。 In the __init__()
I have called self.player = playerData()
only. 在
__init__()
我仅调用了self.player = playerData()
。 If a key is pressed I call self.player.move_left(flag=True)
that is defined in the PlayerData
class. 如果按下某个键,我将调用
PlayerData
类中定义的self.player.move_left(flag=True)
。 If the same key is released i call self.player.move_left(flag=False)
, so it stop's subtract pixels to move left. 如果释放相同的键,则调用
self.player.move_left(flag=False)
,因此它将停止减去像素以向左移动。
Again, so far, so good I think. 再一次,到目前为止,我认为很好。 But then I hit the Game Loop, which is like this:
Handle events
Update game state
Draw
In the Handle events block, I check for key and if pressed I call the PlayerData
method to move. 但是随后我点击了Game Loop,如下所示:
Handle events
Update game state
Draw
在处理事件块中,我检查按键,如果按下,则调用PlayerData
方法进行移动。 (Means to re-define x,y coordinates of a position Vector defined in the PlayerData
class). (用于重新定义
PlayerData
类中定义的位置向量的x,y坐标)。 Then I go to the Update data block, there I call Player.update_pos()
, which assigns the new position coordinates to the player rectangle shape. 然后转到Update数据块,在其中调用
Player.update_pos()
,它将新的位置坐标分配给播放器矩形形状。 Then I redraw the player. 然后我重画播放器。
The problem is the position Vector is not changed when I call the update_pos()
method. 问题是当我调用
update_pos()
方法时,位置Vector不会更改。 Here is the code. 这是代码。
import pygame
import sys
import datetime
from pygame.locals import *
from datetime import timedelta
class Vector(object):
''' Performs vector aritmetics
'''
def __init__(self, x, y):
self.x = x
self.y = y
def add(self, v):
x = self.x + v.x
y = self.y + v.y
return Vector(x, y)
class GroundTerrain(object):
''' Ground data structure.
Creates a ground data structure and her component's.
'''
def __init__(self):
self.position = Vector(0, 334) # TODO: Remove the hard coding
self.color = (128, 128, 128) # Gray
self.width = WINDOWWIDTH
self.height = 166
self.ground = {'shape': pygame.Rect((self.position.x, self.position.y),
(self.width, self.height)),
'color': self.color
}
def draw_ground(self):
''' Draw's the ground shape and color using pygame.draw.rect(...).
'''
pygame.draw.rect(WINDOWSURFACE, self.ground['color'],
self.ground['shape'])
class PlayerData(object):
''' Player data structure.
Creates a player data structure and handles few actions.
'''
def __init__(self):
self.ground = GroundTerrain()
self.position = Vector(15, 264) # TODO: Remove the hard coding
self.size = Vector(50, 70)
self.velocity = Vector(5, 5)
self.gravity = Vector(0, -10)
self.color = (0, 100, 0) # Dark Green
self.player = {'shape': pygame.Rect((self.position.x, self.position.y),
(self.size.x, self.size.y)),
'color': self.color}
def move_left(self, flag=False):
''' Moves the player shape horizontally
if it's inside window borders.
'''
if flag and self.position.x > 0:
self.position.x = self.position.x - self.velocity.x
def move_right(self, flag=False):
''' Moves the player shape horizontally
if it's inside window borders.
'''
if flag and self.position.x + self.size.x < WINDOWWIDTH:
self.position.x = self.position.x + self.velocity.x
def update_pos(self):
self.player['shape'].left = self.position.x
self.player['shape'].top = self.position.y
def draw_player(self):
''' Draw's the player shape and color using pygame.draw.rect(...).
'''
pygame.draw.rect(WINDOWSURFACE, self.player['color'],
self.player['shape'])
class EventManager(object):
''' Handles keyboard event's.
Toggles player variables according to the event's.
'''
def __init__(self):
self.player = PlayerData()
def set_variables(self):
''' Toggles player variables according to keyboard/mouse event's.
'''
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_LEFT or event.key == ord('a'):
self.player.move_left(True)
if event.key == K_RIGHT or event.key == ord('d'):
self.player.move_right(True)
if event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_LEFT or event.key == ord('a'):
self.player.move_left(False)
if event.key == K_RIGHT or event.key == ord('d'):
self.player.move_right(False)
#-------------------------------------------------------------------------
WINDOWWIDTH = 900
WINDOWHEIGHT = 500
WINDOWSURFACE = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Placeholder')
MAIN_CLOCK = pygame.time.Clock()
FPS = 40
def main():
pygame.init()
Ground = GroundTerrain()
Player = PlayerData()
EventHandle = EventManager()
while True:
# Handle events
EventHandle.set_variables()
# Update game state
Player.update_pos()
# Draw
WINDOWSURFACE.fill((0, 0, 0)) # Black
Ground.draw_ground()
Player.draw_player()
pygame.display.update()
MAIN_CLOCK.tick(FPS)
main()
class EventManager(object):
''' Handles keyboard event's.
Toggles player variables according to the event's.
'''
def __init__(self, player):
self.player = player
...
pass the player into the EventManager 将玩家传递到EventManager
player = PlayerData()
EventHandle = EventManager(player)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.