master
abc15379 1 year ago
parent 075fef94f9
commit 1594f0fdad

3
.idea/.gitignore vendored

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

@ -0,0 +1,401 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DBNavigator.Project.DatabaseFileManager">
<open-files />
</component>
<component name="DBNavigator.Project.Settings">
<connections />
<browser-settings>
<general>
<display-mode value="TABBED" />
<navigation-history-size value="100" />
<show-object-details value="false" />
</general>
<filters>
<object-type-filter>
<object-type name="SCHEMA" enabled="true" />
<object-type name="USER" enabled="true" />
<object-type name="ROLE" enabled="true" />
<object-type name="PRIVILEGE" enabled="true" />
<object-type name="CHARSET" enabled="true" />
<object-type name="TABLE" enabled="true" />
<object-type name="VIEW" enabled="true" />
<object-type name="MATERIALIZED_VIEW" enabled="true" />
<object-type name="NESTED_TABLE" enabled="true" />
<object-type name="COLUMN" enabled="true" />
<object-type name="INDEX" enabled="true" />
<object-type name="CONSTRAINT" enabled="true" />
<object-type name="DATASET_TRIGGER" enabled="true" />
<object-type name="DATABASE_TRIGGER" enabled="true" />
<object-type name="SYNONYM" enabled="true" />
<object-type name="SEQUENCE" enabled="true" />
<object-type name="PROCEDURE" enabled="true" />
<object-type name="FUNCTION" enabled="true" />
<object-type name="PACKAGE" enabled="true" />
<object-type name="TYPE" enabled="true" />
<object-type name="TYPE_ATTRIBUTE" enabled="true" />
<object-type name="ARGUMENT" enabled="true" />
<object-type name="DIMENSION" enabled="true" />
<object-type name="CLUSTER" enabled="true" />
<object-type name="DBLINK" enabled="true" />
</object-type-filter>
</filters>
<sorting>
<object-type name="COLUMN" sorting-type="NAME" />
<object-type name="FUNCTION" sorting-type="NAME" />
<object-type name="PROCEDURE" sorting-type="NAME" />
<object-type name="ARGUMENT" sorting-type="POSITION" />
<object-type name="TYPE ATTRIBUTE" sorting-type="POSITION" />
</sorting>
<default-editors>
<object-type name="VIEW" editor-type="SELECTION" />
<object-type name="PACKAGE" editor-type="SELECTION" />
<object-type name="TYPE" editor-type="SELECTION" />
</default-editors>
</browser-settings>
<navigation-settings>
<lookup-filters>
<lookup-objects>
<object-type name="SCHEMA" enabled="true" />
<object-type name="USER" enabled="false" />
<object-type name="ROLE" enabled="false" />
<object-type name="PRIVILEGE" enabled="false" />
<object-type name="CHARSET" enabled="false" />
<object-type name="TABLE" enabled="true" />
<object-type name="VIEW" enabled="true" />
<object-type name="MATERIALIZED VIEW" enabled="true" />
<object-type name="INDEX" enabled="true" />
<object-type name="CONSTRAINT" enabled="true" />
<object-type name="DATASET TRIGGER" enabled="true" />
<object-type name="DATABASE TRIGGER" enabled="true" />
<object-type name="SYNONYM" enabled="false" />
<object-type name="SEQUENCE" enabled="true" />
<object-type name="PROCEDURE" enabled="true" />
<object-type name="FUNCTION" enabled="true" />
<object-type name="PACKAGE" enabled="true" />
<object-type name="TYPE" enabled="true" />
<object-type name="DIMENSION" enabled="false" />
<object-type name="CLUSTER" enabled="false" />
<object-type name="DBLINK" enabled="true" />
</lookup-objects>
<force-database-load value="false" />
<prompt-connection-selection value="true" />
<prompt-schema-selection value="true" />
</lookup-filters>
</navigation-settings>
<dataset-grid-settings>
<general>
<enable-zooming value="true" />
<enable-column-tooltip value="true" />
</general>
<sorting>
<nulls-first value="true" />
<max-sorting-columns value="4" />
</sorting>
<audit-columns>
<column-names value="" />
<visible value="true" />
<editable value="false" />
</audit-columns>
</dataset-grid-settings>
<dataset-editor-settings>
<text-editor-popup>
<active value="false" />
<active-if-empty value="false" />
<data-length-threshold value="100" />
<popup-delay value="1000" />
</text-editor-popup>
<values-actions-popup>
<show-popup-button value="true" />
<element-count-threshold value="1000" />
<data-length-threshold value="250" />
</values-actions-popup>
<general>
<fetch-block-size value="100" />
<fetch-timeout value="30" />
<trim-whitespaces value="true" />
<convert-empty-strings-to-null value="true" />
<select-content-on-cell-edit value="true" />
<large-value-preview-active value="true" />
</general>
<filters>
<prompt-filter-dialog value="true" />
<default-filter-type value="BASIC" />
</filters>
<qualified-text-editor text-length-threshold="300">
<content-types>
<content-type name="Text" enabled="true" />
<content-type name="Properties" enabled="true" />
<content-type name="XML" enabled="true" />
<content-type name="DTD" enabled="true" />
<content-type name="HTML" enabled="true" />
<content-type name="XHTML" enabled="true" />
<content-type name="SQL" enabled="true" />
<content-type name="PL/SQL" enabled="true" />
<content-type name="JSON" enabled="true" />
<content-type name="JSON5" enabled="true" />
<content-type name="YAML" enabled="true" />
</content-types>
</qualified-text-editor>
<record-navigation>
<navigation-target value="VIEWER" />
</record-navigation>
</dataset-editor-settings>
<code-editor-settings>
<general>
<show-object-navigation-gutter value="false" />
<show-spec-declaration-navigation-gutter value="true" />
<enable-spellchecking value="true" />
<enable-reference-spellchecking value="false" />
</general>
<confirmations>
<save-changes value="false" />
<revert-changes value="true" />
</confirmations>
</code-editor-settings>
<code-completion-settings>
<filters>
<basic-filter>
<filter-element type="RESERVED_WORD" id="keyword" selected="true" />
<filter-element type="RESERVED_WORD" id="function" selected="true" />
<filter-element type="RESERVED_WORD" id="parameter" selected="true" />
<filter-element type="RESERVED_WORD" id="datatype" selected="true" />
<filter-element type="RESERVED_WORD" id="exception" selected="true" />
<filter-element type="OBJECT" id="schema" selected="true" />
<filter-element type="OBJECT" id="role" selected="true" />
<filter-element type="OBJECT" id="user" selected="true" />
<filter-element type="OBJECT" id="privilege" selected="true" />
<user-schema>
<filter-element type="OBJECT" id="table" selected="true" />
<filter-element type="OBJECT" id="view" selected="true" />
<filter-element type="OBJECT" id="materialized view" selected="true" />
<filter-element type="OBJECT" id="index" selected="true" />
<filter-element type="OBJECT" id="constraint" selected="true" />
<filter-element type="OBJECT" id="trigger" selected="true" />
<filter-element type="OBJECT" id="synonym" selected="false" />
<filter-element type="OBJECT" id="sequence" selected="true" />
<filter-element type="OBJECT" id="procedure" selected="true" />
<filter-element type="OBJECT" id="function" selected="true" />
<filter-element type="OBJECT" id="package" selected="true" />
<filter-element type="OBJECT" id="type" selected="true" />
<filter-element type="OBJECT" id="dimension" selected="true" />
<filter-element type="OBJECT" id="cluster" selected="true" />
<filter-element type="OBJECT" id="dblink" selected="true" />
</user-schema>
<public-schema>
<filter-element type="OBJECT" id="table" selected="false" />
<filter-element type="OBJECT" id="view" selected="false" />
<filter-element type="OBJECT" id="materialized view" selected="false" />
<filter-element type="OBJECT" id="index" selected="false" />
<filter-element type="OBJECT" id="constraint" selected="false" />
<filter-element type="OBJECT" id="trigger" selected="false" />
<filter-element type="OBJECT" id="synonym" selected="false" />
<filter-element type="OBJECT" id="sequence" selected="false" />
<filter-element type="OBJECT" id="procedure" selected="false" />
<filter-element type="OBJECT" id="function" selected="false" />
<filter-element type="OBJECT" id="package" selected="false" />
<filter-element type="OBJECT" id="type" selected="false" />
<filter-element type="OBJECT" id="dimension" selected="false" />
<filter-element type="OBJECT" id="cluster" selected="false" />
<filter-element type="OBJECT" id="dblink" selected="false" />
</public-schema>
<any-schema>
<filter-element type="OBJECT" id="table" selected="true" />
<filter-element type="OBJECT" id="view" selected="true" />
<filter-element type="OBJECT" id="materialized view" selected="true" />
<filter-element type="OBJECT" id="index" selected="true" />
<filter-element type="OBJECT" id="constraint" selected="true" />
<filter-element type="OBJECT" id="trigger" selected="true" />
<filter-element type="OBJECT" id="synonym" selected="true" />
<filter-element type="OBJECT" id="sequence" selected="true" />
<filter-element type="OBJECT" id="procedure" selected="true" />
<filter-element type="OBJECT" id="function" selected="true" />
<filter-element type="OBJECT" id="package" selected="true" />
<filter-element type="OBJECT" id="type" selected="true" />
<filter-element type="OBJECT" id="dimension" selected="true" />
<filter-element type="OBJECT" id="cluster" selected="true" />
<filter-element type="OBJECT" id="dblink" selected="true" />
</any-schema>
</basic-filter>
<extended-filter>
<filter-element type="RESERVED_WORD" id="keyword" selected="true" />
<filter-element type="RESERVED_WORD" id="function" selected="true" />
<filter-element type="RESERVED_WORD" id="parameter" selected="true" />
<filter-element type="RESERVED_WORD" id="datatype" selected="true" />
<filter-element type="RESERVED_WORD" id="exception" selected="true" />
<filter-element type="OBJECT" id="schema" selected="true" />
<filter-element type="OBJECT" id="user" selected="true" />
<filter-element type="OBJECT" id="role" selected="true" />
<filter-element type="OBJECT" id="privilege" selected="true" />
<user-schema>
<filter-element type="OBJECT" id="table" selected="true" />
<filter-element type="OBJECT" id="view" selected="true" />
<filter-element type="OBJECT" id="materialized view" selected="true" />
<filter-element type="OBJECT" id="index" selected="true" />
<filter-element type="OBJECT" id="constraint" selected="true" />
<filter-element type="OBJECT" id="trigger" selected="true" />
<filter-element type="OBJECT" id="synonym" selected="true" />
<filter-element type="OBJECT" id="sequence" selected="true" />
<filter-element type="OBJECT" id="procedure" selected="true" />
<filter-element type="OBJECT" id="function" selected="true" />
<filter-element type="OBJECT" id="package" selected="true" />
<filter-element type="OBJECT" id="type" selected="true" />
<filter-element type="OBJECT" id="dimension" selected="true" />
<filter-element type="OBJECT" id="cluster" selected="true" />
<filter-element type="OBJECT" id="dblink" selected="true" />
</user-schema>
<public-schema>
<filter-element type="OBJECT" id="table" selected="true" />
<filter-element type="OBJECT" id="view" selected="true" />
<filter-element type="OBJECT" id="materialized view" selected="true" />
<filter-element type="OBJECT" id="index" selected="true" />
<filter-element type="OBJECT" id="constraint" selected="true" />
<filter-element type="OBJECT" id="trigger" selected="true" />
<filter-element type="OBJECT" id="synonym" selected="true" />
<filter-element type="OBJECT" id="sequence" selected="true" />
<filter-element type="OBJECT" id="procedure" selected="true" />
<filter-element type="OBJECT" id="function" selected="true" />
<filter-element type="OBJECT" id="package" selected="true" />
<filter-element type="OBJECT" id="type" selected="true" />
<filter-element type="OBJECT" id="dimension" selected="true" />
<filter-element type="OBJECT" id="cluster" selected="true" />
<filter-element type="OBJECT" id="dblink" selected="true" />
</public-schema>
<any-schema>
<filter-element type="OBJECT" id="table" selected="true" />
<filter-element type="OBJECT" id="view" selected="true" />
<filter-element type="OBJECT" id="materialized view" selected="true" />
<filter-element type="OBJECT" id="index" selected="true" />
<filter-element type="OBJECT" id="constraint" selected="true" />
<filter-element type="OBJECT" id="trigger" selected="true" />
<filter-element type="OBJECT" id="synonym" selected="true" />
<filter-element type="OBJECT" id="sequence" selected="true" />
<filter-element type="OBJECT" id="procedure" selected="true" />
<filter-element type="OBJECT" id="function" selected="true" />
<filter-element type="OBJECT" id="package" selected="true" />
<filter-element type="OBJECT" id="type" selected="true" />
<filter-element type="OBJECT" id="dimension" selected="true" />
<filter-element type="OBJECT" id="cluster" selected="true" />
<filter-element type="OBJECT" id="dblink" selected="true" />
</any-schema>
</extended-filter>
</filters>
<sorting enabled="true">
<sorting-element type="RESERVED_WORD" id="keyword" />
<sorting-element type="RESERVED_WORD" id="datatype" />
<sorting-element type="OBJECT" id="column" />
<sorting-element type="OBJECT" id="table" />
<sorting-element type="OBJECT" id="view" />
<sorting-element type="OBJECT" id="materialized view" />
<sorting-element type="OBJECT" id="index" />
<sorting-element type="OBJECT" id="constraint" />
<sorting-element type="OBJECT" id="trigger" />
<sorting-element type="OBJECT" id="synonym" />
<sorting-element type="OBJECT" id="sequence" />
<sorting-element type="OBJECT" id="procedure" />
<sorting-element type="OBJECT" id="function" />
<sorting-element type="OBJECT" id="package" />
<sorting-element type="OBJECT" id="type" />
<sorting-element type="OBJECT" id="dimension" />
<sorting-element type="OBJECT" id="cluster" />
<sorting-element type="OBJECT" id="dblink" />
<sorting-element type="OBJECT" id="schema" />
<sorting-element type="OBJECT" id="role" />
<sorting-element type="OBJECT" id="user" />
<sorting-element type="RESERVED_WORD" id="function" />
<sorting-element type="RESERVED_WORD" id="parameter" />
</sorting>
<format>
<enforce-code-style-case value="true" />
</format>
</code-completion-settings>
<execution-engine-settings>
<statement-execution>
<fetch-block-size value="100" />
<execution-timeout value="20" />
<debug-execution-timeout value="600" />
<focus-result value="false" />
<prompt-execution value="false" />
</statement-execution>
<script-execution>
<command-line-interfaces />
<execution-timeout value="300" />
</script-execution>
<method-execution>
<execution-timeout value="30" />
<debug-execution-timeout value="600" />
<parameter-history-size value="10" />
</method-execution>
</execution-engine-settings>
<operation-settings>
<transactions>
<uncommitted-changes>
<on-project-close value="ASK" />
<on-disconnect value="ASK" />
<on-autocommit-toggle value="ASK" />
</uncommitted-changes>
<multiple-uncommitted-changes>
<on-commit value="ASK" />
<on-rollback value="ASK" />
</multiple-uncommitted-changes>
</transactions>
<session-browser>
<disconnect-session value="ASK" />
<kill-session value="ASK" />
<reload-on-filter-change value="false" />
</session-browser>
<compiler>
<compile-type value="KEEP" />
<compile-dependencies value="ASK" />
<always-show-controls value="false" />
</compiler>
<debugger>
<debugger-type value="JDBC" />
</debugger>
</operation-settings>
<ddl-file-settings>
<extensions>
<mapping file-type-id="VIEW" extensions="vw" />
<mapping file-type-id="TRIGGER" extensions="trg" />
<mapping file-type-id="PROCEDURE" extensions="prc" />
<mapping file-type-id="FUNCTION" extensions="fnc" />
<mapping file-type-id="PACKAGE" extensions="pkg" />
<mapping file-type-id="PACKAGE_SPEC" extensions="pks" />
<mapping file-type-id="PACKAGE_BODY" extensions="pkb" />
<mapping file-type-id="TYPE" extensions="tpe" />
<mapping file-type-id="TYPE_SPEC" extensions="tps" />
<mapping file-type-id="TYPE_BODY" extensions="tpb" />
</extensions>
<general>
<lookup-ddl-files value="true" />
<create-ddl-files value="false" />
<synchronize-ddl-files value="true" />
<use-qualified-names value="false" />
<make-scripts-rerunnable value="true" />
</general>
</ddl-file-settings>
<general-settings>
<regional-settings>
<date-format value="MEDIUM" />
<number-format value="UNGROUPED" />
<locale value="SYSTEM_DEFAULT" />
<use-custom-formats value="false" />
</regional-settings>
<environment>
<environment-types>
<environment-type id="development" name="Development" description="Development environment" color="-2430209/-12296320" readonly-code="false" readonly-data="false" />
<environment-type id="integration" name="Integration" description="Integration environment" color="-2621494/-12163514" readonly-code="true" readonly-data="false" />
<environment-type id="production" name="Production" description="Productive environment" color="-11574/-10271420" readonly-code="true" readonly-data="true" />
<environment-type id="other" name="Other" description="" color="-1576/-10724543" readonly-code="false" readonly-data="false" />
</environment-types>
<visibility-settings>
<connection-tabs value="true" />
<dialog-headers value="true" />
<object-editor-tabs value="true" />
<script-editor-tabs value="false" />
<execution-result-tabs value="true" />
</visibility-settings>
</environment>
</general-settings>
</component>
</project>

