这似乎是一个非常容易回答的问题,但我只是一个需要快速帮助的初学者。
我正在尝试创建一个程序,当你点击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
答案 0 :(得分: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。
答案 1 :(得分:0)
我将Esthete的代码编辑为一个独立的工作示例:
根据您的操作,获取/设置单个像素可能会很慢。 (如果需要,可以使用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()