Phython 小游戏编写

Phython 小游戏编写

特别是Clock机制用起来很舒服,告别界面刷新的麻烦

clock = pygame.time.Clock()

pygame.display.flip()

clock.tick(tms_sec) # tms_sec=timers in a second

春节放假在家,有时间写了一个打地鼠的小游戏,给小朋友玩玩还是足够了,呵呵

while sw_game:

    if timer>0 and timer%tms_sec==0 and clicked == False: # next round

        # redraw the playgd
        for i in range(1,10,1):
            pygame.draw.rect( playgd, color_bk,blok_list[i-1],0)

        # new rats pos
        seed_n = random.randint(0,8)
        while seed_n==seed_o:
            seed_n = random.randint(0,8)
        
        seed_x = seed_n//3+1
        seed_y = seed_n%3+1
        seed_o = seed_n
        
        # draw the rats(icon)
        rat_x = diff_w*seed_x+blok_w*(seed_x-1)
        rat_y = diff_h*seed_y+blok_h*(seed_y-1)
        playgd.blit( ico_rat, [ rat_x,rat_y] )
        #pygame.display.update()
        pygame.display.flip()
        sniffer = True
        #print("sniffer is on: "+str(timer)+", x="+str(seed_x)+",y="+str(seed_y) )
                    
    elif timer>0 and timer%tms_sec>0 and sniffer == False and clicked==True: # goto next round
         timer -= timer%tms_sec
         timer +=1
         clicked = False
         #continue

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            
        elif sniffer==True and clicked==False and event.type == pygame.MOUSEBUTTONDOWN:

            #print( "x="+str(event.pos[0])+":"+str(rat_x)+";y="+str(event.pos[1])+":"+str(rat_y) )
            if (event.pos[0]-rat_x)>0 and (event.pos[0]-rat_x)<blok_w and (event.pos[1]-rat_y)>0 and (event.pos[1]-rat_y)<blok_h :
                result +=1
                clicked = True
                sniffer = False # no more detect mouse click
                # redraw the rats(icon)
                pygame.draw.rect( playgd, color_bk,[rat_x,rat_y,blok_w,blok_h],0 )
                playgd.blit( ico_low, [ rat_x,rat_y+60] )
                #print("sniffer is off")
                if result <20 :
                    playgd.blit( ico_rst, [ 50+25*(result-1),550] )
                # show the counter
                #msg_surf = msg_font.render( "You got "+str(result)+" rat(s)!", 1, (255,0,0) )
                #pygame.draw.rect( playgd, color_bg, [100,550,500,50] )
                #playgd.blit( msg_surf, [100,550] )
                pygame.display.flip()

    pygame.draw.rect( playgd, color_bg, [100,500,500,50] )

    if timer>0 :
        msg_rst = msg_font.render( "="*(timer//tms_sec), 1, (0,200,0) )
        playgd.blit( msg_rst, [100,500] )
        timer -= 1
    else:
        msg_rst = msg_font.render( "Game Over!"+" You got "+str(result)+" rat(s)!", 1, (255,0,0) )
        playgd.blit( msg_rst, [100,500] )

    pygame.display.flip()    
    clock.tick(tms_sec) # timers in a second