@ -0,0 +1,12 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyArgumentEqualDefaultInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
<inspection_tool class="PyAugmentAssignmentInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
<inspection_tool class="PyClassicStyleClassInspection" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="PyCompatibilityInspection" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="PyMandatoryEncodingInspection" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="PyMissingOrEmptyDocstringInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
<inspection_tool class="PyMissingTypeHintsInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
</profile>
</component>

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/AuxiliaryPlay.iml" filepath="$PROJECT_DIR$/.idea/AuxiliaryPlay.iml" />
</modules>
</component>
</project>

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

@ -29,10 +29,16 @@
</filter>
</filter-actions>
</component>
<component name="DBNavigator.Project.ExecutionManager">
<retain-sticky-names value="false" />
</component>
<component name="DBNavigator.Project.ObjectQuickFilterManager">
<last-used-operator value="EQUAL" />
<filters />
</component>
<component name="DBNavigator.Project.ParserDiagnosticsManager">
<diagnostics-history />
</component>
<component name="DBNavigator.Project.Settings">
<connections>
<connection id="08cdce82-e17c-4657-88fb-4d2ee5b7f6be" active="true" signed="true">

@ -1,968 +0,0 @@
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from sensor_msgs.msg import LaserScan
import tf_transformations
import threading
import numpy as np
import os
from configparser import ConfigParser
import pygame
class Drive(object):
def __init__(self) -> None:
self.valueinit()
self.ros_register()
def valueinit(self):
if os.path.exists('config.ini'):
config = ConfigParser()
with open('config.ini') as f:
config.read_file(f)
self.threshold_l = float(config.get('threshold', 'threshold_l'))
self.threshold_lf = float(config.get('threshold', 'threshold_lf'))
self.threshold_f = float(config.get('threshold', 'threshold_f'))
self.threshold_rf = float(config.get('threshold', 'threshold_rf'))
self.threshold_r = float(config.get('threshold', 'threshold_r'))
self.fyaw = float(config.get('threshold', 'fyaw'))
self.ryaw = float(config.get('threshold', 'ryaw'))
self.byaw = float(config.get('threshold', 'byaw'))
self.lyaw0 = float(config.get('threshold', 'lyaw0'))
self.lyaw1 = float(config.get('threshold', 'lyaw1'))
self.blocksize = float(config.get('threshold', 'blocksize'))
self.kp = float(config.get('threshold', 'kp'))
self.speed_x = float(config.get('threshold', 'speed_x'))
self.speed_z = float(config.get('threshold', 'speed_z'))
else:
self.threshold_l = 0.085
self.threshold_lf = 0.12
self.threshold_f = 0.078
self.threshold_rf = 0.12
self.threshold_r = 0.085
self.fyaw = 4.71
self.ryaw = 3.14
self.byaw = 1.57
self.lyaw0 = 0
self.lyaw1 = 6.28
self.blocksize = 0.17
self.kp = 10
self.speed_x = 0.10
self.speed_z = 0.35
self.yaw = 0
self.l_dis = 0
self.fl_dis = 0
self.f_dis = 0
self.fr_dis = 0
self.r_dis = 0
self.position_x = 0
self.position_y = 0
def ros_register(self):
self.msg = Twist()
self.string = String()
self.node = Node('mynode')
self.node.create_subscription(LaserScan, '/scan', self.laser, 10)
self.node.create_subscription(Odometry, '/odom', self.odom, 10)
self.pub = self.node.create_publisher(Twist, '/cmd_vel', 10)
self.pub_custom = self.node.create_publisher(String, '/mycustom', 10)
# self.timer = self.node.create_timer(0.05, self.ros_pub)
self.rate = self.node.create_rate(50.0)
def ros_pub(self):
self.msg.linear.x = self.speed_x
self.msg.angular.z = self.speed_z
self.pub.publish(self.msg)
def ros_spin(self):
rclpy.spin(self.node)
def laser(self, msg):
region = msg.ranges
self.l_dis = region[340]
self.fl_dis = region[270]
self.f_dis = region[180]
self.fr_dis = region[90]
self.r_dis = region[20]
def get_laser(self):
return self.l_dis, self.fl_dis, self.f_dis, self.fr_dis, self.r_dis
def odom(self, msg):
position = msg.pose.pose.position
self.position_x = position.x
self.position_y = position.y
quaternion = (
msg.pose.pose.orientation.x,
msg.pose.pose.orientation.y,
msg.pose.pose.orientation.z,
msg.pose.pose.orientation.w)
euler = tf_transformations.euler_from_quaternion(quaternion)
self.yaw = euler[2] + 3.1415926
def get_odom(self):
return self.position_x, self.position_y, self.yaw
def posture_adjust(self):
fl_dis = self.fl_dis
fr_dis = self.fr_dis
l_dis = self.l_dis
r_dis = self.r_dis
if self.f_dis > 0.09:
if fl_dis < 0.118:
speed_z_temp = 0.5 * (fl_dis - 0.118) * self.kp
elif fr_dis < 0.118:
speed_z_temp = -0.5 * (fr_dis - 0.118) * self.kp
else:
speed_z_temp = 0.0
else:
if l_dis < 0.085:
speed_z_temp = 0.5 * (l_dis - 0.085) * self.kp
elif r_dis < 0.085:
speed_z_temp = -0.5 * (r_dis - 0.085) * self.kp
else:
speed_z_temp = 0.0
return speed_z_temp
def move(self, numblock=1):
flag = 1
flag_cps = 0
compensate = 0
while rclpy.ok():
self.msg.linear.x = self.speed_x
self.msg.angular.z = self.posture_adjust()
self.pub.publish(self.msg)
self.rate.sleep()
if flag:
tempx, tempy, tempz = self.get_odom()
if (not tempx) and (not tempy):
continue
flag = 0
if self.l_dis < 0.1 and self.r_dis < 0.1:
flag_cps = 0
elif self.l_dis < 0.1 and self.r_dis > 0.1:
flag_cps = 1
if self.l_dis > 0.1 and self.r_dis < 0.1:
flag_cps = 2
elif self.l_dis > 0.1 and self.r_dis > 0.1:
flag_cps = 3
if 0.01 < self.f_dis < 0.075:
self.msg.linear.x = 0.0
self.msg.angular.z = 0.0
self.pub.publish(self.msg)
# rclpy.spin_once(self.node)
self.rate.sleep()
break
if abs(self.get_odom()[0] - tempx) >= self.blocksize * numblock or abs(
self.get_odom()[1] - tempy) >= self.blocksize * numblock:
self.msg.linear.x = 0.0
self.msg.angular.z = 0.0
self.pub.publish(self.msg)
# rclpy.spin_once(self.node)
self.rate.sleep()
break
if flag_cps == 0 and (self.l_dis > 0.1 or self.r_dis > 0.1):
flag = 1
compensate = 1
break
"""
# 其他情况,暂时没想好怎么处理,所以注释掉
if flag_cps ==1 and self.l_dis>0.1:
flag = 1
compensate = 0
break
if flag_cps ==2 and self.r_dis>0.1:
flag = 1
compensate = 0
break
"""
while compensate and rclpy.ok():
self.msg.linear.x = self.speed_x
self.msg.angular.z = self.posture_adjust()
self.pub.publish(self.msg)
self.rate.sleep()
if flag:
tempx, tempy, tempz = self.get_odom()
if (not tempx) and (not tempy):
continue
flag = 0
if 0.01 < self.f_dis < 0.075:
self.msg.linear.x = 0.0
self.msg.angular.z = 0.0
self.pub.publish(self.msg)
# rclpy.spin_once(self.node)
self.rate.sleep()
break
if abs(self.get_odom()[0] - tempx) >= self.blocksize / 2 + 0.01 or abs(
self.get_odom()[1] - tempy) >= self.blocksize / 2 + 0.01:
self.msg.linear.x = 0.0
self.msg.angular.z = 0.0
self.pub.publish(self.msg)
# rclpy.spin_once(self.node)
self.rate.sleep()
break
def turn(self, angle):
while rclpy.ok():
self.msg.linear.x = 0.0
self.msg.angular.z = -self.speed_z
self.pub.publish(self.msg)
self.rate.sleep()
if angle - 0.1 < self.yaw < angle + 0.1:
self.msg.linear.x = 0.0
self.msg.angular.z = 0.0
self.pub.publish(self.msg)
# rclpy.spin_once(self.node)
self.rate.sleep()
break
def turnright(self):
flag = 1
while rclpy.ok():
self.msg.linear.x = 0.0
self.msg.angular.z = -self.speed_z
self.pub.publish(self.msg)
self.rate.sleep()
if flag: # It is similar with move.
oldyaw = self.get_odom()[2]
if not oldyaw:
continue
flag = 0
# Considering the mutation of 0 and 6.28, so dividing the whole process into four parts.
if 4.41 < oldyaw < 5.01: # up
if self.ryaw - 0.1 < self.yaw < self.ryaw + 0.1:
self.msg.linear.x = 0.0
self.msg.angular.z = 0.0
self.pub.publish(self.msg)
# rclpy.spin_once(self.node)
self.rate.sleep()
break
elif 2.84 < oldyaw < 3.44: # right
if self.byaw - 0.1 < self.yaw < self.byaw + 0.1:
self.msg.linear.x = 0.0
self.msg.angular.z = 0.0
self.pub.publish(self.msg)
# rclpy.spin_once(self.node)
self.rate.sleep()
break
elif 1.27 < oldyaw < 1.87: # back
if self.yaw < self.lyaw0 + 0.1:
self.msg.linear.x = 0.0
self.msg.angular.z = 0.0
self.pub.publish(self.msg)
# rclpy.spin_once(self.node)
self.rate.sleep()
break
elif oldyaw < 0.3 or oldyaw > 5.98: # left
if self.fyaw - 0.1 < self.yaw < self.fyaw + 0.1:
self.msg.linear.x = 0.0
self.msg.angular.z = 0.0
self.pub.publish(self.msg)
# rclpy.spin_once(self.node)
self.rate.sleep()
break
def turnleft(self):
flag = 1
while rclpy.ok():
self.msg.linear.x = 0.0
self.msg.angular.z = self.speed_z
self.pub.publish(self.msg)
self.rate.sleep()
if flag:
oldyaw = self.yaw
if not oldyaw:
continue
flag = 0
if 4.41 < oldyaw < 5.01: # up
if self.yaw > self.lyaw1 - 0.1:
self.msg.linear.x = 0.0
self.msg.angular.z = 0.0
self.pub.publish(self.msg)
# rclpy.spin_once(self.node)
self.rate.sleep()
print(1111)
break
elif 2.84 < oldyaw < 3.44: # right
if self.fyaw - 0.1 < self.yaw < self.fyaw + 0.1:
self.msg.linear.x = 0.0
self.msg.angular.z = 0.0
self.pub.publish(self.msg)
# rclpy.spin_once(self.node)
self.rate.sleep()
print(222)
break
elif 1.27 < oldyaw < 1.87: # back
if self.ryaw - 0.1 < self.yaw < self.ryaw + 0.1:
self.msg.linear.x = 0.0
self.msg.angular.z = 0.0
self.pub.publish(self.msg)
# rclpy.spin_once(self.node)
self.rate.sleep()
print(44444)
break
elif oldyaw < 0.3 or oldyaw > 5.98: # left
if self.byaw - 0.1 < self.yaw < self.byaw + 0.1:
self.msg.linear.x = 0.0
self.msg.angular.z = 0.0
self.pub.publish(self.msg)
# rclpy.spin_once(self.node)
self.rate.sleep()
print(155555)
break
def turnback(self):
flag = 1
while rclpy.ok():
self.msg.linear.x = 0.0
self.msg.angular.z = -self.speed_z
self.pub.publish(self.msg)
self.rate.sleep()
if flag:
oldyaw = self.get_odom()[2]
if not oldyaw:
continue
flag = 0
if 4.41 < oldyaw < 5.01: # up
if self.byaw - 0.1 < self.yaw < self.byaw + 0.1:
self.msg.linear.x = 0.0
self.msg.angular.z = 0.0
self.pub.publish(self.msg)
# rclpy.spin_once(self.node)
self.rate.sleep()
break
elif 2.84 < oldyaw < 3.44: # right
if self.yaw < self.lyaw0 + 0.1:
self.msg.linear.x = 0.0
self.msg.angular.z = 0.0
self.pub.publish(self.msg)
# rclpy.spin_once(self.node)
self.rate.sleep()
break
elif 1.27 < oldyaw < 1.87: # back
if self.fyaw - 0.1 < self.yaw < self.fyaw + 0.1:
self.msg.linear.x = 0.0
self.msg.angular.z = 0.0
self.pub.publish(self.msg)
# rclpy.spin_once(self.node)
self.rate.sleep()
break
elif oldyaw < 0.3 or oldyaw > 5.98: # left
if self.ryaw - 0.1 < self.yaw < self.ryaw + 0.1:
self.msg.linear.x = 0.0
self.msg.angular.z = 0.0
self.pub.publish(self.msg)
# rclpy.spin_once(self.node)
self.rate.sleep()
break
class Micromouse(Drive):
def __init__(self):
"""继承父类,禁止删减,但可以增加自己要添加的内容。"""
super().__init__()
self.valuesinit()
def valuesinit(self):
"""Micromosue参数初始化, 禁止修改"""
self.mapblock = np.full((16, 16), '00000') # 2D array,墙壁资料初始化, flag left down right up
# flag: 是否走过, 0 or 1
# left: 是否有路, 0 or 1
# down: 是否有路, 0 or 1
# right: 是否有路, 0 or 1
# up: 是否有路, 0 or 1
self.mapblock[0, 0] = '10001' # 起点墙壁初始化
self.crosswaystack = []
self.mouse_x = 0 # x,y起点坐标这是在迷宫中的坐标
self.mouse_y = 0
self.dir = 0 # Micromouse车头,0:up, 1:right, 2:down, 3:left
def __coordinateupdate(self):
"""根据车头方向更新坐标, 禁止修改"""
if self.dir == 0: # 车头向上
self.mouse_y += 1
elif self.dir == 1: # 车头向右
self.mouse_x += 1
elif self.dir == 2: # 车头向下
self.mouse_y -= 1
elif self.dir == 3: # 车头向左
self.mouse_x -= 1
def get_coordinate(self):
"""获取坐标,方便调用,禁止修改"""
return self.mouse_x, self.mouse_y
def __savewallinfo(self):
"""墙壁信息保存, 禁止修改"""
frontpath = '1' if self.f_dis > 0.2 else '0'
rightpath = '1' if self.r_dis > 0.2 else '0'
backpath = '1'
leftpath = '1' if self.l_dis > 0.2 else '0'
# 墙壁资料赋值
if self.dir == 0:
self.mapblock[self.mouse_x, self.mouse_y] = ''.join(('1', leftpath, backpath, rightpath, frontpath))
elif self.dir == 1:
self.mapblock[self.mouse_x, self.mouse_y] = ''.join(('1', backpath, rightpath, frontpath, leftpath))
elif self.dir == 2:
self.mapblock[self.mouse_x, self.mouse_y] = ''.join(('1', rightpath, frontpath, leftpath, backpath))
elif self.dir == 3:
self.mapblock[self.mouse_x, self.mouse_y] = ''.join(('1', frontpath, leftpath, backpath, rightpath))
def turnright(self):
"""右转弯,加入了方向转换, 禁止修改"""
self.dir = (self.dir + 1) % 4
return super(Micromouse, self).turnright()
def turnleft(self):
"""左转弯,加入了方向转换, 禁止修改"""
self.dir = (self.dir + 3) % 4
return super(Micromouse, self).turnleft()
def turnback(self):
"""向后转弯,加入了方向转换, 禁止修改"""
self.dir = (self.dir + 2) % 4
return super(Micromouse, self).turnback()
def moveoneblock(self):
"""移动一个单元格,然后更新坐标,保存墙壁信息的功能, 禁止修改"""
self.move()
self.__coordinateupdate()
if self.mapblock[self.mouse_x, self.mouse_y][0] == '0':
self.__savewallinfo()
self.ros_pub_custom()
def ros_pub_custom(self):
data = ''.join((str(self.mouse_x), ',',
str(self.mouse_y), ',',
str(self.dir), ',',
self.mapblock[self.mouse_x, self.mouse_y][1:]
))
self.string.data = data
self.pub_custom.publish(self.string)
def rightmethod(self):
frontpath = '1' if self.f_dis > 0.2 else '0'
rightpath = '1' if self.r_dis > 0.2 else '0'
backpath = '1'
leftpath = '1' if self.l_dis > 0.2 else '0'
if rightpath == '1': # 右侧有路
if self.dir == 0:
flag = self.mapblock[self.mouse_x + 1, self.mouse_y][0]
elif self.dir == 1:
flag = self.mapblock[self.mouse_x, self.mouse_y - 1][0]
elif self.dir == 2:
flag = self.mapblock[self.mouse_x - 1, self.mouse_y][0]
elif self.dir == 3:
flag = self.mapblock[self.mouse_x, self.mouse_y + 1][0]
if flag == '0':
self.turnright()
return
if frontpath == '1': # 前方有路
if self.dir == 0:
flag = self.mapblock[self.mouse_x, self.mouse_y + 1][0]
elif self.dir == 1:
flag = self.mapblock[self.mouse_x + 1, self.mouse_y][0]
elif self.dir == 2:
flag = self.mapblock[self.mouse_x, self.mouse_y - 1][0]
elif self.dir == 3:
flag = self.mapblock[self.mouse_x - 1, self.mouse_y][0]
if flag == '0':
return
if leftpath == '1': # 左侧有路
if self.dir == 0:
flag = self.mapblock[self.mouse_x - 1, self.mouse_y][0]
elif self.dir == 1:
flag = self.mapblock[self.mouse_x, self.mouse_y + 1][0]
elif self.dir == 2:
flag = self.mapblock[self.mouse_x + 1, self.mouse_y][0]
elif self.dir == 3:
flag = self.mapblock[self.mouse_x, self.mouse_y - 1][0]
if flag == '0':
self.turnleft()
return
def leftmethod(self):
frontpath = '1' if self.f_dis > 0.2 else '0'
rightpath = '1' if self.r_dis > 0.2 else '0'
backpath = '1'
leftpath = '1' if self.l_dis > 0.2 else '0'
if leftpath == '1': # 左侧有路
if self.dir == 0:
flag = self.mapblock[self.mouse_x - 1, self.mouse_y][0]
elif self.dir == 1:
flag = self.mapblock[self.mouse_x, self.mouse_y + 1][0]
elif self.dir == 2:
flag = self.mapblock[self.mouse_x + 1, self.mouse_y][0]
elif self.dir == 3:
flag = self.mapblock[self.mouse_x, self.mouse_y - 1][0]
if flag == '0':
self.turnleft()
return
if frontpath == '1': # 前方有路
if self.dir == 0:
flag = self.mapblock[self.mouse_x, self.mouse_y + 1][0]
elif self.dir == 1:
flag = self.mapblock[self.mouse_x + 1, self.mouse_y][0]
elif self.dir == 2:
flag = self.mapblock[self.mouse_x, self.mouse_y - 1][0]
elif self.dir == 3:
flag = self.mapblock[self.mouse_x - 1, self.mouse_y][0]
if flag == '0':
return
if rightpath == '1': # 右侧有路
if self.dir == 0:
flag = self.mapblock[self.mouse_x + 1, self.mouse_y][0]
elif self.dir == 1:
flag = self.mapblock[self.mouse_x, self.mouse_y - 1][0]
elif self.dir == 2:
flag = self.mapblock[self.mouse_x - 1, self.mouse_y][0]
elif self.dir == 3:
flag = self.mapblock[self.mouse_x, self.mouse_y + 1][0]
if flag == '0':
self.turnright()
return
def frontrightmethod(self):
frontpath = '1' if self.f_dis > 0.2 else '0'
rightpath = '1' if self.r_dis > 0.2 else '0'
backpath = '1'
leftpath = '1' if self.l_dis > 0.2 else '0'
if frontpath == '1': # 前方有路
if self.dir == 0:
flag = self.mapblock[self.mouse_x, self.mouse_y + 1][0]
elif self.dir == 1:
flag = self.mapblock[self.mouse_x + 1, self.mouse_y][0]
elif self.dir == 2:
flag = self.mapblock[self.mouse_x, self.mouse_y - 1][0]
elif self.dir == 3:
flag = self.mapblock[self.mouse_x - 1, self.mouse_y][0]
if flag == '0':
return
if rightpath == '1': # 右侧有路
if self.dir == 0:
flag = self.mapblock[self.mouse_x + 1, self.mouse_y][0]
elif self.dir == 1:
flag = self.mapblock[self.mouse_x, self.mouse_y - 1][0]
elif self.dir == 2:
flag = self.mapblock[self.mouse_x - 1, self.mouse_y][0]
elif self.dir == 3:
flag = self.mapblock[self.mouse_x, self.mouse_y + 1][0]
if flag == '0':
self.turnright()
return
if leftpath == '1': # 左侧有路
if self.dir == 0:
flag = self.mapblock[self.mouse_x - 1, self.mouse_y][0]
elif self.dir == 1:
flag = self.mapblock[self.mouse_x, self.mouse_y + 1][0]
elif self.dir == 2:
flag = self.mapblock[self.mouse_x + 1, self.mouse_y][0]
elif self.dir == 3:
flag = self.mapblock[self.mouse_x, self.mouse_y - 1][0]
if flag == '0':
self.turnleft()
return
def frontleftmethod(self):
frontpath = '1' if self.f_dis > 0.2 else '0'
rightpath = '1' if self.r_dis > 0.2 else '0'
backpath = '1'
leftpath = '1' if self.l_dis > 0.2 else '0'
if frontpath == '1': # 前方有路
if self.dir == 0:
flag = self.mapblock[self.mouse_x, self.mouse_y + 1][0]
elif self.dir == 1:
flag = self.mapblock[self.mouse_x + 1, self.mouse_y][0]
elif self.dir == 2:
flag = self.mapblock[self.mouse_x, self.mouse_y - 1][0]
elif self.dir == 3:
flag = self.mapblock[self.mouse_x - 1, self.mouse_y][0]
if flag == '0':
return
if leftpath == '1': # 左侧有路
if self.dir == 0:
flag = self.mapblock[self.mouse_x - 1, self.mouse_y][0]
elif self.dir == 1:
flag = self.mapblock[self.mouse_x, self.mouse_y + 1][0]
elif self.dir == 2:
flag = self.mapblock[self.mouse_x + 1, self.mouse_y][0]
elif self.dir == 3:
flag = self.mapblock[self.mouse_x, self.mouse_y - 1][0]
if flag == '0':
self.turnleft()
return
if rightpath == '1': # 右侧有路
if self.dir == 0:
flag = self.mapblock[self.mouse_x + 1, self.mouse_y][0]
elif self.dir == 1:
flag = self.mapblock[self.mouse_x, self.mouse_y - 1][0]
elif self.dir == 2:
flag = self.mapblock[self.mouse_x - 1, self.mouse_y][0]
elif self.dir == 3:
flag = self.mapblock[self.mouse_x, self.mouse_y + 1][0]
if flag == '0':
self.turnright()
return
def centralmethod(self):
if self.mouse_x < 8:
if self.mouse_y < 8: # Micromouse位于左下角
if self.dir == 0:
self.frontrightmethod()
elif self.dir == 1:
self.frontleftmethod()
elif self.dir == 2:
self.leftmethod()
elif self.dir == 3:
self.rightmethod()
else: # Micromouse位于左上角
if self.dir == 0:
self.rightmethod()
elif self.dir == 1:
self.frontrightmethod()
elif self.dir == 2:
self.frontleftmethod()
elif self.dir == 3:
self.leftmethod()
else:
if self.mouse_y < 8: # Micromouse位于右下角
if self.dir == 0:
self.frontleftmethod()
elif self.dir == 1:
self.leftmethod()
elif self.dir == 2:
self.rightmethod()
elif self.dir == 3:
self.frontrightmethod()
else: # Micromouse位于右下角
if self.dir == 0:
self.leftmethod()
elif self.dir == 1:
self.rightmethod()
elif self.dir == 2:
self.frontrightmethod()
elif self.dir == 3:
self.frontleftmethod()
def centralmethod2(self):
if self.mouse_x in (7, 8) or self.mouse_y in (7, 8):
if self.mouse_y in (7, 8):
if self.mouse_x < 8:
if self.dir == 0:
self.rightmethod()
elif self.dir == 1:
self.frontrightmethod()
elif self.dir == 2:
self.leftmethod()
elif self.dir == 3:
self.frontrightmethod()
else:
if self.dir == 0:
self.leftmethod()
elif self.dir == 1:
self.frontrightmethod()
elif self.dir == 2:
self.rightmethod()
elif self.dir == 3:
self.frontrightmethod()
if self.mouse_x in (7, 8):
if self.mouse_y < 8:
if self.dir == 0:
self.frontrightmethod()
elif self.dir == 1:
self.leftmethod()
elif self.dir == 2:
self.frontrightmethod()
elif self.dir == 3:
self.rightmethod()
else:
if self.dir == 0:
self.frontrightmethod()
elif self.dir == 1:
self.rightmethod()
elif self.dir == 2:
self.frontrightmethod()
elif self.dir == 3:
self.leftmethod()
elif self.mouse_x < 8:
if self.mouse_y < 8: # Micromouse位于左下角
if self.dir == 0:
self.frontrightmethod()
elif self.dir == 1:
self.frontleftmethod()
elif self.dir == 2:
self.leftmethod()
elif self.dir == 3:
self.rightmethod()
else: # Micromouse位于左上角
if self.dir == 0:
self.rightmethod()
elif self.dir == 1:
self.frontrightmethod()
elif self.dir == 2:
self.frontleftmethod()
elif self.dir == 3:
self.leftmethod()
else:
if self.mouse_y < 8: # Micromouse位于右下角
if self.dir == 0:
self.frontleftmethod()
elif self.dir == 1:
self.leftmethod()
elif self.dir == 2:
self.rightmethod()
elif self.dir == 3:
self.frontrightmethod()
else: # Micromouse位于右下角
if self.dir == 0:
self.leftmethod()
elif self.dir == 1:
self.rightmethod()
elif self.dir == 2:
self.frontrightmethod()
elif self.dir == 3:
self.frontleftmethod()
def destinationcheck(self):
if (self.mouse_x == 7 and self.mouse_y == 7) or (self.mouse_x == 7 and self.mouse_y == 8) or (
self.mouse_x == 8 and self.mouse_y == 7) or (self.mouse_x == 8 and self.mouse_y == 8):
return True
else:
return False
def crosswaychoice(self):
self.centralmethod()
def mapstepedit(self, dx, dy):
"""制作等高图, 禁止修改"""
self.mapstep = np.full((16, 16), 255)
step = 1
n = 1
stack = []
stack.append((dx, dy))
cx = dx
cy = dy
while n:
self.mapstep[cx, cy] = step
step += 1
count = 0
# 统计当前坐标有几个可前进的方向
if (self.mapblock[cx, cy][-1] == '1') and (self.mapstep[cx, cy + 1] > step):
count += 1
if (self.mapblock[cx, cy][-2] == '1') and (self.mapstep[cx + 1, cy] > step):
count += 1
if (self.mapblock[cx, cy][-3] == '1') and (self.mapstep[cx, cy - 1] > step):
count += 1
if (self.mapblock[cx, cy][-4] == '1') and (self.mapstep[cx - 1, cy] > step):
count += 1
if count == 0:
cx, cy = stack.pop()
step = self.mapstep[cx, cy]
n -= 1
else:
if count > 1:
stack.append((cx, cy))
n += 1
# 随便挑一个方向,不影响结果,因为会全部走一遍
if (self.mapblock[cx, cy][-1] == '1') and (self.mapstep[cx, cy + 1] > step):
cy += 1
continue
if (self.mapblock[cx, cy][-2] == '1') and (self.mapstep[cx + 1, cy] > step):
cx += 1
continue
if (self.mapblock[cx, cy][-3] == '1') and (self.mapstep[cx, cy - 1] > step):
cy -= 1
continue
if (self.mapblock[cx, cy][-4] == '1') and (self.mapstep[cx - 1, cy] > step):
cx -= 1
continue
def objectgoto(self, dx, dy):
"""向目标点运动, 禁止修改"""
self.mapstepedit(dx, dy)
temp_dir = 0
cx = self.mouse_x
cy = self.mouse_y
while (cx != dx) or (cy != dy):
# 沿着等高值减小的方向运行,直至到达目标点
step = self.mapstep[cx, cy]
if (self.mapblock[cx, cy][-1] == '1') and (self.mapstep[cx, cy + 1] < step):
temp_dir = 0
elif (self.mapblock[cx, cy][-2] == '1') and (self.mapstep[cx + 1, cy] < step):
temp_dir = 1
elif (self.mapblock[cx, cy][-3] == '1') and (self.mapstep[cx, cy - 1] < step):
temp_dir = 2
elif (self.mapblock[cx, cy][-4] == '1') and (self.mapstep[cx - 1, cy] < step):
temp_dir = 3
d_dir = (temp_dir - self.dir + 4) % 4
if d_dir == 1:
self.turnright()
elif d_dir == 2:
self.turnback()
elif d_dir == 3:
self.turnleft()
self.moveoneblock()
cx = self.mouse_x
cy = self.mouse_y
def crosswaycheck(self):
temp = 0
left, down, right, up = self.mapblock[self.mouse_x, self.mouse_y][1:]
if up == '1':
if self.mapblock[self.mouse_x, self.mouse_y + 1][0] == '0':
temp += 1
if right == '1':
if self.mapblock[self.mouse_x + 1, self.mouse_y][0] == '0':
temp += 1
if down == '1':
if self.mapblock[self.mouse_x, self.mouse_y - 1][0] == '0':
temp += 1
if left == '1':
if self.mapblock[self.mouse_x - 1, self.mouse_y][0] == '0':
temp += 1
return temp
def mazesearch(self):
while 1:
# print(self.mouse_x, self.mouse_y)
if self.destinationcheck(): # 如果到了终点,则返回起点
destination = (self.mouse_x, self.mouse_y)
self.turnback()
self.objectgoto(0, 0)
return (1, destination)
else: # 否则一直搜索
crosswaycount = self.crosswaycheck()
if crosswaycount:
if crosswaycount > 1:
self.crosswaystack.append((self.mouse_x, self.mouse_y))
self.crosswaychoice()
self.moveoneblock()
if crosswaycount == 1:
self.crosswaychoice()
self.moveoneblock()
else:
self.turnback()
self.objectgoto(*self.crosswaystack.pop())
def spurt(self, dest):
self.objectgoto(*dest)
self.turnback()
self.objectgoto(0, 0)
def main():
rclpy.init(args=None)
micromouse = Micromouse()
t = threading.Thread(None, target=micromouse.ros_spin, daemon=True)
t.start()
flag, destination = micromouse.mazesearch()
micromouse.spurt(destination)
def main2():
""" remote control """
flag = -1
pygame.init()
if pygame.joystick.get_count():
stick = pygame.joystick.Joystick(0)
else:
print('No joystick found!!!')
rclpy.init(args=None)
micromouse = Micromouse()
t = threading.Thread(None, target=micromouse.ros_spin, daemon=True)
t.start()
while 1:
events = pygame.event.get()
if events:
for event in events:
if event.type == pygame.JOYBUTTONDOWN:
if event.button == 0:
flag = 0
print('go')
if event.button == 1:
flag = 1
print('turn right')
if event.button == 2:
flag = 2
print('turn back')
if event.button == 3:
flag = 3
print('turn left')
if event.button == 4:
flag = 66
print('go back')
if event.button == 5:
flag = 88
print('spurt')
if event.type == pygame.JOYBUTTONUP:
if event.button in (0, 1, 2, 3):
print('stop')
flag = -1
match flag:
case 0:
micromouse.moveoneblock()
case 1:
micromouse.turnright()
case 2:
micromouse.turnback()
case 3:
micromouse.turnleft()
case 66:
destination = (micromouse.mouse_x, micromouse.mouse_y)
micromouse.turnback()
micromouse.objectgoto(0, 0)
flag = -1
case 88:
print(destination)
micromouse.spurt(destination)
break
if __name__ == '__main__':
try:
main()
finally:
rclpy.shutdown()

