简体   繁体   English

Pygame中图像与对象之间的碰撞检测

[英]Collision detection between an image and an object in Pygame

Hope you all are having a great day. 希望大家都过得愉快。
I am trying to detect a collision between my object (the black rectangle) and the food image. 我正在尝试检测我的物体(黑色矩形)和食物图像之间的碰撞。
What i want to basically do is whenever my rectangle collides with the food image, the food image is then placed randomly on the screen and the score gets increased by +1. 我要做的基本上是,每当我的矩形与食物图像碰撞时,食物图像就会随机放置在屏幕上,并且分数会增加+1。

import pygame
import time
import random

pygame.init()

#Colours
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,155,0)

#Game Display
display_width = 800
display_height  = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('KALM Creation')

#Directions
DOWN='down'
UP='up'
LEFT='left'
RIGHT='right'

#Score
score=0

# My food image
foodimg=pygame.image.load("food.png")#.convert_alpha()
foodrect = foodimg.get_rect()
foodrect.centerx = 100
foodrect.centery = 200

#Our Icon For The Game
icon=pygame.image.load('icon1.jpg')
pygame.display.set_icon(icon)

#Clock
clock = pygame.time.Clock()
FPS = 30

cellSize=10

#Font Size
smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 50)
largefont = pygame.font.SysFont("comicsansms", 80)

#The score function - displays the score on top right
def scoredisplay(scoredef=0):
    text=smallfont.render("Score :%s" %(scoredef) ,True ,black)
    gameDisplay.blit(text,[0,0])

#Starting Of the game
def game_intro():

    intro = True
    while intro:    
      for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN:
            if event.key ==pygame.K_c:
                intro = False
            if event.key ==pygame.K_q:
                pygame.quit()
                quit()
        gameDisplay.fill(white)
        #Game Initial display message
        message_to_screen("Welcome To  Eat it Game",
                          green,
                          -200,
                          size="medium")
        message_to_screen("Press 'C' to play the game or 'Q' to quit.",
                          black,
                          150,
                          size="small")
        pygame.display.update()
        clock.tick(15)
#Text Size
def text_objects(text,color, size):
    if size=="small":
        textSurface=smallfont.render(text, True ,color)
    elif size=="medium":
        textSurface=medfont.render(text, True ,color)
    elif size=="large":
        textSurface=largefont.render(text, True ,color)


    return textSurface,textSurface.get_rect()

#Message to screen
def message_to_screen(msg,color,y_displace=0,size="small"):
    textSurf,textRect=text_objects(msg,color,size)
    textRect.center = (display_width / 2),(display_height / 2)+y_displace
    gameDisplay.blit(textSurf,textRect)

#Drawing Cells
def drawCell(coords,ccolor):
    for coord in coords:
        x=coord['x']*cellSize
        y=coord['y']*cellSize
        makeCell=pygame.Rect(x,y,cellSize,cellSize)
        pygame.draw.rect(gameDisplay,ccolor,makeCell)

#The Game run up
def runGame():
    score=0
    gameExit = False
    gameOver = False
    #Starting Position of the object
    startx=3
    starty=3
    coords=[{'x':startx,'y':starty}]
    direction = RIGHT
    while not gameExit:
        while gameOver == True:
            #Game Over message

            gameDisplay.fill(white)
            message_to_screen("Game over",
                              red,
                              y_displace=-50,
                              size="large")
            message_to_screen("Press C to play again or Q to quit",
                              black,
                              y_displace=50,
                              size="medium")

            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        gameExit = True
                        gameOver = False
                    if event.key == pygame.K_c:
                        gameLoop()

        #Game Controls
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameExit = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    direction = LEFT
                elif event.key == pygame.K_RIGHT:
                    direction = RIGHT
                elif event.key == pygame.K_UP:
                    direction = UP 
                elif event.key == pygame.K_DOWN:
                    direction = DOWN

        if direction == UP:
            newCell={'x':coords[0]['x'],'y':coords[0]['y']-1}
        elif direction == DOWN:
            newCell={'x':coords[0]['x'],'y':coords[0]['y']+1}
        elif direction == LEFT:
            newCell={'x':coords[0]['x']-1,'y':coords[0]['y']}
        elif direction == RIGHT:
            newCell={'x':coords[0]['x']+1,'y':coords[0]['y']}

        del coords[-1]  
        coords.insert(0, newCell)
        gameDisplay.fill(white)
        drawCell(coords,black)
        clock.tick(FPS)

        #If object moves outside the screen , game gets over.
        if(newCell['x']<0 or newCell['y']<0 or newCell['x']>display_width/cellSize or newCell['y']>display_height):
           gameOver= True

        #Displays Score
        scoredisplay(score)

        gameDisplay.blit(foodimg,foodrect)
        #pygame.display.flip()
        pygame.display.update()




#The game run up
def gameLoop():
    clock.tick(FPS)
    runGame()
    pygame.quit()
    quit()
game_intro()
gameLoop()

In the drawcell() call: 在drawcell()调用中:

if makecell.colliderect(foodrect):
    foodrect.x = random.randint(0, sceeenwidth)
    foodrect.y = random.randint(0, screenheight)

Should do it. 应该做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM