我在这个项目中工作,但我在碰撞检测中被困了几天我希望我的角色跳跃并留在块上没有找到任何可以解决我在互联网上问题的东西。这是我的代码,它有点笨拙,因为我是 python 的新手,我有 1-2 周的时间。我从代码中删除了一些东西,因为它太长了,但如果有人好心并想帮助我,我可以提供完整的代码。感谢您的任何改进或评论
import pygame
import time
import os
pygame.init()
WIDTH,HEIGHT=1280,720
screen=pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Jump man")
fps=60
run=True
clock=pygame.time.Clock()
bg=pygame.image.load('background/bg.png')
runRight=[frame0r,frame1r,frame2r,frame3r,frame4r,frame5r,frame6r,frame7r]
runLeft=[frame0l,frame1l,frame2l,frame3l,frame4l,frame5l,frame6l,frame7l]
jumpRight=[jumpRight]
jumpLeft=[jumpLeft]
fallAnimation=[fall]
x,y=400,400
dx,dy=0,0
jump=False
touchedGround=False
count=0
i=0
LIST=runRight
tileSize=50
def drawGrid():
for line in range(0,15):
pygame.draw.line(screen, (255, 255, 255), (0, line * tileSize), (WIDTH, line * tileSize))
for line in range(0,26):
pygame.draw.line(screen, (255, 255, 255), (line * tileSize, 0), (line * tileSize, HEIGHT))
class World():
def __init__(self, data):
self.tile_list = []
#load images
dirt_img = pygame.image.load('background/dirt.png')
grass_img = pygame.image.load('background/grass.png')
row_count = 0
for row in data:
col_count = 0
for tile in row:
if tile == 1:
img = pygame.transform.scale(dirt_img, (tileSize, tileSize))
img_rect = img.get_rect()
img_rect.x = col_count * tileSize
img_rect.y = row_count * tileSize
tile = (img, img_rect)
self.tile_list.append(tile)
if tile == 2:
img = pygame.transform.scale(grass_img, (tileSize, tileSize))
img_rect = img.get_rect()
img_rect.x = col_count * tileSize
img_rect.y = row_count * tileSize
tile = (img, img_rect)
self.tile_list.append(tile)
col_count += 1
row_count += 1
def draw(self):
for tile in self.tile_list:
screen.blit(tile[0], tile[1])
def runAnimation(i,list,count):
if(count%5==0):
i+=1
i%=len(list)
return i,list
world=World(worldData)
while run:
clock.tick(fps)
count+=1
# Key inputs
key=pygame.key.get_pressed()
if key[pygame.K_RIGHT] and x<1220:
x+=3
if jump==False:
i,LIST=runAnimation(i,runRight,count)
if key[pygame.K_LEFT] and x>0:
x-=3
if jump==False:
i,LIST=runAnimation(i,runLeft,count)
if key[pygame.K_UP] and touchedGround:
jump=True
if jump and (dy>=-10) and key[pygame.K_RIGHT]:
dy-=1
jump=False
i,LIST=runAnimation(i,jumpRight,count)
elif jump and (dy>=-10) and key[pygame.K_LEFT]:
dy-=1
jump=False
i,LIST=runAnimation(i,jumpLeft,count)
elif dy>0:
i,LIST=runAnimation(i,fallAnimation,count)
else:
touchedGround=False
if y<=HEIGHT-200:
dy+=0.5
else:
if touchedGround==False:
dy=0
touchedGround=True
y+=dy
screen.fill((25, 25, 25))
screen.blit(bg,(0,0))
world.draw()
#drawGrid()
screen.blit(LIST[i], (x, y))
# Event handler
for event in pygame.event.get():
if event.type==pygame.QUIT:
run=False
pygame.display.update()
pygame.quit()