@ -17,7 +17,7 @@ class RegPictrue(QThread):
def __init__(self, shotArea, window):
super(RegPictrue, self).__init__()
self.shotArea = shotArea
self.ocr = PaddleOCR(use_angle_cls=True, lang="ch") # 初始化OCR模型
self.ocr = PaddleOCR() # 初始化OCR模型
self.translate_window = window
self.isOpen = True
self.last_words = ''
@ -26,7 +26,7 @@ class RegPictrue(QThread):
while self.isOpen:
screenshot = p.screenshot(region=(self.shotArea['left'], self.shotArea['top'],
self.shotArea['width'], self.shotArea['height']))
screenshot_np = np.array(screenshot) # 将Pillow图像对象转换为np.ndarray类型
screenshot_np = np.array(screenshot.convert('RGB'))[:, :, ::-1] # 将Pillow图像对象转换为np.ndarray类型
result = self.ocr.ocr(screenshot_np, cls=False)
orgwords = ''
for idx in result:

@ -18,7 +18,7 @@ class SetShotArea():
self.capture = pyautogui.screenshot()
# 将截图转换为OpenCV格式
self.capture = np.array(self.capture)
self.capture = np.array(self.capture.convert('RGB'))[:, :, ::-1]
self.capture = cv2.cvtColor(self.capture, cv2.COLOR_RGB2BGR)
# 回调函数,用于处理鼠标事件

