jjxyfxyt 2022-12-27 16:05 采纳率: 50%

# Python 3.11.1 下载mediapipe

``````import random

import cvzone
import cv2
import numpy as np
from cvzone.HandTrackingModule import HandDetector

cap = cv2.VideoCapture(0)   # 0代表自己电脑的摄像头
cap.set(3, 1280)        # 宽
cap.set(4, 720)         # 高

detector = HandDetector(detectionCon=0.8, maxHands=1)

class SnakeGameClass:
def __init__(self, pathFood):             # 构造方法
self.points = []            # 蛇身上所有的点
self.lengths = []           # 每个点之间的长度
self.currentLength = 0      # 蛇的总长
self.allowedLength = 150    # 蛇允许的总长度
self.previousHead = 0, 0    # 第二个头结点

self.hFood, self.wFood, _ = self.imgFood.shape
self.foodPoint = 0, 0
self.randomFoodLocation()

self.score = 0
self.gameOver = False

def randomFoodLocation(self):
self.foodPoint = random.randint(100, 1000), random.randint(100, 600)

def update(self, imgMain, currentHead):     # 实例方法

if self.gameOver:
cvzone.putTextRect(imgMain, "Game Over", [300, 400],
scale=7, thickness=5, offset=20)
scale=7, thickness=5, offset=20)
else:

self.points.append([cx, cy])             # 添加蛇的点列表节点
distance = math.hypot(cx - px, cy - py)  # 两点之间的距离
self.lengths.append(distance)            # 添加蛇的距离列表内容
self.currentLength += distance

# Length Reduction
if self.currentLength > self.allowedLength:
for i, length in enumerate(self.lengths):
self.currentLength -= length
self.lengths.pop(i)
self.points.pop(i)
if self.currentLength < self.allowedLength:
break

# Check if snake ate the food
rx, ry = self.foodPoint
if rx - self.wFood // 2 < cx < rx + self.wFood // 2 and \
ry - self.hFood // 2 < cy < ry + self.hFood // 2:
self.randomFoodLocation()
self.allowedLength += 50
self.score += 1
print(self.score)

# Draw Snake
if self.points:
for i, point in enumerate(self.points):
if i != 0:
cv2.line(imgMain, self.points[i - 1], self.points[i], (0, 0, 255), 20)
# 对列表最后一个点也就是蛇头画为紫色点
cv2.circle(imgMain, self.points[-1], 20, (200, 0, 200), cv2.FILLED)

# Draw Food

