如何防止用户将图像(他们可以使用箭头或 WASD 键移动图像)移出 canvas?

How do I prevent the user from moving image (they can move the image with the arrow or WASD keys) off of the canvas?

我的程序涉及用户使用箭头键或 WASD 键移动类似于 'player character' 的图像。是否有代码可以阻止用户将图像移出 canvas?

这就是我将如何使用您提供的信息解决此问题的方法:

if move.ending_x_coord < right_limit or move.ending_x_coord > left_limit or   
move.ending_y_coord < bottom_limit or move.ending_y_coord > top limit:
    move.is_valid = False