Home Backend Development Python Tutorial Writing game scripts in Python turns out to be so easy

Writing game scripts in Python turns out to be so easy

Apr 13, 2023 am 10:04 AM
python Script game

Preface

I have been playing Princess Connect recently. I have also played games like Onmyoji before. Such games will have an initial number like this. Something, or something that can be eaten.

Of course, as a programmer, things like liver can be completed automatically for us by writing code. The game script is actually not advanced. The easiest way to experience it is to download an Airtest, just take a few pictures, write a few layers of code, and then you can play the game according to your own logic.

Writing game scripts in Python turns out to be so easy

Of course, this article is not about how to use Airtest, but about using the original python opencv to implement the above operations.

In the past two days, I wrote a program for Princess Link to get the initial account. I can’t be considered a veteran in writing game scripts. This article is mainly to share some basic techniques and experience in using it.

Preparation work

First, we need to complete the following preparations.

One Android device: emulator or real device can be used.

Install ADB and add it to the system's PATH: adb is used to

Install tesseract-ocr and add it to the system's PATH: Help us achieve simple character recognition

Install versions of python3.7 or above

I have put adb and tesseract in Baidu network disk, and there is a recorded effect video in it.

Link: pan.baidu.com/s/1edTPu2o7… Extraction code: 33aw

python library installation

##pipinstall pillow pytesseract opencv-python copy code

In addition, you can install uiautomator2 if necessary. This article will not cover this knowledge.

Use adb to obtain an Android device

Here we mainly involve the ADB connection operation of a single Android device. First, we open the emulator.

Then we call adb devices to get the current Android device. Here is an emulator.

Writing game scripts in Python turns out to be so easy

Next, you can call adb shell to test whether you can enter the shell environment of the Android device, and confirm that you can enter exit to exit.

Writing game scripts in Python turns out to be so easy

#If sometimes you cannot enter the shell, you can call adb kill-server first, and then call adb devices.

Possibly commonly used ADB Shell commands

The following are some ADB command operations. Through the adb command, we can use python to operate Android devices.

Screenshot

The most common operation is to take a screenshot. First call screencap to take the screenshot and put it into the Android device, and then pull the screenshot down to computer.

def take_screenshot():
os.system("adb shell screencap -p /data/screenshot.png")
os.system("adb pull /data/screenshot.png ./tmp.png")
Copy after login

Drop-down file

The drop-down file is the adb pull just now. Taking Princess Link as an example, the following code can export the xml of account information , you can log in through xml in the future.

os.system(f"adb pull /data/data/tw.sonet.princessconnect/shared_prefs/tw.sonet.princessconnect.v2.playerprefs.xml ./user_info.xml")
Copy after login

Upload files

With the drop-down, uploading will naturally occur, which can be completed through adb push. Taking Princess Link as an example, the following code can complete account switching.

# 切换账号1
os.system("adb push ./user_info1.xml /data/data/tw.sonet.princessconnect/shared_prefs/tw.sonet.princessconnect.v2.playerprefs.xml")
# 切换账号2
os.system("adb push ./user_info2.xml /data/data/tw.sonet.princessconnect/shared_prefs/tw.sonet.princessconnect.v2.playerprefs.xml")
Copy after login

Click somewhere on the screen

def adb_click(center, offset=(0, 0)):
(x, y) = center
x += offset[0]
y += offset[1]
os.system(f"adb shell input tap {x} {y}")
Copy after login

Enter text


text = "YourPassword"
os.system(f"adb shell input text {text}")
Copy after login

Delete characters

Sometimes the input box will have input cache, and we need to delete characters.

# 删除10个字符
for i in range(10):
os.system("adb shell input keyevent 67")
Copy after login

Query the currently running package name and Activity

Through the following code, you can query the Activity of the currently running program, and you can also check the package by the way. name.

Writing game scripts in Python turns out to be so easy

##Stop an application Sometimes you need to stop an application and you need to provide the application's package name.

