项目分析:
构成:
蛇 Snake
食物 Food
世界 World
蛇和食物属于整个世界
  class World:
      self.snake
      self.food
上面代码不太友好
我们用另外一个思路来分析
我们的分析思路
食物是一个独立的事物
蛇也可以认为是一个独立的事物
世界也是,但世界负责显示

------------------------------------------------

import queue
import time
from tkinter import *
import threading
import random
class GUI(Tk):
    def __init__(self, queue):
        Tk.__init__(self)
        self.queue = queue
        self.is_game_over = False
        #self.canvas = Canvas(self, width=500, height=300, bg='#000000')
        self.canvas = Canvas(self, width=500, height=300, bg='gray')
        self.canvas.pack()
        self.snake = self.canvas.create_line((0,0),(0,0), fill='#FFCC4C', width=10)
        self.food = self.canvas.create_rectangle(0,0,0,0,fill='#FFCC4C', outline='#FFCC4C')
        self.points_earned = self.canvas.create_text(450, 20,fill='white', text='SCORE: 0')
        self.queue_handler()
    def queue_handler(self):
        try:
            while True:
                task = self.queue.get(block=False)
                if task.get("game_over"):
                    self.game_over()
                if task.get('move'):
                    points = [ x for point in task['move'] for x in point]
                    self.canvas.coords(self.snake, *points)
                if task.get('food'):
                    self.canvas.coords(self.food, *task['food'])
                elif task.get('points_earned'):
                    self.canvas.itemconfigure(self.points_earned,
                                              text='SCORE: {}'.format(task['points_earned']))
                    self.queue.task_done()
        except queue.Empty:
            if not self.is_game_over:
                self.canvas.after(100, self.queue_handler)
    def game_over(self):
        self.is_game_over = True
        self.canvas.create_text(200,150, fill='white', text='Game Over')
        quitbtn = Button(self, text='Quit', command=self.destroy)
        rebtn = Button(self, text='Begin', command=self.__init__)
        self.canvas.create_window(200, 180, anchor='nw', window=quitbtn)
class Food():
    def __init__(self,queue):
        self.queue = queue
        self.generate_food()
    def generate_food(self):
        x = random.randrange(5,490,10)
        y = random.randrange(5, 290,10)
        self.postion = x,y
        self.exppos = x - 5, y - 5, x + 5, y + 5
        self.queue.put({'food':self.exppos})
class Snake(threading.Thread):
    def __init__(self,gui, queue):
        threading.Thread.__init__(self)
        self.gui = gui
        self.queue = queue
        self.daemon = True
        self.points_earned = 0
        self.snake_points = [(495,55),(485,55), (465,55),(455,55)]
        self.food = Food(queue)
        self.direction = 'Left'
        self.start()
    def run(self):
        if self.gui.is_game_over:
            self._delete()
        while not self.gui.is_game_over:
            self.queue.put({'move': self.snake_points})
            time.sleep(0.5)
            self.move()
    def key_pressed(self,e):
        # keysym 按键名称
        self.direction = e.keysym
    def move(self):
        new_snake_point = self.calculate_new_coordinates()
        if self.food.postion == new_snake_point:
            self.points_earned += 1
            self.queue.put({'points_earned': self.points_earned})
            self.food.generate_food()
        else:
            self.snake_points.pop(0)
            self.check_game_over(new_snake_point)
            self.snake_points.append(new_snake_point)
    def calculate_new_coordinates(self):
        last_x, last_y = self.snake_points[-1]
        if self.direction == 'Up':
            new_snake_point = last_x, last_y - 10
        elif self.direction == 'Down':
            new_snake_point = last_x, last_y + 10
        elif self.direction == 'Left':
            new_snake_point = last_x - 10, last_y
        elif self.direction == 'Right':
            new_snake_point = last_x + 10, last_y
        return new_snake_point
    def check_game_over(self, snake_point):
        x,y = snake_point[0], snake_point[1]
        if not -5 < x < 505 or not -5 < y < 315 or snake_point in self.snake_points:
            self.queue.put({'game_over': True})
def main():
    q = queue.Queue()
    gui = GUI(q)
    gui.title("傻傻的贪吃蛇")
    #global  q, gui
    snake = Snake(gui,q)
    gui.bind('<Key-Left>', snake.key_pressed)
    gui.bind('<Key-Right>', snake.key_pressed)
    gui.bind('<Key-Up>', snake.key_pressed)
    gui.bind('<Key-Down>', snake.key_pressed)
    gui.mainloop()
if __name__ == "__main__":
    main()

