简体   繁体   English

我的班级在这个简单的角色移动脚本中无法正常工作

[英]my class isn't working in this simple character movement script

import pygame, sys
from pygame.locals import *

bifl = 'screeing.jpg'
milf = 'char_fowed_walk1.png'

pygame.init()

screen = pygame.display.set_mode((640, 360),0, 32)
background = pygame.image.load(bifl).convert()
mouse_c = pygame.image.load(milf).convert_alpha()

x, y = 0, 0
movex, movey = 0, 0


class move:
    def moveUp():
        movey =- 0.3
    def moveDown():
        movey =+ 0.3
    def moveLeft():
        movex =- 0.3
    def moveRight():
        movex =+ 0.3

    def stopUp():
        movey = 0
    def stopDown():
        movey = 0
    def stopLeft():
        movex = 0
    def stopRight():
        movex = 0




while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_LEFT:
                move.moveLeft()
            elif event.key == K_RIGHT:
                move.moveRight()
            elif event.key == K_UP:
                move.moveUp()
            elif event.key == K_DOWN:
                move.moveDown()

        if event.type == KEYUP:
             if event.key == K_LEFT:
                 move.stopLeft()
             elif event.key == K_RIGHT:
                 move.stopRight()
             elif event.key == K_UP:
                 move.stopUp()
             elif event.key == K_DOWN:
                 move.stopDown()

    x += movex
    y += movey

    screen.blit(background, (0, 0))
    screen.blit(mouse_c, (x, y))

    pygame.display.update()

when i run this everything works only that the player doesn't move, i testes this without classes and functions and it work so it's definitely something to do with the classes i added. 当我运行此程序时,所有操作仅在播放器不会移动的情况下进行,我在没有类和函数的情况下对此进行了测试,并且它可以正常工作,因此与添加的类肯定有关。 pygame is installed correctly i am using python 2.7 and i have used pygame in other scripts and it works fine. pygame已正确安装,我正在使用python 2.7,并且我已在其他脚本中使用pygame,并且工作正常。

Since movex and movey are inside a function, they are locals, their values will never change outside the function (it will always be 0 from the movex, movey = 0, 0 line). 由于movexmovey在函数内部,因此它们是movey变量,因此它们的值永远不会在函数外部更改(从movex, movey = 0, 0始终为0 movex, movey = 0, 0行)。 Read about variable scopes in Python. 了解Python中的变量作用域。

You have to either put a global movex and global movey inside the move class or return the value of movex and movey on the functions, and use that returned value on the event capturing loop, like: 您必须将global movexglobal movey放在move类中,或者在函数上返回movexmovey的值,然后在事件捕获循环中使用该返回的值,例如:

if event.key == K_LEFT:
    y += move.stopLeft()

I'd reorganize the entire thing and have a separate file for the move functions instead of a class, though. 我将重新组织整个过程,并为移动功能(而不是类)提供一个单独的文件。

I'd take a totally different approach and store your x/y coordinations in a object that knows how to alter them: 我将采用一种完全不同的方法,将您的x / y坐标存储在一个知道如何更改它们的对象中:

import pygame, sys
from pygame.locals import *

class Position(object):
    def __init__(self):
        self.x = 0
        self.y = 0

    def moveUp(self):
        self.y =- 0.3

    def moveDown(self):
        self.y =+ 0.3

    def moveLeft(self):
        self.x =- 0.3

    def moveRight(self):
        self.x =+ 0.3

pos = Position()

movemap = {
    (KEYDOWN, K_LEFT): pos.moveLeft,
    (KEYDOWN, K_RIGHT): pos.moveRight,
    (KEYDOWN, K_UP): pos.moveUp,
    (KEYDOWN, K_DOWN): pos.moveDown,
}

bifl = 'screeing.jpg'
milf = 'char_fowed_walk1.png'

pygame.init()

screen = pygame.display.set_mode((640, 360),0, 32)
background = pygame.image.load(bifl).convert()
mouse_c = pygame.image.load(milf).convert_alpha()

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

        try:
            action = movemap[(event.type, event.key)]
        except KeyError:
            continue

        action()

    screen.blit(background, (0, 0))
    screen.blit(mouse_c, (pos.x, pos.y))

    pygame.display.update()

First, the Pythony stuff: in Python 2.7, classes should explicit inherit from object . 首先,Pythony的东西:在Python 2.7中,类应显式继承自object That's the class Position(object) part. 那是class Position(object)一部分。 Also, the first argument to an instance method is an instance object. 同样,实例方法的第一个参数是实例对象。 That's all the self stuff. 这就是self东西。 Finally, you don't have to put regular functions in classes. 最后,你不必把普通功能类。 It's perfectly OK to have a dosomething(): return 5 function at the top level of a module. 拥有dosomething(): return 5是完全可以的dosomething(): return 5在模块的顶层dosomething(): return 5函数。

Now, on to the rest: 现在,接下来的内容:

A Position object knows how to mutate its own state. Position对象知道如何改变其自身的状态。 By making a dict that maps combinations of key events to methods, you don't have to have those long if/elif/elif blocks. 通过做出将键事件的组合映射到方法的命令,您不必具有较长的if/elif/elif块。 You can also ignore every keyup event; 您也可以忽略每个键入事件。 just don't do anything unless the user is pressing a key. 除非用户按下某个键,否则什么也不要做。

Zooming in a bit: 放大一点:

movex =- 0.3

You want 你要

movex -= 0.3

your version is actually understood by python to be: 您的版本实际上被python理解为:

movex = (- 0.3)

Which is to say, negate 0.3 and assign the result to a local variable named movex , Likewise: movex =+ 0.3 is "make sure 0.3 is a number and assign it to movex". 也就是说,取反0.3并将结果分配给名为movex局部变量,同样: movex =+ 0.3是“确保0.3是数字并将其分配给movex”。

In place operators put the operator before the equal sign. 就位运算符将运算符放在等号之前 Just fixing that will give you a somewhat helpful traceback, telling you that you can't assign a variable that hasn't been declared yet, since it still looks to the python interpreter like you want movex and movey to be locals. 仅仅解决这个问题将为您提供一些有用的回溯,告诉您不能分配尚未声明的变量,因为它仍然像希望movexmovey成为本地movey一样看起来像python解释器。 Fixing that would be: 解决的办法是:

def moveLeft(self):
    global movex
    movex -= 0.3 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM