我想看看我拥有的汽车是否没有与矩形相撞。我的车在路上,我不想让它熄火。所以我想让计算机检测汽车是否在路上,有点像 colliderect() 函数,但恰恰相反。这是我的代码:我的错误愚蠢的 QUESTIN !!!!!!!!!
import pygame
from pygame.locals import *
pygame.init()
#define variables
width, height = 940, 780
screen = pygame.display.set_mode((width, height))
grey = 87, 87, 87
white = 255, 255, 255
player = pygame.image.load("Pics\goodcar.jpeg")
keys = [False, False, False, False, False]
playerpos = [0,40]
green = 0,255,0
red = 255,0,0
color = red
x1 = 0
x2 = 40
y1 = 940
y2 = 100
#main program
while 1:
screen.fill(0)
road = pygame.draw.rect(screen, grey, (x1,x2,y1,y2), 0)
traffic_light = pygame.draw.circle(screen, color, (640,90), 40, 0)
screen.blit(player, playerpos)
car_rect = player.get_rect(left=playerpos[0], top=playerpos[1])
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
exit(0)
if event.type == pygame.KEYDOWN:
if event.key==K_RIGHT:
keys[0]=True
if event.key==K_LEFT:
keys[1]=True
if event.key==K_DOWN:
keys[2]=True
if event.key==K_UP:
keys[3]=True
if event.key==K_SPACE:
keys[4]=True
if event.type == pygame.KEYUP:
if event.key==pygame.K_RIGHT:
keys[0]=False
if event.key==pygame.K_LEFT:
keys[1]=False
if event.key==pygame.K_DOWN:
keys[2]=False
if event.key==pygame.K_UP:
keys[3]=False
if event.key==pygame.K_SPACE:
keys[4]=False
if traffic_light.colliderect(car_rect):
if color == red:
keys[0]=False
if car_rect == 100:
keys[2]=False
if keys[0]==True:
playerpos[0]+=2
if keys[1]==True:
playerpos[0]-=2
if keys[2]==True:
playerpos[1]+=2
if keys[3]==True:
playerpos[1]-=2
if keys[4]==True:
if color==red:
color = green
else:
color = red
pygame.display.update()
感谢之前的帮助!