adb shell am force-stop tw.sonet.princessconnect
Copy after login

Opening an applicationTo open an application, you need to provide the package name and Activity.

adb shell am start -W -n tw.sonet.princessconnect/jp.co.cygames.activity.OverrideUnityActivity
Copy after login

图像操作

对于图像的操作第一就是图像查找了,比如说像Airtest提供的这种,无非就是判断某个图像在不在截屏中,在的话在什么位置。

Writing game scripts in Python turns out to be so easy

除此之外还需要一些抠图,比如说我们想获取账号的id,账号的等级,需要截取出一部分图片然后进行OCR操作。

Writing game scripts in Python turns out to be so easy

图像查找

图像查找其实就是先拿到两张图片,然后调用cv2.matchTemplate方法来查找是否存在以及位置,这里匹配是一个相对模糊的匹配,会有一个相似度的概率,最高是1。我们设定一个阈值来判断模板是否在截屏里即可。

这里截屏如下,文件名为tmp.png:

Writing game scripts in Python turns out to be so easy

模板如下:

Writing game scripts in Python turns out to be so easy

代码如下:

import cv2
def image_to_position(screen, template):
image_x, image_y = template.shape[:2]
result = cv2.matchTemplate(screen, template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
print("prob:", max_val)
if max_val > 0.98:
global center
center = (max_loc[0] + image_y / 2, max_loc[1] + image_x / 2)
return center
else:
return False
if __name__ == "__main__":
screen = cv2.imread('tmp.png')
template =cv2.imread('Xuandan.png')
print(image_to_position(screen, template))
Copy after login

运行上述代码后,可以看到模板匹配出来的概率为0.9977,位置为(1165, 693),对于一张图片,左上角为原点,因为我的分辨率是1280 * 720,那么右下角的坐标就是(1280, 720)。可以看到我们这个选单其实就是刚好在右下角的位置。

Writing game scripts in Python turns out to be so easy

如何快速裁剪模板?(win10)

游戏脚本其实并不是代码很难写,而是需要截很多的图,这些图要保证分辨率和原始一样。我发现在win10如果用画图打开图片

Writing game scripts in Python turns out to be so easy

可以保证使用QQ截屏出来的分辨率,和图片本身的分辨率一样。

Writing game scripts in Python turns out to be so easy

这个时候直接用qq截屏出来的模板即可直接用于识别。

图像裁剪

接下来就是有时候需要裁剪一些图像了,当然我们的模板图片也可以通过裁剪图片的方式得到,这样的模板图片是最准的。

裁剪其实就是需要裁剪的位置,以及需要的高度和宽度,说白了就是一篇长方形的区域,下面的代码使用PIL库实现。

from PIL import Image
def crop_screenshot(img_file, pos_x, pos_y, width, height, out_file):
img = Image.open(img_file)
region = (pos_x, pos_y, pos_x + width, pos_y + height)
cropImg = img.crop(region)
cropImg.save(out_file)
print("exported:", out_file)
if __name__ == "__main__":
crop_screenshot("tmp.png", 817,556, 190, 24, "test_id.png")
Copy after login

上面的代码以截取玩家的id为例。

Writing game scripts in Python turns out to be so easy

运行代码后,得到截图如下:

Writing game scripts in Python turns out to be so easy

简单的OCR

得到了以上的图片信息后就是进行OCR了,也就是光学字符识别。这里代码非常简单,只要调用API即可。


from PIL import Image
import pytesseract
image = Image.open('test_id.png')
content = pytesseract.image_to_string(image) # 识别图片
print(content)
Copy after login

Writing game scripts in Python turns out to be so easy

不过需要注意的一点就是pytesseract识别出来的结果会有空格符,换行符这样的符号,真正要用的时候进行一些字符的过滤即可。

The End

这篇文章到这里就结束了,主要还是介绍一些ADB以及图像相关的基础操作。谢谢大家的观看。

The above is the detailed content of Writing game scripts in Python turns out to be so easy. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles