变量的值未按预期变化

时间:2019-12-19 12:08:30

标签: python python-3.7

所以我要做的是更改变量(targetx)的值,它的初始值是随机分配的targetx = random.randrange(0,500,1) 该值可以在0到500之间的任何位置,需要一次将其值更改为0,例如444,443,442 ...,0这个值达到零,我希望它一次又一次回到500, 这是我尝试过的:

targeVel是步数,在这种情况下,一旦值达到1(或targetVel的值),它将停止并开始在targetVeltargetVel*2之间切换

    if targetx >= 1 and moving == True:
        targetx-= targetVel
        if targetx <= 1:
            moving = False

    else:
        #targetx <= targetVel:
        targetx+= targetVel
        if targetx <= 500:
            moving = True

这是完整的代码:

import random

pygame.init()

win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("name")

moving = True

shipx = 10
shipy = 10
shipVel = 2
shipWidth = 64
shipLength = 64

targetVel = random.randrange(1,3,1)
targetx = random.randrange(0,500,1)
targety = random.randrange(0,500,1)

shipImg = pygame.image.load('res/ufo.png')
targetImg = pygame.image.load('res/man.png')

def turnl():
    if targetx <= 0:
        targetx+= targetVel

def turnr():
    if targetx >= 500:
        targetx-= argetVel

def ship():
    win.blit(shipImg, (shipx, shipy))

def target():
    win.blit(targetImg, (targetx, targety))

run = True

while run:
    pygame.time.delay(0)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()




    if targetx >= 1 and moving == True:
        targetx-= targetVel
        if targetx <= 1:
            moving = False

    else:
        #targetx <= targetVel:
        targetx+= targetVel
        if targetx <= 500:
            moving = True

    print(targetx,targetVel)

    if keys[pygame.K_LEFT]:
        shipx-= shipVel

    if keys[pygame.K_RIGHT]:
        shipx+= shipVel

    if keys[pygame.K_UP]:
        shipy-= shipVel

    if keys[pygame.K_DOWN]:
        shipy+= shipVel

    if shipx >= 500 -shipLength:
        shipx-= shipVel

    if shipx <= 0:
        shipx+= shipVel

    if shipy >= 500 -shipWidth:
        shipy-= shipVel

    if shipy <= 0:
        shipy+= shipVel

    win.fill((68, 154, 91))
    target()
    ship()
    pygame.display.update()

pygame.quit()

0 个答案:

没有答案