问题描述
是否可以将 Pygame 的鼠标点击检测更改为外部输入? 我正在尝试构建一个国际象棋代码,它从 Arduino 接收位置。因此,在下面的代码中,我试图将我的输入字符串 (b2) 转换为位置 (2,2) 并将其作为 pygame 的 x,y 信息返回到我的主文件中。
def objectdetection(screen,game_state,valid_moves,square_selected):
ser = serial.Serial('/dev/ttyUSB0',9600,timeout=1)
ser.flush()
while True:
if ser.in_waiting > 0:
Position = [ser.readline().decode('utf-8').rstrip()]
if Position == "b2":
return (2,2)
main:
elif e.type == objectdetection:
if not game_over and human_turn:
location = objectdetection() # (x,y) location of the mouse
col = location[0] // SQUARE_SIZE
row = location[1] // SQUARE_SIZE
if square_selected == (row,col) or col >= 8: # user clicked the same square twice
square_selected = () # deselect
player_select = [] # clear clicks
else:
square_selected = (row,col)
player_select.append(square_selected) # append for both 1st and 2nd click
if len(player_select) == 2: # after 2nd click
move = ChessEngine.Move(player_select[0],player_select[1],game_state.board)
for i in range(len(valid_moves)):
if move == valid_moves[i]:
game_state.makeMove(valid_moves[i])
move_made = True
animate = True
square_selected = () # reset user clicks
player_select = []
if not move_made:
player_select = [square_selected]
遗憾的是它并不那么容易。总体上是否可以将鼠标检测从 pygame 更改为外部输入? 感谢您的帮助。
解决方法
为对象选择编写函数并将代码放入函数中:
def select(row,col)
global square_selected,player_select,move,move_made,animate
if square_selected == (row,col) or col >= 8: # user clicked the same square twice
square_selected = () # deselect
player_select = [] # clear clicks
else:
square_selected = (row,col)
player_select.append(square_selected) # append for both 1st and 2nd click
if len(player_select) == 2: # after 2nd click
move = ChessEngine.Move(player_select[0],player_select[1],game_state.board)
for i in range(len(valid_moves)):
if move == valid_moves[i]:
game_state.makeMove(valid_moves[i])
move_made = True
animate = True
square_selected = () # reset user clicks
player_select = []
if not move_made:
player_select = [square_selected]
可以在鼠标点击时调用该函数:
for e in p.event.get():
if e.type == p.QUIT:
# [...]
elif e.type == p.MOUSEBUTTONDOWN:
if not game_over and human_turn:
col = e.pos[0] // SQUARE_SIZE
row = e.pos[1] // SQUARE_SIZE
select(row,col)
并且您可以在收到职位时调用该函数:
position = objectdetection(.....)
if position != None:
row = position[0]
col = position[1]
select(row,col)