如何在 pygame 中使用鼠标按钮?

How to use mousebuttons in pygame?

嗨,我是 pygame 的新手,我正在创建我创建的棋盘游戏的虚拟版本。

所以现在我正在玩 pygame,我想将我使用 w 和 d 移动棋子的代码更改为我将使用鼠标点击移动我的棋子的代码

代码如下:

if event.type==pygame.KEYDOWN and event.key==pygame.K_w:
    y-=z
if event.type==pygame.KEYDOWN and event.key==pygame.K_d:
    x+=2*z
    y-=2*z
if event.type==pygame.KEYDOWN and event.key==pygame.K_a:
    x-=2*z
    y-=2*z

http://www.pygame.org/docs/ is the main documentation for Pygame
http://www.pygame.org/docs/ref/mouse.html is the mouse documentation
http://www.pygame.org/docs/ref/event.html is the event documentation

我推荐 Carter 和 Warren Sande 合着的书 "Hello World!" 来学习 Python 和 Pygame 的基础知识。

下面是 pygame 鼠标和按键的一些示例代码:

import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640,480])
clock = pygame.time.Clock()

while 1:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            print "A key was pressed!"
        if event.type == pygame.MOUSEBUTTONDOWN:
            print "A button was clicked!"

这是我想出的代码:

import pygame,sys
import math
from pygame.locals import*
pygame.init()

black=(0,0,0)
white=(255,255,255)
w=500
h=500
p=0
root=pygame.display.set_mode((w+50,h),0,32)
pygame.display.set_caption('Clash of Hunters')
clock = pygame.time.Clock()


def mainloop():
    global p
    running=False
    marksman=pygame.image.load('resized.png').convert_alpha()
    background=pygame.image.load('board.png').convert()
    dael=pygame.image.load('dael.png').convert_alpha()
    x=14;y=457;z=55;k=10;x1=240;y1=17
    root.blit(marksman,(x,y))
    root.blit(dael,(x1,y1))
    while not running:
        clock.tick(60)
        for event in pygame.event.get():
            mouse=pygame.mouse.get_pos()
            d=math.sqrt(math.pow(mouse[0]-x,2)+ math.pow(mouse[1]-y,2))
            if event.type== pygame.QUIT or event.type==pygame.KEYDOWN and event.key==pygame.K_ESCAPE:
                pygame.quit()
                quit()

            #moving in action

            #elif event.type==pygame.KEYDOWN and event.key==pygame.K_e:
                #x+=2*z
                #y-=2*z
            #elif event.type==pygame.KEYDOWN and event.key==pygame.K_q:
                #x-=2*z
                #y-=2*z
            #elif event.type==pygame.KEYDOWN and event.key==pygame.K_d:
                #x+=2*z
           # elif event.type==pygame.KEYDOWN and event.key==pygame.K_a:
                #x-=2*z
            elif x>w:
                x-=2*z
            elif x<0:
                x+=2*z
            elif  y<=30:
                root.blit(marksman,(514,466))
            else:
                if pygame.mouse.get_pressed()[0]==1:
                    if d<30:
                        x=mouse[0]
                        y=mouse[1]
                root.blit(background,(0,0))
                root.blit(marksman,(x,y))
                root.blit(dael,(x1,y1))


        pygame.display.update()
mainloop()