{"id":1968,"date":"2022-11-30T11:44:06","date_gmt":"2022-11-30T03:44:06","guid":{"rendered":"https:\/\/qaqaq.top\/?p=1968"},"modified":"2023-01-10T22:06:38","modified_gmt":"2023-01-10T14:06:38","slug":"python-tkinter%e5%86%99%e4%b8%80%e4%b8%aa%e8%b4%aa%e5%90%83%e8%9b%87","status":"publish","type":"post","link":"https:\/\/qaqaq.top\/?p=1968","title":{"rendered":"python tkinter \u5199\u4e00\u4e2a\u8d2a\u5403\u86c7"},"content":{"rendered":"\n<figure class=\"wp-block-image size-large\"><div class='fancybox-wrapper lazyload-container-unload' data-fancybox='post-images' href='https:\/\/qaqaq.top\/wp-content\/uploads\/2023\/01\/image-219-1024x971.png'><img class=\"lazyload lazyload-style-1\" src=\"data:image\/svg+xml;base64,PCEtLUFyZ29uTG9hZGluZy0tPgo8c3ZnIHdpZHRoPSIxIiBoZWlnaHQ9IjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgc3Ryb2tlPSIjZmZmZmZmMDAiPjxnPjwvZz4KPC9zdmc+\"  loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"971\" data-original=\"https:\/\/qaqaq.top\/wp-content\/uploads\/2023\/01\/image-219-1024x971.png\" src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB\/AAffA0nNPuCLAAAAAElFTkSuQmCC\" alt=\"\" class=\"wp-image-3534\"  sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/div><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>from tkinter import *\nimport random\n\n# \u6e38\u620f\u8bbe\u7f6e\nGAME_WIDTH = 800  # \u6e38\u620f\u5bbd\u5ea6\nGAME_HEIGHT = 800  # \u6e38\u620f\u9ad8\u5ea6\nSPEED = 50  # \u8d2a\u5403\u86c7\u901f\u5ea6\nSPACE_SIZE = 50  # \u6e38\u620f\u5355\u4e2a\u90e8\u4ef6\u7684\u5927\u5c0f\nBODY_PARTS = 3  # \u8d2a\u5403\u86c7\u521d\u59cb\u957f\u5ea6\nSNAKE_COLOR = \"#0000FF\"  # \u8d2a\u5403\u86c7\u989c\u8272\nFOOD_COLOR = \"#FFFF00\"  # \u98df\u7269\u989c\u8272\nBACKGROUND_COLOR = \"#000000\"  # \u6e38\u620f\u80cc\u666f\u989c\u8272\n\n\n# \u751f\u6210\u8d2a\u5403\u86c7\nclass Snake:\n\n    def __init__(self, canvas):\n        self.body_size = BODY_PARTS\n        self.coordinates = &#91;]\n        self.squares = &#91;]\n\n        for i in range(0, BODY_PARTS):\n            self.coordinates.append(&#91;0, 0])\n\n        for x, y in self.coordinates:\n            square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR, tag=\"snake\")\n            self.squares.append((square))\n\n\n# \u751f\u6210\u98df\u7269\nclass Food:\n\n    def __init__(self, canvas):\n        # 700 \/ 50 = 14 (0,13)\n        x = random.randint(0, GAME_WIDTH \/ SPACE_SIZE - 1) * SPACE_SIZE\n        y = random.randint(0, GAME_HEIGHT \/ SPACE_SIZE - 1) * SPACE_SIZE\n\n        self.coordonates = &#91;x, y]\n\n        canvas.create_oval(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=FOOD_COLOR, tags=\"food\")\n\n\n# \u6e38\u620f\nclass Game:\n\n    def __init__(self):\n\n        self.window = Tk()\n        self.window.title(\"Snake game\")\n        self.window.resizable(False, False)  # \u8bbe\u7f6e\u4e3a\u4e0d\u53ef\u8c03\u6574\u5927\u5c0f\n\n        # \u8bb0\u5f55\u5206\u6570\n        self.score = 0\n        # \u521d\u59cb\u65b9\u5411\n        self.direction = \"down\"\n\n        # \u8bb0\u5f55\u5206\u6570\u7684\u7a97\u4f53\n        self.label = Label(self.window, text=\"Score:{}\".format(self.score), font=(\"consolas\", 40))\n        self.label.pack()\n\n        # \u6e38\u620f\u8fd0\u884c\u4e3b\u7a97\u4f53\n        self.canvas = Canvas(self.window, bg=BACKGROUND_COLOR, height=GAME_HEIGHT, width=GAME_WIDTH)\n        self.canvas.pack()\n\n        # \u5237\u65b0\u7a97\u4f53\u4f7f\u5176\u5c55\u793a\u5230\u5c4f\u5e55\u4e2d\u95f4\n        self.window.update()\n\n        window_width = self.window.winfo_width()\n        window_height = self.window.winfo_height()\n        screen_width = self.window.winfo_screenwidth()\n        screen_height = self.window.winfo_screenheight()\n\n        x = int((screen_width \/ 2) - (window_width \/ 2))\n        y = int((screen_height \/ 2) - (window_height \/ 2))\n\n        self.window.geometry(f\"{window_width}x{window_height}+{x}+{y}\")\n\n        # \u7ed1\u5b9a\u6309\u952e\u4e8b\u4ef6\n        self.window.bind(\"&lt;Left&gt;\", lambda event: self.change_direction(\"left\"))\n        self.window.bind(\"&lt;Right&gt;\", lambda event: self.change_direction(\"right\"))\n        self.window.bind(\"&lt;Up&gt;\", lambda event: self.change_direction(\"up\"))\n        self.window.bind(\"&lt;Down&gt;\", lambda event: self.change_direction(\"down\"))\n\n        # \u8c03\u7528\u751f\u6210\u8d2a\u5403\u86c7\u548c\u98df\u7269\n        snake = Snake(self.canvas)\n        food = Food(self.canvas)\n\n        # \u8c03\u7528\u5f00\u59cb\u6e38\u620f\n        self.next_turn(snake, food)\n\n        self.window.mainloop()\n\n    # \u5f00\u59cb\u6e38\u620f\n    def next_turn(self, snake, food):\n        # \u7ed8\u5236\u8d2a\u5403\u86c7\u8eab\u4f53\n        x, y = snake.coordinates&#91;0]\n\n        if self.direction == \"up\":\n            y -= SPACE_SIZE\n        elif self.direction == \"down\":\n            y += SPACE_SIZE\n        elif self.direction == \"left\":\n            x -= SPACE_SIZE\n        elif self.direction == \"right\":\n            x += SPACE_SIZE\n\n        snake.coordinates.insert(0, (x, y))\n\n        square = self.canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR)\n\n        snake.squares.insert(0, square)\n\n        # \u5b9e\u73b0\u5403\u6389\u98df\u7269\u5e76\u8ba1\u7b97\u5206\u6570\n        if x == food.coordonates&#91;0] and y == food.coordonates&#91;1]:\n\n            self.score += 1\n\n            self.label.config(text=\"Score:{}\".format(self.score))\n\n            self.canvas.delete(\"food\")\n\n            food = Food(self.canvas)\n\n        else:\n\n            del snake.coordinates&#91;-1]\n\n            self.canvas.delete(snake.squares&#91;-1])\n\n            del snake.squares&#91;-1]\n\n        # \u5b9e\u73b0\u6709\u78b0\u649e\u7ed3\u675f\u6e38\u620f\n        if self.check_collisions(snake):\n            self.game_over()\n\n        else:\n            self.window.after(SPEED, self.next_turn, snake, food)\n\n    # \u63a7\u5236\u65b9\u5411\n    def change_direction(self, new_direction):\n\n        if new_direction == \"left\":\n            if self.direction != \"right\":\n                self.direction = new_direction\n        elif new_direction == \"right\":\n            if self.direction != \"left\":\n                self.direction = new_direction\n        elif new_direction == \"up\":\n            if self.direction != \"down\":\n                self.direction = new_direction\n        elif new_direction == \"down\":\n            if self.direction != \"up\":\n                self.direction = new_direction\n\n    # \u68c0\u67e5\u78b0\u649e\n    def check_collisions(self, snake):\n\n        x, y = snake.coordinates&#91;0]\n\n        # \u68c0\u67e5\u5899\u58c1\u78b0\u649e\n        if x &lt; 0 or x &gt;= GAME_WIDTH:\n            return True\n        elif y &lt; 0 or y &gt;= GAME_HEIGHT:\n            return True\n\n        # \u68c0\u67e5\u8eab\u4f53\u78b0\u649e\n        for body_part in snake.coordinates&#91;1:]:\n            if x == body_part&#91;0] and y == body_part&#91;1]:\n                return True\n\n        return False\n\n    # \u6e38\u620f\u7ed3\u675f\n    def game_over(self):\n\n        self.canvas.delete(ALL)\n        self.canvas.create_text(self.canvas.winfo_width() \/ 2, self.canvas.winfo_height() \/ 2, font=(\"consolas\", 70),\n                                text=\"GAME OVER\", fill=\"red\", tags=\"gameover\")\n\n\nGame()\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[65],"tags":[50],"class_list":["post-1968","post","type-post","status-publish","format-standard","hentry","category-python-code","tag-python"],"_links":{"self":[{"href":"https:\/\/qaqaq.top\/index.php?rest_route=\/wp\/v2\/posts\/1968"}],"collection":[{"href":"https:\/\/qaqaq.top\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/qaqaq.top\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/qaqaq.top\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/qaqaq.top\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1968"}],"version-history":[{"count":3,"href":"https:\/\/qaqaq.top\/index.php?rest_route=\/wp\/v2\/posts\/1968\/revisions"}],"predecessor-version":[{"id":3535,"href":"https:\/\/qaqaq.top\/index.php?rest_route=\/wp\/v2\/posts\/1968\/revisions\/3535"}],"wp:attachment":[{"href":"https:\/\/qaqaq.top\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1968"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/qaqaq.top\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1968"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/qaqaq.top\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1968"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}