@ -1,22 +1,94 @@
import psycopg2
# 获得连接
gamerule = psycopg2.connect(database="gamerule", user="postgres", password="123456", host="localhost", port="5432")
# 获得游标对象
cursor = gamerule.cursor()
from psycopg2 import errors
sql = "SELECT * FROM table1;"
# 执行SQL查询
cursor.execute(sql)
# 获取查询结果
rows = cursor.fetchall()
class DatabaseHandler:
def __init__(self, database, user, password, host, port):
self.database = database
self.user = user
self.password = password
self.host = host
self.port = port
self.conn = None
self.cur = None
# 处理查询结果
for row in rows:
print(row)
def connect(self):
self.conn = psycopg2.connect(database=self.database,
user=self.user,
password=self.password,
host=self.host,
port=self.port)
self.cur = self.conn.cursor()
# conn.commit()
# 关闭数据库连接
gamerule.close()
def create_table(self, table_name):
self.cur.execute(
"SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name='" + table_name + "');")
table_exists = self.cur.fetchone()[0]
if table_exists:
print("表已存在")
else:
try:
self.cur.execute(f"CREATE SEQUENCE {table_name}_pid_seq START 1;")
self.cur.execute(
f"CREATE TABLE {table_name} (pid INTEGER DEFAULT nextval('{table_name}_pid_seq'), id INTEGER, path VARCHAR, xOffset INTEGER, yOffset INTEGER, pOffsetX INTEGER, pOffsetY INTEGER, time INTEGER, rgb VARCHAR);")
self.conn.commit()
print("操作成功")
except errors.DuplicateTable:
print("表已存在")
def insert_data(self, table_name, id, path, xOffset, yOffset, pOffsetX, pOffsetY, time, rgb):
try:
self.cur.execute(
f"INSERT INTO {table_name} (id, path, xOffset, yOffset, pOffsetX, pOffsetY, time, rgb) VALUES ({id}, '{path}', {xOffset}, {yOffset}, {pOffsetX}, {pOffsetY}, {time}, '{rgb}')")
self.conn.commit()
print("数据插入成功")
except errors.ForeignKeyViolation:
print("插入数据失败")
def execute_query(self, table_name):
self.cur.execute("SELECT * FROM " + table_name)
rows = self.cur.fetchall()
for row in rows:
print(row)
def close(self):
self.conn.close()
#
# # 示例用法
# db = DatabaseHandler(database='gamerule', user='postgres', password='123456', host='localhost', port='5432')
# db.connect()
# db.create_table('rule11')
# db.insert_data('rule11', 9, '../pictures/terminal_photo.png', 10, 20, 30, 40, 12345, '255,0,0')
# db.execute_query('rule11')
# db.close()
class DatabaseDatum:
def __init__(self, tablename=None, id=None, path=None, xOffset=None, yOffset=None, pOffsetX=None, pOffsetY=None,
time=None, rgb=None):
self.tablename = tablename
self.id = id
self.path = path
self.xOffset = xOffset
self.yOffset = yOffset
self.pOffsetX = pOffsetX
self.pOffsetY = pOffsetY
self.time = time
self.rgb = rgb
def get_path_by_pid(self, tablename, pid):
db = DatabaseHandler(database='gamerule', user='postgres', password='123456', host='localhost', port='5432')
db.connect()
query = f"SELECT path FROM {tablename} WHERE pid = {pid};"
db.cur.execute(query)
result = db.cur.fetchone()
db.close()
if result:
self.path = result[0]
else:
self.path = None
return self.path

@ -7,18 +7,78 @@ from windows.res.tools.deal_picture import DealPicture
class operation:
def click_once(photo):
@staticmethod
def mouse_to_lefttop():
p.moveTo(10, 10, duration=0.3)
@staticmethod
def click_position_once(position):
# 检查变量是否为元组
if isinstance(position, tuple):
# 将元组转换为字典
position_dict = {
'left': position[0],
'top': position[1],
'width': position[2],
'height': position[3]
}
else:
position_dict = position
x, y = (position_dict['left']+position_dict['width']/2), (position_dict['top']+position_dict['height']/2)
p.click(x, y)
time.sleep(0.1)
operation.mouse_to_lefttop()
@staticmethod
def click_position_util(position, stop_function):
count = 0
x, y = (position['left'] + position['width'] / 2), (position['top'] + position['height'] / 2)
p.click(x, y)
time.sleep(0.1)
operation.mouse_to_lefttop()
while stop_function() is False or stop_function() is None:
x, y = (position['left'] + position['width'] / 2), (position['top'] + position['height'] / 2)
p.click(x, y)
time.sleep(0.1)
count += 1
if count >= 6:
break
time.sleep(0.1)
@staticmethod
def click_once(photo, pOffsetX=None, pOffsetY=None):
poffsetx = 0
poffsety = 0
if pOffsetX:
poffsetx = pOffsetX
if pOffsetY:
poffsety = pOffsetY
positions = p.locateCenterOnScreen(photo, confidence=0.8)
x, y = positions.x, positions.y
x, y = positions.x + poffsetx, positions.y +poffsety
p.click(x, y)
time.sleep(0.1)
operation.mouse_to_lefttop()
def click_util(click_photo, stop_function):
@staticmethod
def click_util(click_photo, stop_function, pOffsetX=None, pOffsetY=None):
poffsetx = 0
poffsety = 0
if pOffsetX:
poffsetx = pOffsetX
if pOffsetY:
poffsety = pOffsetY
count = 0
while stop_function() is False:
positions = DealPicture.find_photo_center(click_photo)
if positions:
x, y = positions.x + poffsetx, positions.y + poffsety
p.click(x, y)
operation.mouse_to_lefttop()
while stop_function() is False or stop_function() is None:
positions = DealPicture.find_photo_center(click_photo)
if positions:
x, y = positions.x, positions.y
x, y = positions.x + poffsetx, positions.y + poffsety
p.click(x, y)
else:
count += 1
@ -26,6 +86,7 @@ class operation:
break
time.sleep(0.1)
@staticmethod
def drag_once(drop_position, xOffset=None, yOffset=None, pOffsetX=None, pOffsetY=None):
offsetx = 0
offsety = 0
@ -55,6 +116,7 @@ class operation:
p.mouseUp(x=x + poffsetx + offsetx, y=y + poffsety + offsety, button='left')
time.sleep(0.3)
@staticmethod
def drag_util(drop_position, stop_function, xOffset=None, yOffset=None, pOffsetX=None, pOffsetY=None):
count = 0
offsetx = 0