imgMain = cvzone.overlayPNG(imgMain, self.imgFood,
(rx - self.wFood // 2, ry - self.hFood // 2))

scale=3, thickness=5, offset=10)

# Check for Collision
pts = np.array(self.points[:-2], np.int32)
pts = pts.reshape((-1, 1, 2))  # 重塑为一个行数未知但只有一列且每个元素有2个子元素的矩阵
cv2.polylines(imgMain, [pts], False, (0, 200, 0), 3)
# 第三个参数是False，我们得到的是不闭合的线
minDist = cv2.pointPolygonTest(pts, (cx, cy), True)
# 参数True表示输出该像素点到轮廓最近距离

if -1 <= minDist <= 1:
print("Hit")
self.gameOver = True
self.points = []  # 蛇身上所有的点
self.lengths = []  # 每个点之间的长度
self.currentLength = 0  # 蛇的总长
self.allowedLength = 150  # 蛇允许的总长度
self.previousHead = 0, 0  # 第二个头结点
self.randomFoodLocation()

return imgMain

game = SnakeGameClass("./donut.png")

# 处理每一帧图像
while True:     # 不断迭代更新
# 翻转图像，使自身和摄像头中的自己呈镜像关系
img = cv2.flip(img, 1)      # 将手水平翻转
hands, img = detector.findHands(img, flipType=False)    # 左手是左手，右手是右手，映射正确

if hands:
lmList = hands[0]['lmList']     # hands是由N个字典组成的列表
pointIndex = lmList[8][0:2]     # 只要食指指尖的x和y坐标
img = game.update(img, pointIndex)

cv2.imshow("Image", img)
key = cv2.waitKey(1)
if key == ord('r'):
game.gameOver = False

``````

``````E:\PyCharm 2022.3\plugins\python\helpers\pydev\_pydev_bundle\pydev_import_hook.py:21: UserWarning: The NumPy module was reloaded (imported a second time). This can in some cases result in small but subtle issues and is discouraged.
module = self._system_import(name, *args, **kwargs)
Traceback (most recent call last):
File "E:\PyCharm 2022.3\plugins\python\helpers\pydev\pydevconsole.py", line 364, in runcode
coro = func()
^^^^^^
File "<input>", line 1, in <module>
File "E:\PyCharm 2022.3\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile
pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\PyCharm 2022.3\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "E:\python38\手势贪吃蛇.py", line 7, in <module>
from cvzone.HandTrackingModule import HandDetector
File "E:\PyCharm 2022.3\plugins\python\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Python11\Lib\site-packages\cvzone\HandTrackingModule.py", line 8, in <module>
import mediapipe as mp
File "E:\PyCharm 2022.3\plugins\python\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ModuleNotFoundError: No module named 'mediapipe'

``````

``````pip install mediapipe
pip install mediapipe -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install mediapipe -i http://pypi.douban.com/simple
``````

``````ERROR: Could not find a version that satisfies the requirement mediapipe (from
ERROR: No matching distribution found for mediapipe

``````

``````Traceback (most recent call last):
File "E:/PyCharm 2022.3/plugins/python/helpers/pydev/pydevconsole.py", line 5, in <module>
from _pydev_comm.pydev_rpc import make_rpc_client, start_rpc_server, start_rpc_server_and_make_client
File "E:\PyCharm 2022.3\plugins\python\helpers\pydev\_pydev_comm\pydev_rpc.py", line 4, in <module>
File "E:\PyCharm 2022.3\plugins\python\helpers\pydev\_pydev_comm\pydev_server.py", line 4, in <module>
File "E:\PyCharm 2022.3\plugins\python\helpers\third_party\thriftpy\_shaded_thriftpy\__init__.py", line 5, in <module>
from .hook import install_import_hook, remove_import_hook
File "E:\PyCharm 2022.3\plugins\python\helpers\third_party\thriftpy\_shaded_thriftpy\hook.py", line 7, in <module>
File "E:\PyCharm 2022.3\plugins\python\helpers\third_party\thriftpy\_shaded_thriftpy\parser\__init__.py", line 16, in <module>
from .parser import parse, parse_fp, incomplete_type, _cast
File "E:\PyCharm 2022.3\plugins\python\helpers\third_party\thriftpy\_shaded_thriftpy\parser\parser.py", line 17, in <module>
from _shaded_thriftpy._compat import urlopen, urlparse, PY3
File "E:\PyCharm 2022.3\plugins\python\helpers\third_party\thriftpy\_shaded_thriftpy\_compat.py", line 28, in <module>
from urllib.request import urlopen
File "E:\Python3.8.0\lib\urllib\request.py", line 88, in <module>
import http.client
File "E:\Python3.8.0\lib\http\client.py", line 72, in <module>
import email.message
File "E:\Python3.8.0\lib\email\message.py", line 10, in <module>
import uu
File "D:\程序\uu.py", line 1
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32
^
SyntaxError: invalid syntax

``````

• 写回答

#### 1条回答默认 最新

• 精神小黑猫 2022-12-28 11:16
关注

尝试在cmd中运行Python文件试试：

``````python xxx.py

``````

记得pycharm里面有设置Python环境的选项，我当时电脑装了个Python3.7，又下载了一个anaconda，当时用pycharm写python还需要把环境配置成anaconda的，不知道是不是这个原因

本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 问题事件

• 已结题 （查看结题原因） 1月26日
• 已采纳回答 1月26日
• 修改了问题 12月27日
• 修改了问题 12月27日
• 展开全部

#### 悬赏问题

• ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
• ¥50 关于多次提交POST数据后，无法获取到POST数据参数的问题
• ¥15 win10，这种情况怎么办
• ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式？（相关搜索：格式化）
• ¥100 在连接内网VPN时，如何同时保持互联网连接
• ¥15 MATLAB中使用parfor，矩阵Removal的有效索引在parfor循环中受限制
• ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
• ¥50 win10 LTSC 虚拟键盘不弹出
• ¥30 微信小程序请求失败，网页能正常带锁访问
• ¥15 Matlab求解微分方程，如何用fish2d进行预优？