pygame.Rect.collidepoint() — 检测一个点是否包含在该 Rect 对象内
pygame.Rect.colliderect() — 检测两个 Rect 对象是否重叠
pygame.Rect.collidelist() — 检测该 Rect 对象是否与列表中的任何一个矩形有交集
pygame.Rect.collidelistall() — 检测该 Rect 对象与列表中的每个矩形是否有交集
pygame.Rect.collidedict() — 检测该 Rect 对象是否与字典中的任何一个矩形有交集
pygame.Rect.collidedictall() — 检测该 Rect 对象与字典中的每个矩形是否有交集
参考
原文链接:https://blog.csdn.net/apythonlearner/article/details/130726661
import pygame
from pygame.locals import *
import sys
import math
pygame.init()
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
c=pygame.time.Clock()
q = [
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1]
]
px=70
py=70
du=0
left=False
right=False
down=False
up=False
img = pygame.image.load("1.png") # 替换为您自己的图像文件路径
img=pygame.transform.scale(img,(30,30))
ci=0
sz=[]
qsz=[]
class zidan:
def __init__(self):
self.x = self
self.y = self
def chuangjian(self):
p=pygame.draw.rect(screen, (40, 140, 40), (self.x, self.y, 10,20), 0)
print(self.x,self.y)
if(p.collidelistall(qsz)):
print("cc")
def player(x,y,zhuan):
#pygame.draw.line(screen, (40, 140, 40), (x, y), (74, 713))
#print(du)
screen.blit(zhuan,(x,y))
def dl(x,y):
pygame.draw.line(screen, (40, 140, 40), (x, y), (x, 700))
while True:
screen.fill((255, 255, 255))
c.tick(7)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
up = True
print("up")
py=py -10
if event.type == pygame.KEYUP:#上
up = False
if keys[pygame.K_LEFT]:#zuo
left = True
du=du+1
img=pygame.transform.rotate(img,du)
rec=img.get_rect(center=(width/2,height/2))
#print(du)
screen.blit(img,rec)
if event.type == pygame.KEYUP:
left = False
if keys[pygame.K_DOWN]:#xia
down = True
print("up")
py = py + 10
if event.type == pygame.KEYUP:
down = False
if keys[pygame.K_RIGHT]:#you
right = True
zi=zidan()
zi.x=px
zi.y=py
sz.append(zi)
#print(sz)
#在这直接写会变成子弹,写成函数qiang(ci)就能画成一次,不会移动的墙
if event.type == pygame.KEYUP:
right = False
for h in range(len(q)):
#print(q[h],"行",h)
for g in range(len(q[h])):
if q[h][g]==1:
#print(q[h][g],"个",g,h)
pz=pygame.draw.rect(screen, (140, 240, 40), (h*60, g*60, 60, 60))
qsz.append(pz)
player(px,py,img)
dl(px,py)
for i in (sz):
#print(i)
i.x=i.x+10
i.chuangjian()
if(i.x>500):
sz.remove(i)
#在这直接写会变成子弹,写成函数qiang(ci)就能画成一次,不会移动的墙
pygame.display.flip()