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

时间:2016-11-21 14:59:43

标签: python python-2.7 python-3.x pygame pygame-surface

我对pygame很新,我正在创建我创建的棋盘游戏的虚拟版本。

所以现在我在pygame中玩arond并且我想改变我的代码,我使用w和d将代码移动到代码,我将使用鼠标cliclicks移动我的作品

这是代码:

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

2 个答案:

答案 0 :(得分:0)

  

https://parseplatform.github.io/docs/ios/guide/#relations是Pygame的主要文档   http://www.pygame.org/docs/是鼠标文档
  http://www.pygame.org/docs/ref/mouse.html是事件文档

我建议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!"

答案 1 :(得分:0)

这是我提出的代码:

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()