首页 > 解决方案 > 如何将代码编译成带有函数的类

问题描述

不知道怎么把这段代码变成类语句然后运行!

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

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()

标签: python-3.xclasspygame

解决方案


所以你上课已经到了。类是对该“对象”通用的数据和函数的封装。任何与该对象有关的或有关该对象的内容都应归入此类。但是当键盘处理的代码被放到一个Dot类中时,这是朝着错误的方向发展的。ADot是绘制到屏幕上的东西,它具有大小、颜色和位置。它不应该负责处理用户输入。这超出了 a 的范围Dot

更新类时,我选择基于PyGame sprite 类。起初这需要做更多的工作,并且需要以特定的方式编写 - 有一个image, 和一个rect, 和(希望)一个update()函数。但是作为一个精灵,它有很多已经编写好的功能,包括 PyGame碰撞例程

在主循环附近,有一些补充。首先是创建 spritedotty和一个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()函数将自己从精灵组中移除。但由于 aDot显然不是弹丸,它可以弯曲到另一边。


推荐阅读