2021-06-04

***********************************************PYTHON推箱子代码******************************************************
上次我们写了贪吃蛇:

https://blog.csdn.net/m0_58989917/article/details/117557272

这次我们写一下推箱子。

代码如下:

import tkinter as tk
import pyautogui as ag
def Box_Move(event):
    global x, y, w
    if event.keysym == "Up":
        if y - w > 0:
            tCanvas.move(box, 0, -w)
            tCanvas.move(box2, 0, -w)
            tCanvas.move(pol, 0, -w)
            y -= w
    elif event.keysym == "Down":
        if y + w < 400 - w:
            tCanvas.move(box, 0, w)
            tCanvas.move(box2, 0, w)
            tCanvas.move(pol, 0, w)
            y += w
    elif event.keysym == "Left":
        if x - w > 0:
            tCanvas.move(box, -w, 0)
            tCanvas.move(box2, -w, 0)
            tCanvas.move(pol, -w, 0)
            x -= w
    elif event.keysym == "Right":
        if x + w < 400 - w:
            tCanvas.move(box, w, 0)
            tCanvas.move(box2, w, 0)
            tCanvas.move(pol, w, 0)
            x += w
 
 
def Window_Open(W, H):
    X, Y = ag.size()
    winSize = "%sx%s" % (str(W), str(H))
    winPos = winSize + '+%s+%s' % (str((X - W) // 2), str((Y - H) // 2))
    win.geometry(winPos)
    win.resizable(False, False)
    title = u'桌面分辨率:%sx%s%s窗体大小:%s' % (str(X), str(Y), ' ' * 3, winSize)
    win.title(title)
    win.update()
 
 
def Draw_Lines(w):
    for i in range(20, 400, w):
        coord = 20, i, 380, i
        tCanvas.create_line(coord)
        coord = i, 20, i, 380
        tCanvas.create_line(coord)
 
 
def Draw_Box():
    global box, pol, box2
    box = tCanvas.create_rectangle(x, y, x + w, y + w, width=2, fill='yellow')
    coord = (x + 2, y + 2, x + 20, y + 20, x + 2, y + 38, x + 38, y + 38, x + 20, y + 20, x + 38, y + 2)
    pol = tCanvas.create_polygon(coord, width=2, outline='green', fill='gold')
    box2 = tCanvas.create_rectangle(x + 2, y + 2, x + w - 2, y + w - 2, width=2, outline='red')
 
 
if __name__ == '__main__':
    win = tk.Tk()
    Window_Open(400, 400)
 
    tCanvas = tk.Canvas(win, width=win.winfo_width(), height=400, bg='honeydew')
    tCanvas.pack(side="top")
 
    x, y, w = 100, 100, 40
 
    Draw_Lines(w)
    Draw_Box()
 
    # 绑定上下左右方向按键事件
    tCanvas.bind_all("<KeyPress-Up>", Box_Move)
    tCanvas.bind_all("<KeyPress-Down>", Box_Move)
    tCanvas.bind_all("<KeyPress-Left>", Box_Move)
    tCanvas.bind_all("<KeyPress-Right>", Box_Move)
 
    win.mainloop()


pyautogui下载:
pip install pyautogui

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值