1

这似乎是一个很容易回答的问题,但我只是一个需要快速帮助的初学者。

我正在尝试创建一个程序,当您单击 pyGame 窗口上的某个位置时,它会打印出您用鼠标左键点击它,并打印出按下位置的坐标。我已经有了这个。我在让它在 pyGame 窗口上绘制像素时遇到问题。基本上,我希望它在我按下 pyGame 窗口的位置绘制一个像素。

#!/usr/bin/env python

#import the module for use 
import pygame

#setting up some variables
running = 1
LEFT = 1 
#Set up the graphics area/screen
screen=pygame.display.set_mode((640,400))

#continuous loop to keep the graphics running
while running==1:
    event=pygame.event.poll()
    if event.type==pygame.QUIT:
        running=0
        pygame.quit()
    elif event.type==pygame.MOUSEBUTTONDOWN and event.button==LEFT:
        print "You pressed the left mouse button at (%d,%d)" %event.pos
    elif event.type==pygame.MOUSEBUTTONUP and event.button==LEFT:
        print "You released the left mouse button at (%d,%d)" %event.pos
4

2 回答 2

0

当您收到鼠标按下事件时,尝试设置每个像素的颜色。

elif event.type==pygame.MOUSEBUTTONDOWN and event.button==LEFT:
  print "You pressed the left mouse button at (%d,%d)" %event.pos
  screen.set_at((event.pos.x, event.pos.y), pygame.Color(255,0,0,255))

请注意,这将根据需要临时锁定和解锁 Surface。

于 2012-11-28T22:32:56.373 回答
0

我将 Aesthete 的代码编辑为一个独立的工作示例:

根据您的操作,获取/设置单个像素可能会很慢。(如果需要,可以使用 Surfarray 和 Pixelarray。)

import pygame
from pygame.locals import *

class Game(object):
    done = False
    def __init__(self, width=640, height=480):
        pygame.init()
        self.width, self.height = width, height
        self.screen = pygame.display.set_mode((width, height))

        # start with empty screen, since we modify it every mouseclick
        self.screen.fill(Color("gray50"))

    def main_loop(self):
        while not self.done:
            # events
            events = pygame.event.get()
            for event in events:
                if event.type == pygame.QUIT: self.done = True
                elif event.type == KEYDOWN:
                    if event.key == K_ESCAPE: self.done = True
                elif event.type == MOUSEMOTION:
                    pass
                elif event.type == MOUSEBUTTONDOWN and event.button == 1:
                    print "Click: ({})".format(event.pos)
                    self.screen.set_at(event.pos, Color("white"))

            # draw
            pygame.display.flip()


if __name__ == "__main__":
    g = Game()
    g.main_loop()
于 2012-11-29T03:30:30.237 回答