Python---tkinter---贪吃蛇(能用的)的更多相关文章

  1. 【python】10分钟教你用python打造贪吃蛇超详细教程

    10分钟教你用python打造贪吃蛇超详细教程 在家闲着没妹子约, 刚好最近又学了一下python,听说pygame挺好玩的.今天就在家研究一下, 弄了个贪吃蛇出来.希望大家喜欢. 先看程序效果: 0 ...

  2. 多线程的Python 教程--“贪吃蛇”

    本指南的里代码可以在这里下载:  threadworms.py ,或者从  GitHub.代码需要  Python 3 或 Python 2 ,同时也需要安装  Pygame . 点击查看大版本图片 ...

  3. 一步步教你怎么用python写贪吃蛇游戏

    目录 0 引言 1 环境 2 需求分析 3 代码实现 4 后记 0 引言 前几天,星球有人提到贪吃蛇,一下子就勾起了我的兴趣,毕竟在那个Nokia称霸的年代,这款游戏可是经典中的经典啊!而用Pytho ...

  4. 如何用python制作贪吃蛇以及AI版贪吃蛇

    用python制作普通贪吃蛇 哈喽,大家不知道是上午好还是中午好还是下午好还是晚上好! 很多人学习python,不知道从何学起.很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手.很 ...

  5. python实现贪吃蛇

    贪吃蛇的算法还是比较简单的,蛇的移动我是通过不停添加一个head方块,然后判断应该加到蛇头的哪个方向,加完后删掉蛇尾就行了,如果吃到食物就不删蛇尾. 只是一个贪吃蛇只需要70行代码左右就可以了,后来又 ...

  6. Python实例:贪吃蛇(简单贪吃蛇编写)🐍

    d=====( ̄▽ ̄*)b 叮~ Python -- 简易贪吃蛇实现 目录: 1.基本原理 2.需要学习的库 3.代码实现 1.基本原理 基本贪吃蛇所需要的东西其实很少,只需要有一块让蛇动的屏幕, 在 ...

  7. 【C/C++】10分钟教你用C++写一个贪吃蛇附带AI功能(附源代码详解和下载)

    C++编写贪吃蛇小游戏快速入门 刚学完C++.一时兴起,就花几天时间手动做了个贪吃蛇,后来觉得不过瘾,于是又加入了AI功能.希望大家Enjoy It. 效果图示 AI模式演示 imageimage 整 ...

  8. Python写的贪吃蛇游戏例子

    第一次用Python写这种比较实用且好玩的东西,权当练手吧 游戏说明: * P键控制“暂停/开始”* 方向键控制贪吃蛇的方向 源代码如下: 复制代码代码如下: from Tkinter import ...

  9. 使用Python写一个贪吃蛇

    参考代码http://blog.csdn.net/leepwang/article/details/7640880 我在程序中加入了分数显示,三种特殊食物,将贪吃蛇的游戏逻辑写到了SnakeGame的 ...

  10. 用Python写一个贪吃蛇

    最近在学Python,想做点什么来练练手,命令行的贪吃蛇一般是C的练手项目,但是一时之间找不到别的,就先做个贪吃蛇来练练简单的语法. 由于Python监听键盘很麻烦,没有C语言的kbhit(),所以这 ...

随机推荐

  1. 测开之路一百四十六:WTForms之表单应用

    WTForms主要是两个功能:1.生成HTML标签  2.对数据格式进行验证 官网:https://wtforms.readthedocs.io/en/stable/ 这篇介绍用wtform生成htm ...

  2. laravel 配置双模板引擎

    有时候我们可能有这种需求,pc 和 mobile 端显示的页面不一样,这个时候,我们就需要判断设备类型: ****我们用  composer require whichbrowser/parser  ...

  3. 各种开源许可 license 区别

    copy from http://www.ruanyifeng.com/blog/2011/05/how_to_choose_free_software_licenses.html

  4. 【Linux开发】【Qt开发】交叉编译器 arm-linux-gnueabi 和 arm-linux-gnueabihf 的区别

    一. 什么是ABI和EABI1) ABI: 二进制应用程序接口(Application Binary Interface (ABI) for the ARM Architecture)在计算机中,应用 ...

  5. python 并发编程 多进程 队列

    队列介绍 进程彼此之间互相隔离,要实现进程间通信(IPC),multiprocessing模块支持两种形式:队列和管道,这两种方式都是使用消息传递的 创建队列的类(底层就是以管道和锁定的方式实现) 制 ...

  6. Nginx跨域问题

    Nginx跨域无法访问,通常报错: Failed to load http://172.18.6.30:8086/CityServlet: No 'Access-Control-Allow-Origi ...

  7. MAC_BOOKPRO苹果电脑系统常用快捷键大全

    Mac 键盘快捷键 我在品多多上拼的Mac终于到货了,安全下车,接下来要熟练使用了! 您可以按下某些组合键来实现通常需要鼠标.触控板或其他输入设备才能完成的操作.   要使用键盘快捷键,请按住一个或多 ...

  8. windows10下安装pygame并验证成功

    首先要确保网络正常 py -m pip install --upgrade pip python -m pip install pygame --user 然后进行验证: py -m pygame.e ...

  9. JGit、SvnKit - 版本提交日志(1)提取

    1.相关开源jar包  1>使用JGIT访问git项目  2>使用SVNkit访问svn Git官方JGit使用教程指导 2.Git历史提交日志导出到文件 在项目根目录执行如下命令,将日志 ...

  10. Python虚拟环境命令

    cd D:\virtual\ virtualenv -p D\Python35\python.exe env1 cd env1 cd Scripts activate.bat # 激活该虚拟环境 de ...