我无法在Pygame中获取对象来更改代码的方向。
import pygame
pygame.init()
width = 900
height = 700
background_image = pygame.image.load("board.png")
background_image = pygame.transform.scale(background_image, (900, 700))
virus_pic = pygame.image.load("virus.png")
trojanvirus_pic = pygame.image.load("trojan_virus.png")
armouredvirus_pic = pygame.image.load("armoured_virus.png")
antivirus_pic = pygame.image.load("antivirus.png")
trojanantivirus_pic = pygame.image.load("trojan_antivirus.png")
armouredantivirus_pic = pygame.image.load("armoured_antivirus.png")
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Anti Virus")
#def anitvirus():
def virus(x_virus,y_virus):
screen.blit(virus_pic, (x_virus, y_virus))
def intro():
background_image = pygame.image.load("intro_background.png")
background_image = pygame.transform.scale(background_image, (900, 700))
logo_image = pygame.image.load("logo.png")
logo_image = pygame.transform.scale(logo_image, (600, 200))
pygame.display.update()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
main()
screen.blit(background_image, (0, 0))
screen.blit(logo_image, (width/2-300,100))
pygame.display.update()
def main():
x_virus = 0
y_virus = 70
pygame.display.update()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
screen.blit(background_image, (0, 0))
if x_virus != 320:
x_virus += 1
virus(x_virus,y_virus)
if x_virus == 320:
if y_virus != 400:
y_virus += 1
virus(x_virus,y_virus)
if y_virus == 400:
if x_virus != 500:
x_virus += .5
virus(x_virus,y_virus)
if x_virus == 500:
if y_virus != 10:
y_virus -= 1
virus(x_virus,y_virus)
这是执行游戏动作的代码^
pygame.display.update()
intro()
我不知道所有的if语句是否是最有效的方法。我尝试了不同的方法,但是if语句在大多数情况下似乎起作用。我将不胜感激任何帮助。谢谢。
答案 0 :(得分:1)
您没有正确使图像发白。让我们看一下这个函数:
def virus(x_virus,y_virus):
screen.blit(virus_pic, (x_virus, y_virus))
您输入x和y坐标,并尝试将virus_pic
变成screen
。问题是您在这里没有考虑不同的范围,您需要传递screen
和virus_pic
作为参数,否则您的函数不知道它们是什么,因此将函数更改为如下所示这个
def virus(screen,virus_pic,x_virus,y_virus):
screen.blit(virus_pic, (x_virus, y_virus))
,然后在main()
函数中更改代码的相应部分。我也很乐意简化它
if x_virus != 320:
x_virus += 1
if x_virus == 320:
if y_virus != 400:
y_virus += 1
if y_virus == 400:
if x_virus != 500:
x_virus += .5
if x_virus == 500:
if y_virus != 10:
y_virus -= 1
virus(screen,virus_pic,x_virus,y_virus)
让我知道这是怎么回事!
编辑:
之所以不改变方向是因为在每一帧中,坐标每次都仅以相同的精确值进行更改,因此,速度矢量保持不变,并且您只能看到一个方向的运动。
您需要找到一种使这些更改动态化的方法。