Я пытаюсь сделать эту игру, и в настоящее время у меня есть изображение с прямоугольником позади него, который действует как его хитбокс, и набор изображений, с которыми игрок может столкнуться (этаж). Однако при запуске кода обнаружение столкновений с помощью «colliderect» проверяет только нижнюю часть прямоугольника, когда я хочу, чтобы символ приземлился поверх изображения. Есть ли способ изменить это?
import tkinter as tk
from tkinter import *
import pygame as pg
import os
from PIL import ImageTk,Image
#____________________________________________________________________________________________________________________________#
class HoverButton(tk.Button):
def __init__(self, master, **kw):
tk.Button.__init__(self,master=master,**kw)
self.defaultBackground = self["background"]
self.bind("<Enter>", self.on_enter)
self.bind("<Leave>", self.on_leave)
def on_enter(self, e):
self['background'] = self['activebackground']
def on_leave(self, e):
self['background'] = self.defaultBackground
#____________________________________________________________________________________________________________________________#
class Player():
global PLAYER_IMG_RIGHT
global PLAYER_IMG_LEFT
PLAYER_IMG_RIGHT = pg.image.load("mainchar_right.png")
PLAYER_IMG_LEFT = pg.image.load("mainchar_left.png")
def __init__(self, playerX, playerY, width, height, vel, screen):
super().__init__()
self.playerX = playerX
self.playerY = playerY
self.width = width
self.height = height
self.screen = screen
self.vel = vel
self.right = False
self.left = False
self.hitbox = pg.Rect(self.playerX, self.playerY, 32, 32)
def draw(self, screen):
if self.right == True:
self.image = pg.draw.rect(screen, (255,255,255), (self.playerX, self.playerY, 32, 32))
screen.blit(PLAYER_IMG_RIGHT, (self.playerX + vel, self.playerY))
print("right")
if self.left == True:
self.image = pg.draw.rect(screen, (255,255,255), (self.playerX, self.playerY, 32, 32))
screen.blit(PLAYER_IMG_LEFT, (self.playerX, self.playerY))
print("left")
self.image = pg.draw.rect(screen, (255,255,255), (self.playerX, self.playerY, 32, 32))
screen.blit(PLAYER_IMG_RIGHT, (self.playerX, self.playerY))
self.hitbox = pg.Rect(self.playerX, self.playerY, 32, 32)
pg.draw.rect(screen, (255,0,0), self.hitbox,2)
#____________________________________________________________________________________________________________________________#
class Enemy():
def __init__(self, enemyX, enemyY, width, height, screen):
self.enemyX = enemyX
self.enemyY = enemyY
self.width = width
self.height = height
self.screen = screen
self.image = pg.image.load("enemy_right.png").convert_alpha()
def look(self):
if self.enemyX > player_coor:
self.image = pg.image.load("enemy_left.png")
else:
self.image = pg.image.load("enemy_right.png")
#____________________________________________________________________________________________________________________________#
def game(MapDesign):
global player_coor
global screen
global SCREEN_WIDTH
global SCREEN_HEIGHT
SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 896
pg.init()
screen = pg.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
clock = pg.time.Clock()
pg.mixer.music.load('maingame.mp3')
pg.mixer.music.play(-1)
BOUNDARY_IMG = pg.image.load("boundary.png")
FLOOR_IMG = pg.image.load("floor.png")
crashed = False
player = Player(0, 779, 32, 32, 10, screen)
isjump = False
jumpcount = 9
while not crashed:
for event in pg.event.get():
if event.type == pg.QUIT:
crashed = True
elif event.type == pg.KEYDOWN:
if event.key == pg.K_x:
crashed = True
bg = pg.image.load("bg.png").convert_alpha()
screen.blit(bg, [0,0])
q=w=0
level = []
with open(MapDesign, "r") as f:
lines = f.readlines()
for i in lines:
level.append(i)
for row in lines:
for col in row:
if col == "f":
Block = pg.draw.rect(screen, [240,100,6],(q, w, 16, 16))
# screen.blit(BOUNDARY_IMG, (q, w, q+16, w+32))
if player.hitbox.colliderect(Block):
if player.right == True:
player.playerX -= player.vel
if player.left == True:
player.playerX += player.vel
if isjump == True:
player.playerY += player.vel
if col == 'x':
Block = pg.draw.rect(screen, [123,10,230], (q, w, 16, 16))
screen.blit(FLOOR_IMG, (q, w, q+16, w+32))
if player.hitbox.colliderect(Block):
if player.right == True:
player.playerX -= player.vel
if player.left == True:
player.playerX += player.vel
if isjump == True:
player.playerY += player.vel
q +=16
w +=32
q=0
pressed = pg.key.get_pressed()
if pressed[pg.K_LEFT] and player.playerX > player.vel:
player.left == True
player.playerX -= player.vel
player.hitbox.move_ip(player.vel, 0)
if pressed[pg.K_RIGHT] and player.playerX < 1008 - player.vel - player.width:
player.right == True
player.playerX += player.vel
player.hitbox.move_ip(player.vel, 0)
if not(isjump):
if pressed[pg.K_SPACE]:
isjump = True
else:
if jumpcount >= -10:
player.playerY -= (jumpcount * abs(jumpcount)) * 0.5
jumpcount -= 1
else:
jumpcount = 10
isjump = False
player.draw(screen)
player_coor = player.playerX
x = eval('[Enemy(100,100,32, 32, screen), Enemy(200, 200, 32, 32, screen)]')
for enemy in x:
screen.blit(enemy.image, (int(enemy.enemyX), int(enemy.enemyY)))
enemy.look()
pg.display.flip()
clock.tick(60)
pg.quit()
quit()
#____________________________________________________________________________________________________________________________#
def level1():
global MapDesign
User = "Fraser"
LevelsCompleted = "1"
lof = os.listdir()
if User in lof:
file = open(User, "r")
verify = file.readlines()
print(verify)
if verify[2] >= LevelsCompleted:
MapDesign = "map1.txt"
game(MapDesign)
#____________________________________________________________________________________________________________________________#
def level2():
MapDesign = "map2.txt"
game(MapDesign)
#____________________________________________________________________________________________________________________________#
def level3():
MapDesign = "map3.txt"
game(MapDesign)
#____________________________________________________________________________________________________________________________#
def level4():
MapDesign = "map4.txt"
game(MapDesign)
#____________________________________________________________________________________________________________________________#
def info():
global info_screen
done = False
while not done:
info_screen = Toplevel(level_screen)
info_screen.minsize(width = 1056, height = 896)
info_screen.maxsize(width = 1056, height = 896)
info_screen.title("How to play the game")
info_screen.bind("<Escape>", Exit)
print("hello")
img = ImageTk.PhotoImage(Image.open("MovingRight.png"))
panel = tk.Label(info_screen, image = img)
panel.place(x=0, y=0)
img1 = ImageTk.PhotoImage(Image.open("MovingLeft.png"))
panel1 = tk.Label(info_screen, image = img1)
panel1.place(x=0, y=224)
img2 = ImageTk.PhotoImage(Image.open("MovingJump.png"))
panel2 = tk.Label(info_screen, image = img2)
panel2.place(x=0, y=448)
img3 = ImageTk.PhotoImage(Image.open("Controls.png"))
panel3 = tk.Label(info_screen, image = img3)
panel3.place(x=0, y=812)
info_screen.mainloop()
#____________________________________________________________________________________________________________________________#
def Exit(e):
info_screen.destroy()
#____________________________________________________________________________________________________________________________#
def SelectionScreen():
global level_screen
level_screen = Tk()
level_screen.minsize(width = 1056, height = 896)
level_screen.maxsize(width = 1056, height = 896)
path1 = "bg.png"
img1 = ImageTk.PhotoImage(Image.open(path1))
panel1 = tk.Label(level_screen, image = img1)
panel1.place(x=0, y=0, relwidth = 1, relheight = 1)
Button(level_screen, text = "Level 1", bg = "white", activebackground = "light green", width = 30, height = 3, font = "fixedsys", command = level1).place(x=185, y=200)
Button(level_screen, text = "Level 2", bg = "white", activebackground = "light green", width = 30, height = 3, font = "fixedsys", command = level2).place(x=185, y=350)
Button(level_screen, text = "Level 3", bg = "white", activebackground = "light green", width = 30, height = 3, font = "fixedsys", command = level3).place(x=600, y=200)
Button(level_screen, text = "Level 4", bg = "white", activebackground = "light green", width = 30, height = 3, font = "fixedsys", command = level4).place(x=600, y=350)
Button(level_screen, text = "Info", bg = "white", activebackground = "light grey", width = 30, height = 3, font = "fixedsys", command = info).place(x=185, y=680)
Button(level_screen, text = "Exit", bg = "white", activebackground = "light grey", width = 30, height = 3, font = "fixedsys", command = Exit).place(x=600, y=680)
panel1.image = img1
level_screen.mainloop
SelectionScreen()