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

时间:2016-05-15 15:04:01

标签: python python-2.7 pygame

希望大家度过美好的一天 我试图检测我的物体(黑色矩形)和食物图像之间的碰撞 我想要的基本做法是每当我的长方形与食物图像碰撞时,食物图像随后被放置在屏幕上并且分数增加+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()

1 个答案:

答案 0 :(得分:0)

在drawcell()中调用:

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

应该这样做。