@ -0,0 +1,30 @@
class Priority:
dormitory_priority = {
'bad_mood': ['res/pictures/bad_mood.png', '5'],
'common_mood': ['res/pictures/common_mood.png', '4']
}
producing_experience_priority = {
'top_experience': ['res/pictures/experience_top.png', '5'],
'common_produce': ['res/pictures/common_produce.png', '4'],
'lower_common_produce': ['res/pictures/lower_common_produce.png', '3'],
'warehouse_produce': ['res/pictures/warehouse_produce.png', '2'],
'house_produce': ['res/pictures/house_produce.png', '1']
}
producing_material_priority = {
'material_top': ['res/pictures/material_top.png', '5'],
'common_produce': ['res/pictures/common_produce.png', '4'],
'lower_common_produce': ['res/pictures/lower_common_produce.png', '3'],
'warehouse_produce': ['res/pictures/warehouse_produce.png', '2'],
'house_produce': ['res/pictures/house_produce.png', '1']
}
trading_priority = {
'trade_top': ['res/pictures/trade_top.png', '5'],
'trade_lower': ['res/pictures/trade_lower.png', '4']
}
def print_trading_priority(self):
for key, value in Priority.trading_priority.items():
print(value[0])

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

@ -0,0 +1,56 @@
import time
import cv2
import pyautogui as p
from PyQt5.QtCore import QThread, pyqtSignal
from windows.entity.operations.operation import operation
from windows.res.tools.deal_picture import DealPicture
p.PAUSE = 0.1
p.FAILSAFE = True
def backToTerminal():
print("back to terminal")
positions = DealPicture.find_photo_center('res/pictures/terminal_photo.png', 2)
while positions is None:
click_photo = cv2.imread('res/pictures/back_btn.png')
back_confirm = cv2.imread('res/pictures/back_confirm.png')
if DealPicture.find_photo_center(click_photo, 1):
operation.click_once(click_photo)
else:
return False
if DealPicture.find_photo_center(back_confirm, 1):
operation.click_once(back_confirm)
else:
return False
positions = DealPicture.find_photo_center('res/pictures/terminal_photo.png')
print("find terminal")
return True
def enter_base():
print("enter the base")
click_photo = cv2.imread('res/pictures/base.png')
stop_photos = [cv2.imread('res/pictures/electricity.png'), cv2.imread('res/pictures/loading.png')]
name = 'base.png'
if DealPicture.find_photo_center(click_photo, 1):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photos))
else:
print("don't find picture", name)
return False
def deal_award():
print("acquire awards")
click_photo = cv2.imread('res/pictures/notice.png')
stop_photos = [cv2.imread('res/pictures/todo-things.png')]
name = 'notice.png'
if DealPicture.find_photo_center(click_photo, 2):
operation.click_util(click_photo, lambda: DealPicture.find_b_photos(stop_photos))
else:
print("don't find picture", name)
return False

@ -1,4 +1,4 @@
import os
import time
import cv2
@ -14,10 +14,10 @@ p.FAILSAFE = True
def backToTerminal():
print("back to terminal")
positions = DealPicture.find_photo_center('../pictures/terminal_photo.png', 2)
positions = DealPicture.find_photo_center('res/pictures/terminal_photo.png', 2)
while positions is None:
click_photo = cv2.imread('../pictures/back_btn.png')
back_confirm = cv2.imread('../pictures/back_confirm.png')
click_photo = cv2.imread('res/pictures/back_btn.png')
back_confirm = cv2.imread('res/pictures/back_confirm.png')
if DealPicture.find_photo_center(click_photo, 1):
operation.click_once(click_photo)
else:
@ -26,7 +26,7 @@ def backToTerminal():
operation.click_once(back_confirm)
else:
return False
positions = DealPicture.find_photo_center('../pictures/terminal_photo.png')
positions = DealPicture.find_photo_center('res/pictures/terminal_photo.png')
print("find terminal")
return True
@ -34,33 +34,33 @@ def backToTerminal():
def find_target_level():
print("finding level")
if DealPicture.find_photo_center('../pictures/cur_chapter1.png', 2):
if DealPicture.find_photo_center('res/pictures/cur_chapter1.png', 2):
print("on purpose chapter")
else:
return False
while (DealPicture.find_photo_center(
'../pictures/level_1-1.png', 1, 0.9) is None
'res/pictures/level_1-1.png', 1, 0.9) is None
and
DealPicture.find_photo_center('../pictures/level_1-7.png', 1, 0.9) is None):
DealPicture.find_photo_center('res/pictures/level_1-7.png', 1, 0.9) is None):
drag_position = cv2.imread('../pictures/back_btn.png')
drag_position = cv2.imread('res/pictures/back_btn.png')
name = 'level_1-7.png'
if DealPicture.find_photo_center('../pictures/back_btn.png', 2):
if DealPicture.find_photo_center('res/pictures/back_btn.png', 2):
operation.drag_once(drag_position, 300, 0, 0, 200)
else:
print("don't find picture ", name)
return False
while DealPicture.find_photo_center('../pictures/level_1-7.png', 1, 0.9) is None:
drag_position = cv2.imread('../pictures/back_btn.png')
if DealPicture.find_photo_center('../pictures/back_btn.png', 2):
while DealPicture.find_photo_center('res/pictures/level_1-7.png', 1, 0.9) is None:
drag_position = cv2.imread('res/pictures/back_btn.png')
if DealPicture.find_photo_center('res/pictures/back_btn.png', 2):
operation.drag_once(drag_position, -400, 0, 300, 200)
else:
print("back to terminal")
return False
click_photo = cv2.imread('../pictures/level_1-7.png')
stop_photo = [cv2.imread('../pictures/fight_photo.png')]
click_photo = cv2.imread('res/pictures/level_1-7.png')
stop_photo = [cv2.imread('res/pictures/fight_photo.png')]
name = 'level_1-7.png'
if DealPicture.find_photo_center(click_photo, 1, 0.9):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photo))
@ -72,8 +72,8 @@ def find_target_level():
def find_target_chapter():
print("finding chapter")
click_photo = cv2.imread('../pictures/terminal_photo.png')
stop_photo = [cv2.imread('../pictures/theme_word.png')]
click_photo = cv2.imread('res/pictures/terminal_photo.png')
stop_photo = [cv2.imread('res/pictures/theme_word.png'), cv2.imread('res/pictures/theme_word2.png')]
name = 'terminal_photo.png'
if DealPicture.find_photo_center(click_photo, 1):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photo))
@ -81,8 +81,8 @@ def find_target_chapter():
print("don't find picture", name)
return False
click_photo = cv2.imread('../pictures/theme_word.png')
stop_photo = [cv2.imread('../pictures/black_circle.png')]
click_photo = cv2.imread('res/pictures/theme_word.png')
stop_photo = [cv2.imread('res/pictures/black_circle.png')]
name = 'theme_word.png'
if DealPicture.find_photo_center(click_photo, 1):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photo))
@ -90,8 +90,8 @@ def find_target_chapter():
print("don't find picture", name)
return False
drag_position = cv2.imread('../pictures/black_circle.png')
stop_photo = [cv2.imread('../pictures/purpose_chapter.png')]
drag_position = cv2.imread('res/pictures/black_circle.png')
stop_photo = [cv2.imread('res/pictures/purpose_chapter.png')]
name = 'black_circle.png'
if DealPicture.find_photo_center(drag_position, 1):
operation.drag_util(drag_position, lambda: DealPicture.find_any_photos(stop_photo), 0, 400)
@ -99,8 +99,8 @@ def find_target_chapter():
print("don't find picture", name)
return False
drag_position = cv2.imread('../pictures/chapter3.png')
stop_photo = [cv2.imread('../pictures/chapter2.png')]
drag_position = cv2.imread('res/pictures/chapter3.png')
stop_photo = [cv2.imread('res/pictures/chapter2.png')]
name = 'chapter3.png'
if DealPicture.find_photo_center(drag_position, 1):
operation.drag_util(drag_position, lambda: DealPicture.find_any_photos(stop_photo), 300, 0)
@ -108,8 +108,8 @@ def find_target_chapter():
print("don't find picture", name)
return False
drag_position = cv2.imread('../pictures/chapter2.png')
stop_photo = [cv2.imread('../pictures/chapter1.png')]
drag_position = cv2.imread('res/pictures/chapter2.png')
stop_photo = [cv2.imread('res/pictures/chapter1.png')]
name = 'chapter2.png'
if DealPicture.find_photo_center(drag_position, 1):
operation.drag_util(drag_position, lambda: DealPicture.find_any_photos(stop_photo), 300, 0)
@ -117,8 +117,8 @@ def find_target_chapter():
print("don't find picture", name)
return False
click_photo = cv2.imread('../pictures/chapter1.png')
stop_photos = [cv2.imread('../pictures/fight_photo.png'), cv2.imread('../pictures/cur_chapter1.png')]
click_photo = cv2.imread('res/pictures/chapter1.png')
stop_photos = [cv2.imread('res/pictures/fight_photo.png'), cv2.imread('res/pictures/cur_chapter1.png')]
name = 'chapter1.png'
if DealPicture.find_photo_center(click_photo, 1):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photos))
@ -131,8 +131,8 @@ def find_target_chapter():
def fight_time():
print("fighting time!")
click_photo = cv2.imread('../pictures/fight_photo.png')
stop_photo = [cv2.imread('../pictures/start_fighting.png')]
click_photo = cv2.imread('res/pictures/fight_photo.png')
stop_photo = [cv2.imread('res/pictures/start_fighting.png')]
name = 'fight_photo.png'
if DealPicture.find_photo_center(click_photo, 1):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photo))
@ -140,8 +140,8 @@ def fight_time():
print("don't find picture", name)
return False
click_photo = cv2.imread('../pictures/start_fighting.png')
stop_photo = [cv2.imread('../pictures/fighting!.png')]
click_photo = cv2.imread('res/pictures/start_fighting.png')
stop_photo = [cv2.imread('res/pictures/fighting!.png')]
name = 'start_fighting!.png'
if DealPicture.find_photo_center(click_photo, 2):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photo))
@ -149,18 +149,18 @@ def fight_time():
print("don't find picture", name)
return False
click_photo = cv2.imread('../pictures/fighting!.png')
click_photo = cv2.imread('res/pictures/fighting!.png')
while DealPicture.find_photo_center(click_photo, 10):
print("战斗中")
time.sleep(10)
click_photo = cv2.imread('../pictures/mission_fail.png')
stop_photo = [cv2.imread('../pictures/mission_complete.png')]
click_photo = cv2.imread('res/pictures/mission_fail.png')
stop_photo = [cv2.imread('res/pictures/mission_complete.png')]
if DealPicture.find_photo_center(click_photo, 5):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photo))
click_photo = cv2.imread('../pictures/mission_complete.png')
stop_photo = [cv2.imread('../pictures/fight_photo.png')]
click_photo = cv2.imread('res/pictures/mission_complete.png')
stop_photo = [cv2.imread('res/pictures/fight_photo.png')]
name = 'mission_complete.png'
if DealPicture.find_photo_center(click_photo, 5):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photo))
@ -175,9 +175,6 @@ class WorkerThread(QThread):
finished = pyqtSignal()
def run(self):
os.chdir('res/rules')
current_directory = os.getcwd()
print("Current working directory:", current_directory)
i = 0
if find_target_level():
while i < 10:
@ -193,8 +190,5 @@ class WorkerThread(QThread):
while i < 10:
fight_time()
i += 1
os.chdir('../../../windows')
current_directory = os.getcwd()
print("Current working directory:", current_directory)
print("自动战斗完毕")
self.finished.emit()

