python pygame中随机生成的对象与玩家之间的碰撞



我第一次用pygame编码,没有人能帮我,因为所有可能的朋友都用javascript编码我写了那几行代码,我想在Food和player发生冲突时做点什么。这是我的代码,我想用最简单的方法:

import pygame
import os
import random
pygame.init()
win_height = 400
win_width = 800
win = pygame.display.set_mode((win_width, win_height))

class Hero:
def __init__(self, x, y):
# Walk
self.x = x
self.y = y
self.velx = 10
self.vely = 6
self.face_right = True
self.face_left = False
self.stepIndex = 0
self.hitboxPlayer = pygame.Rect(self.x, self.y, 50, 112.5)
# Jump
self.jump = False
def draw(self, win):
self.hitboxPlayer = pygame.Rect(self.x, self.y, 50, 112.5)
pygame.draw.rect(win, (0, 0, 0), self.hitboxPlayer, 1)
if self.stepIndex >= 3:
self.stepIndex = 0
if self.face_left:
win.blit(left[self.stepIndex], (self.x, self.y))
self.stepIndex += 1
if self.face_right:
win.blit(right[self.stepIndex], (self.x, self.y))
self.stepIndex += 1

def jump_motion(self, userInput):
if userInput[pygame.K_SPACE] and self.jump is False:
self.jump = True
if self.jump:
self.y -= self.vely * 4
self.vely -= 1
if self.vely < -6:
self.jump = False
self.vely = 6
def direction(self):
if self.face_right:
return 1
if self.face_left:
return -1

class Food:
def __init__(self, lx, hx):
self.y = 0
self.speed = 5
self.highestx = win_width
self.x = random.randint(0,self.highestx)
self.sprite = str(1)
self.FoodCount = []
self.hitboxFood = pygame.Rect(self.x, self.y, 50, 50)

def draw(self):
self.hitboxFood = pygame.Rect(self.x + 15, self.y + 15, 50, 50)
pygame.draw.rect(win, (0, 0, 0), self.hitboxFood, 1)
win.blit(food, (self.x,self.y))
self.sprite = win.blit(food, (self.x,self.y))
if self.y == win_height-200:
print("Ground ")
if snacks.hitboxFood.colliderect(player.hitboxPlayer) :
print("hit")

def move(self):
self.y += self.speed

def draw_game():
global tower_health, speed
win.fill((0, 0, 0))
win.blit(background, (0, 0))

player.draw(win)
for snack in snacks.FoodCount:
snack.draw()
snack.move()

pygame.time.delay(30)
pygame.display.update()

pygame.time.set_timer(pygame.USEREVENT, 1000)
snacks = Food(0, win_width)
player = Hero(250, 290)
run = True
while run:
if event.type == pygame.USEREVENT:
snacks.spawn()
userInput = pygame.key.get_pressed()
player.move_hero(userInput)
player.jump_motion(userInput)
draw_game()

我真的不知道该怎么做。。。我试了很多坦克的帮助!!!!!!!!!!!!!

您尝试过在Googlepygame detect collision上搜索吗。我做到了,这就是我的发现,我希望这对你有帮助

当你学习编码或使用新模块时,花时间在谷歌上搜索是你应该首先想到的。

最新更新