1. 鼠标点击检测原理
2. 封装checkPoint()函数
def checkPoint ( obj, pos) :
top = obj[ 'y' ]
bottom = obj[ 'y' ] + obj[ 'height' ]
left = obj[ 'x' ]
right = obj[ 'x' ] + obj[ 'width' ]
x, y = pos
if left <= x <= right and top <= y <= bottom:
return True
3. 改造beatMouse()函数
def beatMouse ( type , arg) :
. . . . . .
elif type == 'mouse' :
if checkPoint( mouse, arg) :
state = True
def eventListen ( ) :
. . . . . .
if event. type == pygame. MOUSEBUTTONDOWN:
pos = pygame. mouse. get_pos( )
beatMouse( 'mouse' , pos)
完整代码
import pygame
import random
pygame. init( )
pygame. display. set_caption( '打地鼠' )
iconImg = pygame. image. load( './images/a.png' )
pygame. display. set_icon( iconImg)
screen = pygame. display. set_mode( ( 500 , 500 ) )
bgImg = pygame. image. load( './images/背景.png' )
ADDMOUSE = 101
pygame. time. set_timer( ADDMOUSE, 2000 )
mouseImgList = [ chr ( i) + '.png' for i in range ( 97 , 123 ) ]
beatMouseImg = pygame. image. load( './images/被打晕的地鼠.png' )
rightMusic = pygame. mixer. Sound( './music/正确.wav' )
errorMusic = pygame. mixer. Sound( './music/错误.wav' )
posList = [ [ 100 , 200 ] , [ 240 , 200 ] , [ 380 , 200 ] ,
[ 100 , 350 ] , [ 240 , 350 ] , [ 380 , 350 ] ]
def createMouse ( ) :
mouseImg = random. choice( mouseImgList)
mouseObj = pygame. image. load( './images/' + mouseImg)
mouseRect = mouseObj. get_rect( )
mouse = {
'letter' : mouseImg[ 0 ] ,
'img' : mouseObj,
'x' : 0 ,
'y' : 0 ,
'width' : mouseRect. width,
'height' : mouseRect. height,
'state' : False
}
x, y = random. choice( posList)
mouse[ 'x' ] = x - mouse[ 'width' ] // 2
mouse[ 'y' ] = y - mouse[ 'height' ] // 2
return mouse
clock = pygame. time. Clock( )
mouse = createMouse( )
def draw ( ) :
screen. blit( bgImg, ( 0 , 0 ) )
screen. blit( mouse[ 'img' ] , ( mouse[ 'x' ] , mouse[ 'y' ] ) )
def eventListen ( ) :
global mouse
for event in pygame. event. get( ) :
if event. type == pygame. QUIT:
pygame. quit( )
exit( )
if event. type == ADDMOUSE:
mouse = createMouse( )
if event. type == pygame. MOUSEBUTTONDOWN:
pos = pygame. mouse. get_pos( )
beatMouse( 'mouse' , pos)
if event. type == pygame. KEYDOWN:
beatMouse( 'key' , event. key)
def beatMouse ( type , arg) :
state = False
if type == 'key' :
if arg == ord ( mouse[ 'letter' ] ) :
state = True
elif type == 'mouse' :
if checkPoint( mouse, arg) :
state = True
if state:
mouse[ 'img' ] = beatMouseImg
mouse[ 'state' ] = True
rightMusic. play( )
else :
errorMusic. play( )
def checkPoint ( obj, pos) :
left = obj[ 'x' ]
right = obj[ 'x' ] + obj[ 'width' ]
top = obj[ 'y' ]
bottom = obj[ 'y' ] + obj[ 'height' ]
x, y = pos
if left <= x <= right and top <= y <= bottom:
return True
while True :
clock. tick( 60 )
draw( )
eventListen( )
pygame. display. update( )