@ -1,14 +1,60 @@
import re
import time
import cv2
import numpy as np
import pyautogui
import pyautogui as p
from PIL.Image import Image
from paddleocr import PaddleOCR
from windows.entity.priority.priority import Priority
class DealPicture:
ocr = PaddleOCR(use_angle_cls=True, lang="ch")
@staticmethod
def screenShot():
p.screenshot().save('../pictures/screenshot.png')
def shot_photo(position):
# 检查变量是否为元组
if isinstance(position, tuple):
# 将元组转换为字典
position_dict = {
'left': position[0],
'top': position[1],
'width': position[2],
'height': position[3]
}
else:
position_dict = position
photo = p.screenshot(region=(position_dict['left'], position_dict['top'],
position_dict['width'], position_dict['height']))
return photo
@staticmethod
def find_photo_positons(photo, run_time=None, confidence=None):
"""
:param photo: 图片地址或是一个imread
:param run_time: 单位秒
:param confidence: 可选参数图片相似度
:return: 一个positions参数为.left,.top,.width,.height
"""
count = 5
i = 0
if confidence is not None:
confidence = confidence
else:
confidence = 0.9
if run_time:
count = run_time * 10
while i < count:
positions = p.locateOnScreen(photo, confidence=confidence)
if positions:
return positions
i += 1
time.sleep(0.1)
return None
@staticmethod
def find_photo_center(photo, run_time=None, confidence=None):
@ -17,22 +63,24 @@ class DealPicture:
:param photo: 图片地址或是一个imread
:param run_time: 单位秒
:param confidence: 可选参数图片相似度
:return: 一个positions参数为xy
:return: 一个positions参数为.x ,.y
"""
count = 5
i = 0
if confidence is not None:
confidence = confidence
else:
confidence = 0.8
confidence = 0.9
if run_time:
count = run_time * 10
while i < count:
positions = p.locateCenterOnScreen(photo, confidence=confidence)
if positions:
return positions
i += 1
time.sleep(0.1)
return None
@staticmethod
@ -55,3 +103,448 @@ class DealPicture:
i += 1
time.sleep(0.1)
return False
@staticmethod
def find_no_photos(photos, run_time=None):
"""
:param photos: 多个图片地址
:param run_time: 单位秒
:return: true or false
"""
count = 3
i = 0
if run_time:
count = run_time * 10
while i < count:
for photo in photos:
positions = p.locateCenterOnScreen(photo, confidence=0.8)
if positions:
return False
i += 1
time.sleep(0.1)
return True
@staticmethod
def find_all_photos(photos, run_time=None):
"""
:param photos: 多个图片地址
:param run_time: 单位秒
:return: true or false
"""
count = 5
i = 0
if run_time:
count = run_time * 10
while i < count:
find_photo_number = 0
for photo in photos:
positions = p.locateCenterOnScreen(photo, confidence=0.8)
if positions:
find_photo_number += 1
if find_photo_number == len(photos):
return True
i += 1
time.sleep(0.1)
return False
@staticmethod
def match_template(template, threshold=None):
"""
匹配掩码图片黑色为掩码
:param template: 要匹配的图片
:param threshold: 相似度
:return: 所有图片的positions,字典参数为lefttopheightwidth
"""
screenshot = pyautogui.screenshot()
original_image = cv2.cvtColor(np.array(screenshot.convert('RGB'))[:, :, ::-1], cv2.COLOR_BGR2GRAY)
# 将模板图像中的黑色部分掩码为0白色部分保留
_, mask = cv2.threshold(template, 1, 255, cv2.THRESH_BINARY)
# 检查掩码图像的通道数是否与模板图像的通道数相同,如果不同,将掩码图像转换为灰度图像(单通道图像)
if mask.shape[2] > 1:
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
# 检查原始图像和模板图像的通道数是否超过2如果超过2可以将它们转换为灰度图像
if template.shape[2] > 2:
template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
# 使用模板匹配技术,在原始图像上应用模板图像的掩码
result = cv2.matchTemplate(original_image, template, cv2.TM_CCOEFF_NORMED, mask=mask)
# 获取匹配结果的位置信息
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
# 获取模板图像的宽度和高度
width, height = template.shape[::-1]
if threshold is None:
# 如果匹配度较高(可以根据需要调整阈值)
threshold = 0.8
else:
threshold = threshold
positons = {}
# 如果匹配度超过阈值,则在匹配到的位置画一个矩形
if max_val >= threshold:
top_left = max_loc
positons['left'] = top_left[0]
positons['width'] = width
positons['top'] = top_left[1]
positons['height'] = height
else:
positons = None
print("未找到匹配的位置")
if positons is None:
return None
else:
return positons
@staticmethod
def mapping_any_photo(template, target, threshold=None):
"""
:param template: 被匹配的图片
:param target: []数组要匹配的图片
:param threshold:相似的
:return: true or false
"""
# 将Pillow图像转换为NumPy数组并确保颜色通道顺序为BGR
template_np = np.array(template)
for traget_photo in target:
if type(traget_photo) != np.ndarray:
print(type(traget_photo))
print(target)
# 使用归一化相关匹配方法
result = cv2.matchTemplate(traget_photo, template_np, cv2.TM_CCOEFF_NORMED)
# 获取所有匹配位置其中匹配度大于0.8的位置
if threshold is None:
threshold_ = 0.9
else:
threshold_ = threshold
loc = np.where(result >= threshold_)
if len(loc[0]) > 0:
return True
return False
@staticmethod
def mapping_all_photo(template, target, threshold=None):
count = 0
for traget_photo in target:
# 使用归一化相关匹配方法
result = cv2.matchTemplate(traget_photo, template, cv2.TM_CCOEFF_NORMED)
# 获取所有匹配位置其中匹配度大于0.8的位置
if threshold is None:
threshold_ = 0.8
else:
threshold_ = threshold
loc = np.where(result >= threshold_)
if len(loc[0]) > 0:
count += 1
if count == len(target):
return True
return False
@staticmethod
def find_operator_rectangle(traget_photo, threshold=None):
"""
:param traget_photo: 图片用于筛选轮廓为数组
:param threshold:相似度
:return:
"""
# 读取截图并转换为OpenCV格式
# screenshot_cv = cv2.imread("../pictures/template.png")
screenshot = p.screenshot()
# 将Pillow图像转换为NumPy数组并确保颜色通道顺序为BGR
screenshot_cv = np.array(screenshot.convert('RGB'))[:, :, ::-1]
# 将截图转换为灰度图像
gray_image = cv2.cvtColor(screenshot_cv, cv2.COLOR_BGR2GRAY)
# 使用Canny边缘检测
edges = cv2.Canny(gray_image, threshold1=200, threshold2=250) # 150 350
# 寻找轮廓
contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# # 在原始图像上绘制轮廓
# cv2.drawContours(screenshot_cv, contours, -1, (0, 255, 0), 2) # -1表示绘制所有轮廓
#
# # 显示带有轮廓的图像
# cv2.imshow("Contours", screenshot_cv)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
if threshold is None:
threshold_ = 0.9
else:
threshold_ = threshold
# 指定矩形的最小宽度和最小高度
min_width = 145
min_height = 120
max_width = 180
# 在原始图像上将符合条件图片添加进来
match_photos = []
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
if min_width <= w <= max_width and h >= min_height:
cropped_image = screenshot_cv[y:y + h, x:x + w]
result = DealPicture.mapping_any_photo(cropped_image, traget_photo, threshold_)
if result:
match_photos.append(cropped_image)
return match_photos
# # 显示带有轮廓的图像
# cv2.imshow("Contours", screenshot_cv)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
@staticmethod
def class_dormitory_priority(photos, priority_list):
last_mapping = False
successive_fail = 0
find_any = False
for photo in photos:
if len(priority_list['5']) > 4:
return False
find_purpose = False
find_word = ''
words = DealPicture.words_in_photo(DealPicture.recognise_word(photo))
if len(words) > 0:
find_word = DealPicture.find_best_word(words)
for key, value in Priority.dormitory_priority.items():
target = [cv2.imread(value[0])]
if DealPicture.mapping_any_photo(photo, target):
find_purpose = True
if find_word not in priority_list[value[1]]:
priority_list[value[1]].append(find_word)
last_mapping = True
successive_fail = 0
find_any = True
break
if find_purpose is False:
if find_word != '':
priority_list['1'].append(find_word)
if not last_mapping:
successive_fail += 1
else:
successive_fail = 0
last_mapping = False
if successive_fail >= 6:
return False
if not find_any:
return False
return True
@staticmethod
def class_experience_priority(photos, priority_list):
last_mapping = False
successive_fail = 0
find_any = False
for photo in photos:
if len(priority_list['5']) > 3:
return False
find_purpose = False
find_word = ''
words = DealPicture.words_in_photo(DealPicture.recognise_word(photo))
if len(words) > 0:
find_word = DealPicture.find_best_word(words)
for key, value in Priority.producing_experience_priority.items():
target = [cv2.imread(value[0])]
if DealPicture.mapping_any_photo(photo, target):
find_purpose = True
if find_word not in priority_list[value[1]]:
priority_list[value[1]].append(find_word)
last_mapping = True
successive_fail = 0
find_any = True
break
if find_purpose is False:
if find_word != '':
priority_list['1'].append(find_word)
if not last_mapping:
successive_fail += 1
else:
successive_fail = 0
last_mapping = False
if successive_fail >= 6:
return False
if not find_any:
return False
return True
@staticmethod
def class_material_priority(photos, priority_list):
last_mapping = False
successive_fail = 0
for photo in photos:
if len(priority_list['5']) >= 3:
break
find_purpose = False
find_word = ''
words = DealPicture.words_in_photo(DealPicture.recognise_word(photo))
if len(words) > 0:
find_word = DealPicture.find_best_word(words)
for key, value in Priority.producing_material_priority.items():
target = [cv2.imread(value[0])]
if DealPicture.mapping_any_photo(photo, target):
if find_word not in priority_list[value[1]]:
priority_list[value[1]].append(find_word)
find_purpose = True
last_mapping = True
successive_fail = 0
break
if find_purpose is False:
priority_list['1'].append(find_word)
if not last_mapping:
successive_fail += 1
else:
successive_fail = 0
last_mapping = False
if successive_fail >= 5:
return False
return True
@staticmethod
def class_trading_priority(photos, priority_list):
last_mapping = False
successive_fail = 0
for photo in photos:
if len(priority_list['5']) >= 3:
break
find_purpose = False
find_word = ''
words = DealPicture.words_in_photo(DealPicture.recognise_word(photo))
if len(words) > 0:
find_word = DealPicture.find_best_word(words)
for key, value in Priority.trading_priority.items():
target = [cv2.imread(value[0])]
if DealPicture.mapping_any_photo(photo, target):
if find_word not in priority_list[value[1]]:
priority_list[value[1]].append(find_word)
find_purpose = True
last_mapping = True
successive_fail = 0
break
if find_purpose is False:
priority_list['1'].append(find_word)
if not last_mapping:
successive_fail += 1
else:
successive_fail = 0
last_mapping = False
if successive_fail >= 5:
return False
return True
@staticmethod
def recognise_word(photo):
# 将Pillow图像对象转换为np.ndarray类型
photo_np = np.array(photo)
recognise_result = DealPicture.ocr.ocr(photo_np, cls=False)
return recognise_result
@staticmethod
def words_in_photo(words_inf):
words = []
for inf in words_inf:
word = inf[1][0]
# 保留中文,英文,,数字
cleaned_text = re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9]', '', word)
if cleaned_text != '':
words.append(cleaned_text)
return words
@staticmethod
def find_word_positon(traget_word, words_inf):
word_position = {}
for inf in words_inf:
word = inf[1][0]
cleaned_text = re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9]', '', word)
if cleaned_text.__contains__(traget_word):
word_position['left'] = inf[0][0][0]
word_position['top'] = inf[0][0][1]
word_position['width'] = inf[0][1][0] - inf[0][0][0]
word_position['height'] = inf[0][2][1] - inf[0][0][1]
return word_position
return None
@staticmethod
def find_words_positon(traget_words, words_inf):
"""
找到所有目标文字地址
:param traget_words: 一个数组
:param words_inf: 当前屏幕文字信息
:return: 地址数组
"""
position_array = []
for inf in words_inf:
word = inf[1][0]
cleaned_text = re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9]', '', word)
for traget_word in traget_words:
if cleaned_text.__contains__(traget_word):
word_position = {'left': inf[0][0][0],
'top': inf[0][0][1],
'width': inf[0][1][0] - inf[0][0][0],
'height': inf[0][2][1] - inf[0][0][1],
'name': traget_word
}
position_array.append(word_position)
break
return position_array
@staticmethod
def find_best_word(words):
"""
找到最适合的一段文字
:param words: 文字数组
:return: 找到的文字
"""
target_word = ''
# 匹配包含中文字符的正则表达式
# 如果文本中包含中文字符
pattern_ch = re.compile(r'[\u4e00-\u9fa5]')
# 匹配包含英文字符和数字的正则表达式
pattern_en_number = re.compile(r'[a-zA-Z0-9]')
# 匹配只包含英文字符的正则表达式
pattern_en = re.compile(r'[a-zA-Z]')
for word in words:
if pattern_ch.search(word):
target_word = word
break
elif pattern_en_number.search(word):
target_word = word
elif pattern_en.search(word):
target_word = word
return target_word
@staticmethod
def screen_changed(last_photo, current_photo):
last = last_photo
current = current_photo
# 将元组转换为字典
if isinstance(last, Image):
last_np = np.array(last.convert('RGB'))[:, :, ::-1]
else:
last_np = last_photo
if isinstance(current, Image):
current_np = [np.array(current.convert('RGB'))[:, :, ::-1]]
else:
current_np = [current]
changed = DealPicture.mapping_any_photo(last_np, current_np, 0.9)
if changed:
return False
else:
return True

@ -0,0 +1,35 @@
from time import sleep
import cv2
import numpy as np
from windows.res.tools.deal_picture import DealPicture
import pyautogui as p
from paddleocr import PaddleOCR
ocr = PaddleOCR(use_angle_cls=False, lang="ch") # 初始化OCR模型
shotArea = {}
find_photo = cv2.imread('../pictures/producing_list.png')
positons1 = DealPicture.find_photo_positons(find_photo)
print(positons1.x)
sleep(3)
if positons1:
shotArea['left'] = positons1.left
shotArea['top'] = positons1.top + positons1.height
shotArea['width'] = positons1.width
find_photo = cv2.imread('../pictures/operator_in_producing.png')
positons1 = DealPicture.find_photo_positons(find_photo)
if positons1:
shotArea['height'] = positons1.top - shotArea['top'] + positons1.height
screenshot = p.screenshot(region=(shotArea['left'], shotArea['top'],
shotArea['width'], shotArea['height']))
screenshot_np = np.array(screenshot.convert('RGB'))[:, :, ::-1] # 将Pillow图像对象转换为np.ndarray类型
result = ocr.ocr(screenshot_np, cls=False)
orgwords = ''
for idx in result:
res = idx[1][0]
orgwords += res
print(result)
print(orgwords)

@ -7,6 +7,20 @@ import shutil
from operateselect_window import operateselect
import os
import time
import cv2
import pyautogui as p
from PyQt5.QtCore import QThread, pyqtSignal
from windows.entity.operations.operation import operation
from windows.res.tools.deal_picture import DealPicture
from windows.control.database.databaseconnact import *
class settingrule(QMainWindow):
def __init__(self):
super().__init__()
@ -49,7 +63,17 @@ class settingrule(QMainWindow):
def write_image_to_folder(self): # 将图片写入目标文件
text_edit = self.findChild(QTextEdit, "textEdit")
self.image_path = text_edit.toPlainText()
db = DatabaseHandler(database='gamerule', user='postgres', password='123456', host='localhost', port='5432')
db.connect()
db.create_table('rule11')
db.insert_data('rule11', 9, self.image_path, 0, 0, 0, 0, 0, '0,0,0')
db.execute_query('rule11')
db.close()
print(self.image_path)
destination_path = "D:/代码/pythoncode/src/windows/res/pictures"
if not os.path.exists(self.image_path):
print("image address is not existing!")
@ -59,6 +83,15 @@ class settingrule(QMainWindow):
def write_image_to_folder_2(self): # 将图片写入目标文件
text_edit = self.findChild(QTextEdit, "textEdit_2")
self.image_path = text_edit.toPlainText()
db = DatabaseHandler(database='gamerule', user='postgres', password='123456', host='localhost', port='5432')
db.connect()
db.create_table('rule11')
db.insert_data('rule11', 9, self.image_path, 0, 0, 0, 0, 0, '0,0,0')
db.execute_query('rule11')
db.close()
print(self.image_path)
destination_path = "D:/代码/pythoncode/src/windows/res/pictures"
if not os.path.exists(self.image_path):
@ -69,6 +102,14 @@ class settingrule(QMainWindow):
def write_image_to_folder_3(self): # 将图片写入目标文件
text_edit = self.findChild(QTextEdit, "textEdit_3")
self.image_path = text_edit.toPlainText()
db = DatabaseHandler(database='gamerule', user='postgres', password='123456', host='localhost', port='5432')
db.connect()
db.create_table('rule11')
db.insert_data('rule11', 9, self.image_path, 0, 0, 0, 0, 0, '0,0,0')
db.execute_query('rule11')
db.close()
print(self.image_path)
destination_path = "D:/代码/pythoncode/src/windows/res/pictures"
if not os.path.exists(self.image_path):

@ -0,0 +1,158 @@
# from time import sleep
#
# import cv2
# import numpy as np
# import pyautogui
#
# # 读取原始图像和模板图像
# # 读取输入图像和模板图像
#
# sleep(3)
# template = cv2.imread('../pictures/current_trade_station.png')
#
# # 截取模板图像并转换为Numpy数组
# original_image = pyautogui.screenshot()
#
# original_image_np = np.array(original_image)
#
# # 创建一个掩码将黑色区域设为0其他区域设为255
# mask = cv2.inRange(template, (0, 0, 0), (0, 0, 0)) # 这里假设黑色的RGB值在(0, 0, 0)到(10, 10, 10)之间
#
# # 在模板图像上应用掩码
# masked_image = cv2.bitwise_and(template, template, mask=~mask)
#
# # 显示结果图像
# cv2.imshow('Result', masked_image)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
#
# # 使用模板匹配函数进行匹配这里使用TM_CCOEFF_NORMED方法
# result = cv2.matchTemplate(original_image_np, template, cv2.TM_CCOEFF_NORMED)
#
# # 设置阈值这里假设阈值为0.8
# threshold = 0.8
#
# # 在匹配结果中找到匹配位置
# locations = np.where(result >= threshold)
# for loc in zip(*locations[::-1]):
# cv2.rectangle(original_image_np, loc, (loc[0] + template.shape[1], loc[1] + template.shape[0]), (0, 255, 0), 2)
#
# # 显示结果图像
# cv2.imshow('Result', original_image_np)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# from time import sleep
#
# import cv2
# import numpy as np
# import pyautogui
#
# sleep(3)
# template = cv2.imread('../pictures/current_trade_station.png')
#
# # 截取模板图像并转换为Numpy数组
# original_image = pyautogui.screenshot()
#
# original_image_np = np.array(original_image)
#
# # 将模板图像转换为带有Alpha通道的图像
# temp_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
# _, alpha = cv2.threshold(temp_gray, 0, 255, cv2.THRESH_BINARY)
# template_with_alpha = cv2.merge([template, alpha])
#
# # 将模板图像的数据类型转换为与原始图像相匹配的类型
# template_with_alpha = template_with_alpha.astype(original_image.dtype)
#
# # 显示结果
# cv2.imshow('Matching Result', template_with_alpha)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
#
#
# # 执行模板匹配
# result = cv2.matchTemplate(original_image_np, template_with_alpha, cv2.TM_CCOEFF_NORMED)
#
# # 获取匹配结果的坐标
# min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
#
# # 绘制矩形框标记匹配区域
# top_left = max_loc
# bottom_right = (top_left[0] + template.shape[1], top_left[1] + template.shape[0])
# cv2.rectangle(original_image_np, top_left, bottom_right, (0, 255, 0), 2)
#
# # 显示结果
# cv2.imshow('Matching Result', original_image_np)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# from time import sleep
#
# import cv2
# import numpy as np
# import pyautogui
#
# sleep(3)
# template = cv2.imread('../pictures/current_trade_station.png', 0)
# screenshot = pyautogui.screenshot()
# original_image = cv2.cvtColor(np.array(screenshot), cv2.COLOR_BGR2GRAY)
# # 将模板图像中的黑色部分掩码为0白色部分保留
# _, mask = cv2.threshold(template, 1, 255, cv2.THRESH_BINARY)
#
# # 使用模板匹配技术,在原始图像上应用模板图像的掩码
# result = cv2.matchTemplate(original_image, template, cv2.TM_CCOEFF_NORMED, mask=mask)
#
# # 获取匹配结果的位置信息
# min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
#
# # 获取模板图像的宽度和高度
# width, height = template.shape[::-1]
#
# # 如果匹配度较高(可以根据需要调整阈值)
# threshold = 0.8
#
# # 如果匹配度超过阈值,则在匹配到的位置画一个矩形
# if max_val >= threshold:
# top_left = max_loc
# bottom_right = (top_left[0] + width, top_left[1] + height)
# cv2.rectangle(original_image, top_left, bottom_right, 255, 2)
#
# # 显示带有矩形标记的图像
# cv2.imshow('Matching Result', original_image)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# else:
# print("未找到匹配的位置")
from time import sleep
import cv2
from windows.res.tools.deal_picture import DealPicture
from time import sleep
import 明日方舟换基建
sleep(3)
明日方舟换基建.change_current_operators()
# 明日方舟换基建.click_operator_by_priority(priority_list)
# import numpy as np
# import pyautogui
# from PIL.Image import Image
#
# q = pyautogui.screenshot()
# q_np = np.array(q)
# print(type(q_np))
# if isinstance(q_np, np.ndarray):
# print('sda')
# sleep(2)
# priority_list = {'1': [], '2': [], '3': [], '4': [], '5': []}
# target_photo = [cv2.imread('res/pictures/good_mood.png'), cv2.imread('res/pictures/common_mood.png')]
# result_photo = DealPicture.find_operator_rectangle(target_photo)
# cv2.imshow('Matching Result', result_photo[1])
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# q_photo = cv2.imread('res/pictures/common_produce.png')
# q = DealPicture.mapping_any_photo(result_photo[0], target_photo)
# print(q)
# continue_shot = DealPicture.class_experience_priority(result_photo, priority_list)
# print(continue_shot)

@ -0,0 +1,587 @@
import time
import cv2
import pyautogui as p
from windows.entity.operations.operation import operation
from windows.res.tools.deal_picture import DealPicture
p.PAUSE = 0.1
p.FAILSAFE = True
def backToTerminal():
print("back to terminal")
positions = DealPicture.find_photo_center('res/pictures/terminal_photo.png', 2)
while positions is None:
click_photo = cv2.imread('res/pictures/back_btn.png')
back_confirm = cv2.imread('res/pictures/back_confirm.png')
if DealPicture.find_photo_center(click_photo, 1):
operation.click_once(click_photo)
else:
return False
if DealPicture.find_photo_center(back_confirm, 1):
operation.click_once(back_confirm)
else:
return False
positions = DealPicture.find_photo_center('res/pictures/terminal_photo.png')
print("find terminal")
return True
def back_to_base():
print("back to terminal")
find_photo = cv2.imread('res/pictures/overview.png')
positions = DealPicture.find_photo_center(find_photo, 2)
while positions is None:
click_photo = cv2.imread('res/pictures/back_btn.png')
back_confirm = cv2.imread('res/pictures/back_cancel.png')
if DealPicture.find_photo_center(click_photo, 1):
operation.click_once(click_photo)
if DealPicture.find_photo_center(back_confirm, 1):
operation.click_once(back_confirm)
positions = DealPicture.find_photo_center(find_photo)
print("find base")
return True
def enter_base():
print("enter the base")
click_photo = cv2.imread('res/pictures/base.png')
stop_photos = [cv2.imread('res/pictures/electricity.png'), cv2.imread('res/pictures/loading.png')]
name = 'base.png'
if DealPicture.find_photo_center(click_photo, 1):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photos))
else:
print("don't find picture", name)
return False
def deal_award():
print("acquire awards")
click_photo = cv2.imread('res/pictures/notice.png')
stop_photos = [cv2.imread('res/pictures/todo-things.png')]
name = 'notice.png'
if DealPicture.find_photo_center(click_photo, 2):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photos))
else:
print("don't find picture", name)
return False
traget_pictures = [cv2.imread('res/pictures/acquiring.png'),
cv2.imread('res/pictures/agenttrust.png'),
cv2.imread('res/pictures/order_delivery.png')]
while DealPicture.find_any_photos(traget_pictures):
if DealPicture.find_photo_center(cv2.imread('res/pictures/acquiring.png'), 0.3):
click_photo = cv2.imread('res/pictures/acquiring.png')
operation.click_once(click_photo)
if DealPicture.find_photo_center(cv2.imread('res/pictures/agenttrust.png'), 0.3):
click_photo = cv2.imread('res/pictures/acquiring.png')
operation.click_once(click_photo)
if DealPicture.find_photo_center(cv2.imread('res/pictures/order_delivery.png'), 0.3):
click_photo = cv2.imread('res/pictures/acquiring.png')
operation.click_once(click_photo)
click_photo = cv2.imread('res/pictures/notice.png')
stop_photos = [cv2.imread('res/pictures/overview.png')]
name = 'notice.png'
if DealPicture.find_photo_center(click_photo, 2):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photos))
else:
print("don't find picture", name)
return False
def change_dormitory_operators():
"""
改变当前所有宿舍干员
:return:
"""
click_photo = cv2.imread('res/pictures/overview.png')
stop_photos = [cv2.imread('res/pictures/remove_operator.png')]
name = 'overview.png'
if DealPicture.find_photo_center(click_photo, 1, 0.7):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photos))
else:
print("don't find picture", name)
return False
changed_dormitory = 0
find_photo = cv2.imread('res/pictures/current_clicked_construction.png')
target_word = '宿舍'
target_photos = [cv2.imread('res/pictures/good_mood_overview.png'),
cv2.imread('res/pictures/common_mood_overview.png')]
while True:
shotphoto = p.screenshot()
words_inf = DealPicture.recognise_word(shotphoto)
word_position = DealPicture.find_word_positon(target_word, words_inf)
# 找到宿舍
if word_position is not None:
photo_position = None
while photo_position is None:
# 点击宿舍
operation.click_position_once(word_position)
photo_position = DealPicture.match_template(find_photo)
shot_photo1 = DealPicture.shot_photo(photo_position)
target_photo1 = [cv2.imread('res/pictures/good_mood_overview.png')]
# 点击心情,进入宿舍
if DealPicture.mapping_any_photo(shot_photo1, target_photo1):
stop_photo = cv2.imread('res/pictures/clear_options.png')
operation.click_util(target_photo1[0], lambda: DealPicture.find_photo_center(stop_photo), 0, -50)
# 以心情优先
click_photo = cv2.imread('res/pictures/clear_options.png')
stop_photo = [cv2.imread('res/pictures/the_fifth_choosed.png')]
if DealPicture.find_photo_center(click_photo, 1, 0.9):
operation.click_util(click_photo, lambda: DealPicture.find_photo_center(stop_photo))
# else:
# print("don't find picture", name)
# 将好心情干员放前面来
click_photo = cv2.imread('res/pictures/mood.png')
stop_photos = [cv2.imread('res/pictures/mood_down.png')]
name = 'mood.png'
if DealPicture.find_photo_center(click_photo, 1, 0.9):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photos))
# 将好心情干员放前面来
click_photo = cv2.imread('res/pictures/mood_down.png')
stop_photos = [cv2.imread('res/pictures/mood_up.png')]
name = 'mood_down.png'
if DealPicture.find_photo_center(click_photo, 1, 0.9):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photos))
# else:
# print("don't find picture", name)
# 截图,优先级
priority_list = {'1': [], '2': [], '3': [], '4': [], '5': []}
target_photo2 = [cv2.imread('res/pictures/bad_mood.png'),
[cv2.imread('res/pictures/common_mood.png')]]
photos = DealPicture.find_operator_rectangle(target_photo2)
DealPicture.class_dormitory_priority(photos, priority_list)
click_operator_by_priority(priority_list, True)
def enter_product_stations():
click_photo = cv2.imread('res/pictures/product_station.png')
stop_photos = [cv2.imread('res/pictures/enter_product.png')]
name = 'product_station.png'
if DealPicture.find_photo_center(click_photo, 1, 0.7):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photos))
else:
print("don't find picture", name)
return False
click_photo = cv2.imread('res/pictures/enter_product.png')
stop_photos = [cv2.imread('res/pictures/producing_list.png')]
name = 'enter_product.png'
if DealPicture.find_photo_center(click_photo, 1):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photos))
else:
print("don't find picture", name)
return False
click_photo = cv2.imread('res/pictures/unclicked_product_station01.png')
stop_photos = [cv2.imread('res/pictures/clicked_product_station01.png')]
if DealPicture.find_photo_center(click_photo, 1):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photos))
else:
print("don't find picture", name)
return False
def judge_current_position():
trading_station = cv2.imread('res/pictures/in_trading_station.png')
producing_station = cv2.imread('res/pictures/in_producing_station.png')
if DealPicture.find_photo_center(trading_station):
return 'trading_station'
if DealPicture.find_photo_center(producing_station):
return 'producing_station'
return ''
def juge_current_station(words):
for word in words:
if word.__contains__('01'):
return '01'
elif word.__contains__('02'):
return '02'
elif word.__contains__('03'):
return '03'
elif word.__contains__('04'):
return '04'
elif word.__contains__('05'):
return '05'
elif word.__contains__('06'):
return '06'
return ''
def juge_next_station(current_station):
if current_station == '01':
return '02'
elif current_station == '02':
return '03'
elif current_station == '03':
return '04'
elif current_station == '04':
return '05'
elif current_station == '05':
return '06'
else:
return ''
def to_next_station():
"""
点击下一个工作站
:return:
"""
current_position = judge_current_position()
if current_position == '':
current_position = judge_current_position()
if current_position == '':
return False
shotArea = {}
if current_position == 'trading_station':
# 得到当前贸易站
current_station_photo = cv2.imread('res/pictures/current_trade_station.png')
current_station_position = DealPicture.match_template(current_station_photo)
screenshot = p.screenshot(region=(current_station_position['left'], current_station_position['top'],
current_station_position['width'], current_station_position['height']))
words_inf = DealPicture.recognise_word(screenshot)
word = DealPicture.words_in_photo(words_inf)
current_station = juge_current_station(word)
if current_station == '':
return False
# 得到当前的贸易站列表
find_photo = cv2.imread('res/pictures/trading_list.png')
positons1 = DealPicture.find_photo_positons(find_photo)
if positons1:
shotArea['left'] = positons1.left
shotArea['top'] = positons1.top + positons1.height
shotArea['width'] = positons1.width
find_photo = cv2.imread('res/pictures/operator_in_trading.png')
positons1 = DealPicture.find_photo_positons(find_photo)
if positons1:
shotArea['height'] = positons1.top - shotArea['top'] + positons1.height
screenshot = p.screenshot(region=(shotArea['left'], shotArea['top'],
shotArea['width'], shotArea['height']))
result_inf = DealPicture.recognise_word(screenshot)
# 得到下一个工作站的位置
next_station = juge_next_station(current_station)
if next_station == '':
return False
next_station_position = DealPicture.find_word_positon(next_station, result_inf)
if next_station_position is not None:
next_station_position['left'] = next_station_position['left'] + shotArea['left']
next_station_position['top'] = next_station_position['top'] + shotArea['top']
click_photo = DealPicture.shot_photo(next_station_position)
# 点击图片,直到图片消失
position = DealPicture.find_photo_positons(click_photo)
if position is not None:
operation.click_position_once(position)
else:
print('没找到下一个站')
return False
elif current_position == 'producing_station':
# 得到当前生产站
current_station_photo = cv2.imread('res/pictures/current_product_station.png')
current_station_position = DealPicture.match_template(current_station_photo)
screenshot = p.screenshot(region=(current_station_position['left'], current_station_position['top'],
current_station_position['width'], current_station_position['height']))
words_inf = DealPicture.recognise_word(screenshot)
word = DealPicture.words_in_photo(words_inf)
current_station = juge_current_station(word)
if current_station == '':
return False
# 得到当前的工作站列表
find_photo = cv2.imread('res/pictures/producing_list.png')
positons1 = DealPicture.find_photo_positons(find_photo)
if positons1:
shotArea['left'] = positons1.left
shotArea['top'] = positons1.top + positons1.height
shotArea['width'] = positons1.width
find_photo = cv2.imread('res/pictures/operator_in_producing.png')
positons1 = DealPicture.find_photo_positons(find_photo)
if positons1:
shotArea['height'] = positons1.top - shotArea['top'] + positons1.height
screenshot = p.screenshot(region=(shotArea['left'], shotArea['top'],
shotArea['width'], shotArea['height']))
result_inf = DealPicture.recognise_word(screenshot)
# 得到下一个工作站的位置
next_station = juge_next_station(current_station)
if next_station == '':
return True
next_station_position = DealPicture.find_word_positon(next_station, result_inf)
if next_station_position is not None:
next_station_position['left'] = next_station_position['left'] + shotArea['left']
next_station_position['top'] = next_station_position['top'] + shotArea['top']
click_photo = DealPicture.shot_photo(next_station_position)
# 点击图片,直到图片消失
position = DealPicture.find_photo_positons(click_photo)
if position is not None:
operation.click_position_once(position)
else:
print('没找到下一个站')
return True
return True
def judge_current_product():
judge_photo = cv2.imread('res/pictures/material_product.png')
if DealPicture.find_photo_center(judge_photo):
return 'material'
else:
return 'experience'
def click_operator_by_priority(priority, isdormitory = None):
"""
按照优先级点击干员
:param priority:
"""
# 将好心情干员放前面来
click_photo = cv2.imread('res/pictures/target_working_state.png')
stop_photos = [cv2.imread('res/pictures/mid_working_state.png')]
name = 'target_working_state.png'
if DealPicture.find_photo_center(click_photo, 1):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photos))
else:
print("don't find picture", name)
click_photo = cv2.imread('res/pictures/mid_working_state.png')
stop_photos = [cv2.imread('res/pictures/target_working_state.png')]
name = 'mid_working_state'
if DealPicture.find_photo_center(click_photo, 1):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photos))
else:
print("don't find picture", name)
# 回到最左边
last_photo = p.screenshot()
drag_photo = cv2.imread('res/pictures/confirmbtn.png')
position1 = DealPicture.find_photo_center(drag_photo)
find_photo = cv2.imread('res/pictures/clear_options.png')
position2 = DealPicture.find_photo_center(find_photo)
count_fail = 0
while count_fail < 2:
operation.drag_once(find_photo, position1.x - position2.x, 0, 0, -200)
current_photo = p.screenshot()
if not DealPicture.screen_changed(last_photo, current_photo):
count_fail += 1
last_photo = current_photo
if isdormitory is None:
# 将要点击的干员列出
priority_number = 5
click_list = []
while priority_number >= 1:
for name in priority[str(priority_number)]:
if len(click_list) > 3:
break
click_list.append(name)
priority_number -= 1
if len(click_list) > 3:
break
else:
# 将要点击的干员列出
priority_number = 5
click_list = []
while priority_number >= 1:
for name in priority[str(priority_number)]:
if len(click_list) > 5:
break
click_list.append(name)
priority_number -= 1
if len(click_list) > 5:
break
print(click_list)
# 点击文字
stop_photo = cv2.imread('res/pictures/the_third_choosed.png')
if isdormitory is not None:
stop_photo = cv2.imread('res/pictures/the_fifth_choosed.png')
drag_photo = cv2.imread('res/pictures/confirmbtn.png')
position1 = DealPicture.find_photo_center(drag_photo)
find_photo = cv2.imread('res/pictures/clear_options.png')
position2 = DealPicture.find_photo_center(find_photo)
count_fail1 = 0
last_photo1 = p.screenshot()
stop = None
while stop is None:
current_photo1 = p.screenshot()
words_inf = DealPicture.recognise_word(current_photo1)
# 点击对应文字
# for click_word in click_list:
# position = DealPicture.find_word_positon(click_word, words_inf)
# if position:
# operation.click_position_once(position)
# click_list.remove(click_word)
positions = DealPicture.find_words_positon(click_list, words_inf)
if len(positions) > 0:
for position in positions:
operation.click_position_once(position)
click_list.remove(position['name'])
time.sleep(0.1)
stop = DealPicture.find_photo_center(stop_photo, 0.5, 0.7)
if stop is None:
operation.drag_once(drag_photo, position2.x - position1.x, 0, 0, -200)
if not DealPicture.screen_changed(last_photo1, current_photo1):
count_fail += 1
last_photo1 = current_photo1
if count_fail1 > 3:
break
# 完成后
click_word = cv2.imread('res/pictures/confirmbtn.png')
operation.click_util(click_word, lambda: DealPicture.find_no_photos([click_word]))
def change_current_operators():
"""
改变当前基站干员
:return:
"""
# 进入换干员界面
current_produce = judge_current_product()
current_position = judge_current_position()
if current_position == 'trading_station':
click_photo = cv2.imread('res/pictures/operator_in_trading.png')
stop_photos = [cv2.imread('res/pictures/clear_options.png')]
name = 'operator_in_stations.png'
if DealPicture.find_photo_center(click_photo, 1):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photos), 0, 80)
else:
print("don't find picture", name)
return False
elif current_position == 'producing_station':
click_photo = cv2.imread('res/pictures/operator_in_producing.png')
stop_photos = [cv2.imread('res/pictures/clear_options.png')]
name = 'operator_in_stations.png'
if DealPicture.find_photo_center(click_photo, 1):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photos), 0, 80)
else:
print("don't find picture", name)
return False
# 将好心情放前面
target_mood = cv2.imread('res/pictures/unclicked_working_state.png')
if DealPicture.find_photo_center(target_mood):
click_photo = cv2.imread('res/pictures/unclicked_working_state.png')
stop_photos = [cv2.imread('res/pictures/target_working_state.png'),
cv2.imread('res/pictures/mid_working_state.png')]
name = 'unclicked_working_state.png'
if DealPicture.find_photo_center(click_photo):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photos))
# else:
# print("don't find picture", name)
click_photo = cv2.imread('res/pictures/mid_working_state.png')
stop_photos = [cv2.imread('res/pictures/target_working_state.png')]
name = 'mid_working_state.png'
if DealPicture.find_photo_center(click_photo):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photos))
# else:
# print("don't find picture", name)
# 检查有坏心情,不好心情,就清空当前干员
click_photo = cv2.imread('res/pictures/bad_mood.png')
stop_photos = [cv2.imread('res/pictures/the_first_choosed.png'),
cv2.imread('res/pictures/the_second_choosed.png'),
cv2.imread('res/pictures/the_third_choosed.png')]
name = 'bad_mood.png'
if DealPicture.find_photo_center(click_photo, 1, 0.9):
click_photo = cv2.imread('res/pictures/clear_options.png')
operation.click_util(click_photo, lambda: DealPicture.find_no_photos(stop_photos))
# else:
# print("don't find picture" + name)
click_photo = cv2.imread('res/pictures/bad_common_mood.png')
stop_photos = [cv2.imread('res/pictures/the_first_choosed.png'),
cv2.imread('res/pictures/the_second_choosed.png'),
cv2.imread('res/pictures/the_third_choosed.png')]
name = 'common_mood.png'
if DealPicture.find_photo_center(click_photo, 1, 0.9):
click_photo = cv2.imread('res/pictures/clear_options.png')
operation.click_util(click_photo, lambda: DealPicture.find_no_photos(stop_photos))
# else:
# print("don't find picture", name)
find_photo = cv2.imread('res/pictures/the_third_choosed.png')
if DealPicture.find_photo_center(find_photo):
# 完成后
click_word = cv2.imread('res/pictures/confirmbtn.png')
operation.click_util(click_word, lambda: DealPicture.find_no_photos([click_word]))
return True
# 将好心情干员放前面来
click_photo = cv2.imread('res/pictures/target_working_state.png')
stop_photos = [cv2.imread('res/pictures/mid_working_state.png')]
name = 'target_working_state.png'
if DealPicture.find_photo_center(click_photo, 1):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photos))
# else:
# print("don't find picture", name)
click_photo = cv2.imread('res/pictures/mid_working_state.png')
stop_photos = [cv2.imread('res/pictures/target_working_state.png')]
if DealPicture.find_photo_center(click_photo, 1):
operation.click_util(click_photo, lambda: DealPicture.find_any_photos(stop_photos))
# else:
# print("don't find picture", name)
priority_list = {'1': [], '2': [], '3': [], '4': [], '5': []}
if current_position == 'producing_station':
# 获取制造站的
continue_shot = True
drag_photo = cv2.imread('res/pictures/confirmbtn.png')
position1 = DealPicture.find_photo_center(drag_photo)
find_photo = cv2.imread('res/pictures/clear_options.png')
position2 = DealPicture.find_photo_center(find_photo)
if current_produce == 'experience':
# 获取经验值的
# 截图,获取当前干员列表图片
while continue_shot:
target_photo = [cv2.imread('res/pictures/good_mood.png'), cv2.imread('res/pictures/common_mood.png')]
result_photo = DealPicture.find_operator_rectangle(target_photo)
continue_shot = DealPicture.class_experience_priority(result_photo, priority_list)
operation.drag_once(drag_photo, position2.x - position1.x, 0, 0, -200)
elif current_produce == 'material':
# 获取金属材料的
# 截图,获取当前干员列表图片
while continue_shot:
target_photo = [cv2.imread('res/pictures/good_mood.png'), cv2.imread('res/pictures/common_mood.png')]
result_photo = DealPicture.find_operator_rectangle(target_photo)
continue_shot = DealPicture.class_material_priority(result_photo, priority_list)
operation.drag_once(drag_photo, position2.x - position1.x, 0, 0, -200)
if current_produce == 'trading_station':
# 获取交易站的
continue_shot = True
drag_photo = cv2.imread('res/pictures/confirmbtn.png')
position1 = DealPicture.find_photo_center(drag_photo)
find_photo = cv2.imread('res/pictures/clear_options.png')
position2 = DealPicture.find_photo_center(find_photo)
# 截图,获取当前干员列表图片
while continue_shot:
target_photo = [cv2.imread('res/pictures/good_mood.png'), cv2.imread('res/pictures/common_mood.png')]
result_photo = DealPicture.find_operator_rectangle(target_photo)
continue_shot = DealPicture.class_trading_priority(result_photo, priority_list)
operation.drag_once(drag_photo, position2.x - position1.x, 0, 0, -200)
click_operator_by_priority(priority_list)
def change():
pass
Loading…
Cancel
Save