我在Python
中制作了一个游戏,目前看起来是这样的:
import pygame, sys, time, random, threading
from threading import Timer
from pygame.locals import *
pygame.init()
WINDOWHEIGHT = 720
WINDOWWIDTH = 1280
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Hitman Grandma')
plorp = 'true'
white = (255,255,255)
red = (255,0,0)
black = (0,0,0)
green = (0,255,0)
blue = (0,0,255)
cyan = (0,255,255)
windowSurface.fill(white)
pygame.display.update()
mainClock = pygame.time.Clock()
hgleft = False
hgright = False
hgup = False
speed = 4
hgair = True
hgjumpallowed = False
level = 0
def stop() :
hgbox.move_ip(0,0)
return
hgbox = pygame.Rect(0 ,13 ,36 ,72)
hitmangrandma = pygame.image.load('hgrd1copy.jpg')
hg = pygame.transform.scale(hitmangrandma, (36,72))
landbox1 = pygame.Rect(0,400,200,50)
li = pygame.image.load('hgland1.png')
land1 = pygame.transform.scale(li,(200,50))
landbox2 = pygame.Rect(230,400,200,50)
land2 = pygame.transform.scale(li,(200,50))
land = landbox1,landbox2
while True:
windowSurface.fill(white)
windowSurface.blit(land1,landbox1)
windowSurface.blit(land2,landbox2)
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_LEFT or event.key == K_a:
hgright = False
hgleft = True
if event.key == K_RIGHT or event.key == K_d:
hgleft = False
hgright = True
if event.key == K_UP or event.key == K_w:
hgair = True
hgup = True
hgupkey = True
if event.type == KEYUP:
if event.key == K_ESCAPE or K_q and pygame.key.get_mods() & pygame.KMOD_CTRL:
pygame.quit()
sys.exit()
exit
if event.key == K_LEFT or K_a:
hgleft = False
if event.key == K_RIGHT or K_d:
hgright = False
if hgup and hgbox.top > 0 and hgupkey == True and hgair == True and hgjumpallowed == True:
hgbox.top -= 100
hgair = True
if hgleft and hgbox.left > 0:
hgbox.left -= speed
if hgright and hgbox.right < WINDOWWIDTH:
hgbox.right += speed
if not hgbox.colliderect(landbox1) or not hgbox.colliderect(landbox2) and hgair == True:
hgair = False
hgbox.top += speed
hgjumpallowed = False
if hgbox.colliderect(landbox1) or hgbox.colliderect(landbox2):
hgjumpallowed = True
stop()
windowSurface.blit(hg, hgbox)
pygame.display.update()
mainClock.tick(40)
但是,当我运行我的脚本时,hgbox
没有检测到与landbox2
的冲突,只是不断下降。我认为这个问题是因为它只运行if语句的第一部分,而没有检查其他部分。我该怎么做才能让它检测到if语句的其他部分?在
要确保Python按照正确的顺序计算逻辑运算符,请添加()。在
if (not hgbox.colliderect(landbox1) or not hgbox.colliderect(landbox2)) and hgair == True:
当与
landbox1
或与landbox2
没有冲突时,以及当hgair == True
时,此值为True。在对于mcve,我的意思是这样的(一个我们可以复制、粘贴和运行的最小但完整的示例):
问题是由这条线引起的:
^{pr2}$它被评估为
^{3}$在上面的例子中,第二部分总是
False
。除非条件的第一部分也是False,否则hgbox
总是失败的,这意味着它只能站在左边的平台上。在尝试将其更改为:
编辑:这里有一个完整的示例,向您展示如何编写移动和跳转代码。使用
x_speed
和y_speed
每一帧移动播放器(同时加速y_speed
),并在事件循环中将速度设置为所需的值。如果玩家接触平台,将其设置为平台矩形的.top
,并将hgjumpallowed
设置为True
。在事件循环中还有一个错误:}是一个真实的值。在
event.key == K_RIGHT or K_d
总是True
,因为它的计算结果是(event.key == K_RIGHT) or (K_d)
,而{相关问题 更多 >
编程相关推荐