2015-09-06 95 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

謝謝你完美的作品 –