如何使用函数将代码编译成Class

时间:2019-03-29 00:50:49

标签: python-3.x class pygame

我不知道如何将这段代码转换为类语句然后运行它!

我希望具有与此相同的结果,但使用类语句。

import pygame
import random
pygame.init()
winh = 500
winl = 500
win = pygame.display.set_mode((winh, winl))

width = 20

vel = 5

y = 250
x = 250

score = 0

direction = "up"

class Dot():
    def __init__(self):
        self.x = x
        self.y = y
        self.width = width
        self.direction = 'right'
    def direction(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
        keys = pygame.key.get_pressed()

        if keys[pygame.K_w]:
            self.direction = "up"
        if keys[pygame.K_a]:
            self.direction = "left"
        if keys[pygame.K_s]:
            self.direction = "down"
        if keys[pygame.K_d]:
            self.direction = "right"

p = True

run = True
while run:
    pygame.time.delay(100)


    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    keys = pygame.key.get_pressed()

    if keys[pygame.K_w]:
        direction = "up"
    if keys[pygame.K_a]:
        direction = "left"
    if keys[pygame.K_s]:
        direction = "down"
    if keys[pygame.K_d]:
        direction = "right"

    if direction == "up":
        y -= width
    if direction == "down":
        y += width
    if direction == "left":
        x -= width
    if direction == "right":
        x += width

    if y > winh - 20:
        y = 20
    if y < 20:
        y = winh - 20
    if x > winl - 20:
        x = 20
    if x < 0:
        x = winl - 20
    win.fill((0,0,0))
    dot = pygame.draw.rect(win, (0, 255, 0), (x, y, width, width))



    pygame.display.update()


pygame.quit()

1 个答案:

答案 0 :(得分:0)

所以您上课已经到了那里。类是对该“对象”通用的数据和功能的封装。有关该对象的任何内容都应归入此类。但是,当将用于键盘处理的代码放入Dot类中时,这是朝错误的方向进行的。 Dot是画在屏幕上的东西,它具有大小,颜色和位置。它不应负责处理用户输入。这超出了Dot的范围。

更新类时,我选择将其基于PyGame sprite class。首先需要做更多的工作,并且需要以特定的方式编写-具有imagerect和(希望)有update()函数。但是作为精灵,它会获得许多已经编写的功能,包括PyGame collision routines

在主循环附近,有几个附加项。首先是创建精灵dotty和一个sprite-group sprites来容纳它。为单个子画面创建一个子画面组有点奇怪,但是我认为将来会有不止一个。

然后在实际循环中,代码调用sprites.update()。这是一个方便的例程,它为组中的每个精灵调用update()函数。然后,随后调用sprites.draw( win ),将组中的每个子画面绘制到屏幕上。这将使用精灵的imagerect来了解绘制位置和绘制内容。

import pygame
import random
pygame.init()
WIN_H = 500
WIN_L = 500
win = pygame.display.set_mode((WIN_H, WIN_L))

width = 20

vel = 5

y = 250
x = 250

score = 0

direction = "up"


class Dot( pygame.sprite.Sprite ):
    def __init__( self, x,y, size=20, direction='right', colour=(0,255,0) ):
        pygame.sprite.Sprite.__init__( self )
        self.size      = size
        self.colour    = colour
        self.direction = direction
        self.image     = pygame.Surface( ( size, size ), pygame.SRCALPHA )
        self.rect      = self.image.get_rect()
        self.rect.x    = x
        self.rect.y    = y
        self.image.fill( colour )

    def move( self, x_dir, y_dir ):
        global WIN_H, WIN_L

        # Adjust our co-oridinates
        self.rect.x += x_dir
        self.rect.y += y_dir

        # Stay on the screen, and wrap around
        if (self.rect.left >= WIN_L ):
            self.rect.right = 0
        elif (self.rect.right <= 0 ):
            self.rect.left = WIN_L
        if (self.rect.top >= WIN_H ):
            self.rect.bottom = 0
        elif (self.rect.bottom <= 0):
            self.rect.top = WIN_H

    def update( self ):
        # TODO - handle animation, collisions, whatever
        pass


# make some sprites
dotty = Dot( x,y )
sprites = pygame.sprite.Group()   # a group, for a single sprite (or more)
sprites.add( dotty )

p = True
run = True
while run:
    pygame.time.delay(100)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    keys = pygame.key.get_pressed()

    if keys[pygame.K_w]:
        direction = "up"
    if keys[pygame.K_a]:
        direction = "left"
    if keys[pygame.K_s]:
        direction = "down"
    if keys[pygame.K_d]:
        direction = "right"

    if direction == "up":
        dotty.move( 0, -width )
    if direction == "down":
        dotty.move( 0, width )
    if direction == "left":
        dotty.move( -width, 0 )
    if direction == "right":
        dotty.move( width, 0 )

    # update all the sprites
    sprites.update()

    # repaint the screen
    win.fill((0,0,0))
    sprites.draw( win )
    #dot = pygame.draw.rect(win, (0, 255, 0), (x, y, width, width))



    pygame.display.update()


pygame.quit()

移动代码已移至Dot类中。这使Dot可以调整其位置,但也可以解决屏幕包装问题。如果说这个精灵,是某种射弹,也许当它越过屏幕边界时,它将调用sprite.kill()函数将自己从精灵组中删除。但是由于Dot显然不是弹丸,所以它可以向另一侧弯曲。