<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                # Tkinter 中的貪食蛇 > 原文: [http://zetcode.com/tkinter/snake/](http://zetcode.com/tkinter/snake/) 在 Tkinter 教程的這一部分中,我們創建一個貪食蛇游戲克隆。 貪食蛇是較舊的經典視頻游戲。 它最初是在 70 年代后期創建的。 后來它被帶到 PC 上。 在這個游戲中,玩家控制蛇。 目的是盡可能多地吃蘋果。 蛇每次吃一個蘋果,它的身體就會長大。 蛇必須避開墻壁和自己的身體。 ## 開發 蛇的每個關節的大小為 10 像素。 蛇由光標鍵控制。 最初,蛇具有三個關節。 游戲立即開始。 游戲結束后,我們將在窗口中心顯示分數上方的游戲結束消息。 我們使用`Canvas`小部件來創建游戲。 游戲中的對象是圖像。 我們使用畫布方法創建圖像項。 我們使用畫布方法使用標簽在畫布上查找項目并進行碰撞檢測。 `snake.py` ```py #!/usr/bin/env python3 """ ZetCode Tkinter tutorial This is a simple Snake game clone. Author: Jan Bodnar Website: zetcode.com Last edited: April 2019 """ import sys import random from PIL import Image, ImageTk from tkinter import Tk, Frame, Canvas, ALL, NW class Cons: BOARD_WIDTH = 300 BOARD_HEIGHT = 300 DELAY = 100 DOT_SIZE = 10 MAX_RAND_POS = 27 class Board(Canvas): def __init__(self): super().__init__(width=Cons.BOARD_WIDTH, height=Cons.BOARD_HEIGHT, background="black", highlightthickness=0) self.initGame() self.pack() def initGame(self): '''initializes game''' self.inGame = True self.dots = 3 self.score = 0 # variables used to move snake object self.moveX = Cons.DOT_SIZE self.moveY = 0 # starting apple coordinates self.appleX = 100 self.appleY = 190 self.loadImages() self.createObjects() self.locateApple() self.bind_all("<Key>", self.onKeyPressed) self.after(Cons.DELAY, self.onTimer) def loadImages(self): '''loads images from the disk''' try: self.idot = Image.open("dot.png") self.dot = ImageTk.PhotoImage(self.idot) self.ihead = Image.open("head.png") self.head = ImageTk.PhotoImage(self.ihead) self.iapple = Image.open("apple.png") self.apple = ImageTk.PhotoImage(self.iapple) except IOError as e: print(e) sys.exit(1) def createObjects(self): '''creates objects on Canvas''' self.create_text(30, 10, text="Score: {0}".format(self.score), tag="score", fill="white") self.create_image(self.appleX, self.appleY, image=self.apple, anchor=NW, tag="apple") self.create_image(50, 50, image=self.head, anchor=NW, tag="head") self.create_image(30, 50, image=self.dot, anchor=NW, tag="dot") self.create_image(40, 50, image=self.dot, anchor=NW, tag="dot") def checkAppleCollision(self): '''checks if the head of snake collides with apple''' apple = self.find_withtag("apple") head = self.find_withtag("head") x1, y1, x2, y2 = self.bbox(head) overlap = self.find_overlapping(x1, y1, x2, y2) for ovr in overlap: if apple[0] == ovr: self.score += 1 x, y = self.coords(apple) self.create_image(x, y, image=self.dot, anchor=NW, tag="dot") self.locateApple() def moveSnake(self): '''moves the Snake object''' dots = self.find_withtag("dot") head = self.find_withtag("head") items = dots + head z = 0 while z < len(items)-1: c1 = self.coords(items[z]) c2 = self.coords(items[z+1]) self.move(items[z], c2[0]-c1[0], c2[1]-c1[1]) z += 1 self.move(head, self.moveX, self.moveY) def checkCollisions(self): '''checks for collisions''' dots = self.find_withtag("dot") head = self.find_withtag("head") x1, y1, x2, y2 = self.bbox(head) overlap = self.find_overlapping(x1, y1, x2, y2) for dot in dots: for over in overlap: if over == dot: self.inGame = False if x1 < 0: self.inGame = False if x1 > Cons.BOARD_WIDTH - Cons.DOT_SIZE: self.inGame = False if y1 < 0: self.inGame = False if y1 > Cons.BOARD_HEIGHT - Cons.DOT_SIZE: self.inGame = False def locateApple(self): '''places the apple object on Canvas''' apple = self.find_withtag("apple") self.delete(apple[0]) r = random.randint(0, Cons.MAX_RAND_POS) self.appleX = r * Cons.DOT_SIZE r = random.randint(0, Cons.MAX_RAND_POS) self.appleY = r * Cons.DOT_SIZE self.create_image(self.appleX, self.appleY, anchor=NW, image=self.apple, tag="apple") def onKeyPressed(self, e): '''controls direction variables with cursor keys''' key = e.keysym LEFT_CURSOR_KEY = "Left" if key == LEFT_CURSOR_KEY and self.moveX <= 0: self.moveX = -Cons.DOT_SIZE self.moveY = 0 RIGHT_CURSOR_KEY = "Right" if key == RIGHT_CURSOR_KEY and self.moveX >= 0: self.moveX = Cons.DOT_SIZE self.moveY = 0 RIGHT_CURSOR_KEY = "Up" if key == RIGHT_CURSOR_KEY and self.moveY <= 0: self.moveX = 0 self.moveY = -Cons.DOT_SIZE DOWN_CURSOR_KEY = "Down" if key == DOWN_CURSOR_KEY and self.moveY >= 0: self.moveX = 0 self.moveY = Cons.DOT_SIZE def onTimer(self): '''creates a game cycle each timer event''' self.drawScore() self.checkCollisions() if self.inGame: self.checkAppleCollision() self.moveSnake() self.after(Cons.DELAY, self.onTimer) else: self.gameOver() def drawScore(self): '''draws score''' score = self.find_withtag("score") self.itemconfigure(score, text="Score: {0}".format(self.score)) def gameOver(self): '''deletes all objects and draws game over message''' self.delete(ALL) self.create_text(self.winfo_width() /2, self.winfo_height()/2, text="Game Over with score {0}".format(self.score), fill="white") class Snake(Frame): def __init__(self): super().__init__() self.master.title('Snake') self.board = Board() self.pack() def main(): root = Tk() nib = Snake() root.mainloop() if __name__ == '__main__': main() ``` 首先,我們將定義一些在游戲中使用的常量。 ```py class Cons: BOARD_WIDTH = 300 BOARD_HEIGHT = 300 DELAY = 100 DOT_SIZE = 10 MAX_RAND_POS = 27 ``` `BOARD_WIDTH`和`BOARD_HEIGHT`常數確定電路板的大小。 `DELAY`常數確定游戲的速度。 `DOT_SIZE`是蘋果的大小和蛇的點。 `MAX_RAND_POS`常數用于計算蘋果的隨機位置。 `initGame()`方法初始化變量,加載圖像并啟動超時功能。 ```py self.createObjects() self.locateApple() ``` `createObjects()`方法在畫布上創建項目。 `locateApple()`在畫布上隨機放置一個蘋果。 ```py self.bind_all("<Key>", self.onKeyPressed) ``` 我們將鍵盤事件綁定到`onKeyPressed()`方法。 游戲由鍵盤光標鍵控制。 ```py try: self.idot = Image.open("dot.png") self.dot = ImageTk.PhotoImage(self.idot) self.ihead = Image.open("head.png") self.head = ImageTk.PhotoImage(self.ihead) self.iapple = Image.open("apple.png") self.apple = ImageTk.PhotoImage(self.iapple) except IOError as e: print(e) sys.exit(1) ``` 在這些行中,我們加載圖像。 貪食蛇游戲中包含三個圖像:頭部,圓點和蘋果。 ```py def createObjects(self): '''creates objects on Canvas''' self.create_text(30, 10, text="Score: {0}".format(self.score), tag="score", fill="white") self.create_image(self.appleX, self.appleY, image=self.apple, anchor=NW, tag="apple") self.create_image(50, 50, image=self.head, anchor=NW, tag="head") self.create_image(30, 50, image=self.dot, anchor=NW, tag="dot") self.create_image(40, 50, image=self.dot, anchor=NW, tag="dot") ``` 在`createObjects()`方法中,我們在畫布上創建游戲對象。 這些是帆布項目。 它們被賦予初始的 x 和 y 坐標。 `image`參數提供要顯示的圖像。 `anchor`參數設置為`NW`; 這樣,畫布項目的坐標就是項目的左上角。 如果我們希望能夠在根窗口的邊框旁邊顯示圖像,這很重要。 嘗試刪除錨點,看看會發生什么。 `tag`參數用于識別畫布上的項目。 一個標簽可用于多個畫布項目。 `checkAppleCollision()`方法檢查蛇是否擊中了蘋果對象。 如果是這樣,我們會增加分數,添加另一個蛇形關節,并稱為`locateApple()`。 ```py apple = self.find_withtag("apple") head = self.find_withtag("head") ``` `find_withtag()`方法使用其標簽在畫布上找到一個項目。 我們需要兩個項目:蛇的頭和蘋果。 請注意,即使只有一個帶有給定標簽的項目,該方法也會返回一個元組。 蘋果產品就是這種情況。 然后,可以通過以下方式訪問蘋果項目:`apple[0]`。 ```py x1, y1, x2, y2 = self.bbox(head) overlap = self.find_overlapping(x1, y1, x2, y2) ``` `bbox()`方法返回項目的邊界框點。 `find_overlapping()`方法查找給定坐標的沖突項。 ```py for ovr in overlap: if apple[0] == ovr: x, y = self.coords(apple) self.create_image(x, y, image=self.dot, anchor=NW, tag="dot") self.locateApple() ``` 如果蘋果與頭部碰撞,我們將在蘋果對象的坐標處創建一個新的點項目。 我們調用`locateApple()`方法,該方法從畫布上刪除舊的蘋果項目,然后創建并隨機放置一個新的項目。 在`moveSnake()`方法中,我們有游戲的關鍵算法。 要了解它,請看一下蛇是如何運動的。 我們控制蛇的頭。 我們可以使用光標鍵更改其方向。 其余關節在鏈上向上移動一個位置。 第二關節移動到第一個關節的位置,第三關節移動到第二個關節的位置,依此類推。 ```py z = 0 while z < len(items)-1: c1 = self.coords(items[z]) c2 = self.coords(items[z+1]) self.move(items[z], c2[0]-c1[0], c2[1]-c1[1]) z += 1 ``` 該代碼將關節向上移動。 ```py self.move(head, self.moveX, self.moveY) ``` 我們使用`move()`方法移動磁頭。 按下光標鍵時,將設置`self.moveX`和`self.moveY`變量。 在`checkCollisions()`方法中,我們確定蛇是否擊中了自己或撞墻之一。 ```py x1, y1, x2, y2 = self.bbox(head) overlap = self.find_overlapping(x1, y1, x2, y2) for dot in dots: for over in overlap: if over == dot: self.inGame = False ``` 如果蛇用頭撞到關節之一,我們就結束游戲。 ```py if y1 > Cons.BOARD_HEIGHT - Cons.DOT_SIZE: self.inGame = False ``` 如果蛇擊中`Board`的底部,我們就結束游戲。 `locateApple()`方法在板上隨機找到一個新蘋果,然后刪除舊的蘋果。 ```py apple = self.find_withtag("apple") self.delete(apple[0]) ``` 在這里,我們找到并刪除了被蛇吃掉的蘋果。 ```py r = random.randint(0, Cons.MAX_RAND_POS) ``` 我們得到一個從 0 到`MAX_RAND_POS-1`的隨機數。 ```py self.appleX = r * Cons.DOT_SIZE ... self.appleY = r * Cons.DOT_SIZE ``` 這些行設置了`apple`對象的 x 和 y 坐標。 在`onKeyPressed()`方法中,我們在游戲過程中對按下的鍵做出反應。 ```py LEFT_CURSOR_KEY = "Left" if key == LEFT_CURSOR_KEY and self.moveX <= 0: self.moveX = -Cons.DOT_SIZE self.moveY = 0 ``` 如果我們按左光標鍵,則相應地設置`self.moveX`和`self.moveY`變量。 在`moveSnake()`方法中使用這些變量來更改蛇對象的坐標。 還要注意,當蛇向右行駛時,我們不能立即向左轉。 ```py def onTimer(self): '''creates a game cycle each timer event ''' self.drawScore() self.checkCollisions() if self.inGame: self.checkAppleCollision() self.moveSnake() self.after(Cons.DELAY, self.onTimer) else: self.gameOver() ``` 每`DELAY` ms,就會調用`onTimer()`方法。 如果我們參與了游戲,我們將調用三種構建游戲邏輯的方法。 否則,游戲結束。 計時器基于`after()`方法,該方法僅在`DELAY` ms 之后調用一次方法。 要重復調用計時器,我們遞歸調用`onTimer()`方法。 ```py def drawScore(self): '''draws score''' score = self.find_withtag("score") self.itemconfigure(score, text="Score: {0}".format(self.score)) ``` `drawScore()`方法在板上畫分數。 ```py def gameOver(self): '''deletes all objects and draws game over message''' self.delete(ALL) self.create_text(self.winfo_width() /2, self.winfo_height()/2, text="Game Over with score {0}".format(self.score), fill="white") ``` 如果游戲結束,我們將刪除畫布上的所有項目。 然后,我們將游戲的最終比分繪制在屏幕中央。 ![Snake](https://img.kancloud.cn/1f/b2/1fb213966db9506266bc7cdcc7dda577_302x326.jpg) 圖:貪食蛇 這是用 Tkinter 創建的貪食蛇電腦游戲。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看