2015-09-06 94 views
1

如何阻止玩家角色离开屏幕边缘并停止在边界?停止sprite走出tkinter窗口

这里是我的代码:

from tkinter import * 
HEIGHT = 800 
WIDTH = 500 
window = Tk() 
window.title('Colour Shooter') 
c = Canvas(window, width=WIDTH, height=HEIGHT, bg='black') 
c.pack() 

ship_id = c.create_rectangle(0, 0, 50, 50, fill='white') 
MID_X = (WIDTH/2)-25 
c.move(ship_id, MID_X, HEIGHT-50) 
left_bound= c.create_line(0, 0, 800, 0,) 
right_bound= c.create_line(500, 0, 500, 500,) 

SHIP_SPD = 10 
def move_ship(event): 
    if event.keysym == 'Left': 
     c.move(ship_id, -SHIP_SPD, 0) 
    elif event.keysym == 'Right': 
     c.move(ship_id, SHIP_SPD, 0) 
c.bind_all('<Key>', move_ship) 


from math import sqrt 
def collision_bound(): 
    dist_left = left_bound.x + ship_id.x 
    if dist_left < 0: 
     c.move(ship_id, 50, HEIGHT-50) 
    dist_right = right_bound.x - ship_id.x 
    if dist_right > WIDTH: 
     c.move(ship_id, WIDTH - 50, HEIGHT-50) 

我很新的蟒蛇和书我没能教我如何解决这个问题。所以任何帮助将不胜感激

回答

1

你可以使用c.coords(ship_id)来获得船的位置,然后你可以检查他们是否被允许移动。

尝试更换

if event.keysym == 'Left': 
    c.move(ship_id, -SHIP_SPD, 0) 
elif event.keysym == 'Right': 
    c.move(ship_id, SHIP_SPD, 0) 

随着

shipPosition = c.coords(ship_id) 
if event.keysym == 'Left' and shipPostion[0] > c.coords(left_bound)[0]: 
    c.move(ship_id, -SHIP_SPD, 0) 
elif event.keysym == 'Right' and shipPosition[0] < c.coords(right_bound)[0]: 
    c.move(ship_id, SHIP_SPD, 0) 

只应允许向左移动球员,如果他们的位置比约束左边的x位置更大,且只允许玩家如果他们的位置小于右边界的x位置,则向右移动。

然而,由于船舶的位置由左边决定的,你可能会想将它更改为

elif event.keysym == 'Right' and shipPosition[0] < c.coords(right_bound)[0] - 50: 
    c.move(ship_id, SHIP_SPD, 0) 

其中50是船的大小。

+0

谢谢你完美的作品 –