我最近開始用python編程,到目前爲止我都喜歡它。我以前編程在C#和Java,這可能是我的問題。在c#中,如果你有一個公共變量,它會在每個方法中改變。對不好的解釋,但它會更容易可視化的代碼。在分配值之前引用了Python全局變量
這段代碼是我想在c#窗體中發生的一個例子。代碼實際上並不工作,因爲它只是一個例子。
class Player
{
public var player; //create the variable
public var playerRectangle;
public var playerMovement;
public Player()
{
player = pygame.image.load("player.png"); //set the variables value
playerRectangle = player.get_rect();
playerMovement = new int[0,0];
}
public void Update()
{
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_w:
playerMovement[1] = -2 //use the variables value
if event.type == pygame.KEYDOWN and event.key == pygame.K_s:
playerMovement[1] = 2
if event.type == pygame.KEYDOWN and event.key == pygame.K_a:
playerMovement[0] = -2
if event.type == pygame.KEYDOWN and event.key == pygame.K_d:
playerMovement[0] = 2
if event.type == pygame.KEYUP and event.key == pygame.K_w:
playerMovement[1] = 0
if event.type == pygame.KEYUP and event.key == pygame.K_s:
playerMovement[1] = 0
if event.type == pygame.KEYUP and event.key == pygame.K_a:
playerMovement[0] = 0
if event.type == pygame.KEYUP and event.key == pygame.K_d:
playerMovement[0] = 0
playerRectangle = playerRectangle.move(playerMovement)
}
}
實際的Python代碼是:
import pygame
class Player:
player = None #create the variable
playerRectangle = None
playerMovement = None
def __init__():
global player
player = pygame.image.load("player.png") #set the variables value
global playerRectangle
playerRectangle = player.get_rect()
global playerMovement
playerMovement = [0,0]
def update():
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_w:
playerMovement[1] = -2 #use the variables !!ERROR!!
if event.type == pygame.KEYDOWN and event.key == pygame.K_s:
playerMovement[1] = 2
if event.type == pygame.KEYDOWN and event.key == pygame.K_a:
playerMovement[0] = -2
if event.type == pygame.KEYDOWN and event.key == pygame.K_d:
playerMovement[0] = 2
if event.type == pygame.KEYUP and event.key == pygame.K_w:
playerMovement[1] = 0
if event.type == pygame.KEYUP and event.key == pygame.K_s:
playerMovement[1] = 0
if event.type == pygame.KEYUP and event.key == pygame.K_a:
playerMovement[0] = 0
if event.type == pygame.KEYUP and event.key == pygame.K_d:
playerMovement[0] = 0
playerRectangle = playerRectangle.move(playerMovement)
def returnTexture():
return player
def returnRectangle():
return playerRectangle
它說,它被賦予了值之前變量被引用,但我把它在構造函數的值。