首页 > 分享 > python实现赛博宠物(纯代码无需素材)

python实现赛博宠物(纯代码无需素材)

1、创作背景

        今天如往常一样来上班,一进公司就看见财务小姐姐闷闷不乐,就走过去跟她聊天,她说她很想养一只小狗,但是家里面不同意,怕把家里弄得乱七八糟。看着小姐姐悲伤的样子,我恏大力最舍不得小姐姐不开熏,所以我恏大力就要出来帮助美丽的财务小姐姐咯。

2、技术选择

        Python             (对于目前的打工人来说,学会python真的是可以提高大部分的工作效率)

3、程序设计

        1.对于一个桌面小宠物来说,首先得有这只宠物的样式,但是如果用素材的话那可玩性就很低了,我这边的方法就是可以无素材独立创作宠物样式!!!

        首先先来写一个创建宠物样式的程序。【create_folders.py】

代码直接付给大家,注释都在代码中,各位可随意修改。

import os

from PIL import Image, ImageDraw

def create_folder_structure():

os.makedirs("images", exist_ok=True)

def create_dog_image(filename, is_sleeping=False, is_walking=False, is_happy=False, is_eating=False, frame=1):

img = Image.new('RGBA', (128, 128), (0, 0, 0, 0))

draw = ImageDraw.Draw(img)

white = (255, 255, 255)

pink = (255, 218, 233)

black = (0, 0, 0)

if is_sleeping:

draw.ellipse([40, 70, 90, 95], fill=white)

draw.ellipse([85, 65, 95, 75], fill=white)

draw.ellipse([25, 60, 60, 90], fill=white)

draw.ellipse([30, 55, 45, 70], fill=white)

draw.ellipse([35, 58, 42, 67], fill=pink)

draw.ellipse([40, 55, 55, 70], fill=white)

draw.ellipse([45, 58, 52, 67], fill=pink)

draw.line([35, 75, 40, 75], fill=black, width=2)

draw.line([45, 75, 50, 75], fill=black, width=2)

draw.ellipse([40, 78, 45, 83], fill=black)

draw.ellipse([45, 90, 55, 98], fill=white)

draw.ellipse([75, 90, 85, 98], fill=white)

else:

draw.ellipse([45, 60, 85, 90], fill=white)

if frame == 1:

draw.arc([75, 45, 95, 65], 0, 180, fill=white, width=4)

else:

draw.arc([75, 45, 95, 65], -30, 150, fill=white, width=4)

if is_walking:

if frame == 1:

draw.ellipse([50, 85, 60, 100], fill=white)

draw.ellipse([70, 88, 80, 103], fill=white)

else:

draw.ellipse([50, 88, 60, 103], fill=white)

draw.ellipse([70, 85, 80, 100], fill=white)

else:

draw.ellipse([50, 85, 60, 100], fill=white)

draw.ellipse([70, 85, 80, 100], fill=white)

draw.ellipse([30, 45, 65, 75], fill=white)

draw.ellipse([35, 35, 50, 50], fill=white)

draw.ellipse([38, 38, 47, 47], fill=pink)

draw.ellipse([45, 35, 60, 50], fill=white)

draw.ellipse([48, 38, 57, 47], fill=pink)

draw.ellipse([38, 55, 43, 60], fill=black)

draw.ellipse([52, 55, 57, 60], fill=black)

draw.ellipse([45, 62, 50, 67], fill=black)

draw.arc([40, 62, 55, 72], 0, 180, fill=black, width=1)

if is_happy:

draw.ellipse([45, 60, 85, 90], fill=white)

if frame == 1:

draw.arc([75, 40, 95, 65], -30, 150, fill=white, width=4)

else:

draw.arc([75, 45, 95, 70], 30, 210, fill=white, width=4)

draw.arc([38, 55, 43, 60], 0, 180, fill=black, width=2)

draw.arc([52, 55, 57, 60], 0, 180, fill=black, width=2)

draw.arc([40, 62, 55, 72], 0, 180, fill=black, width=2)

elif is_eating:

draw.ellipse([45, 60, 85, 90], fill=white)

draw.ellipse([30, 55, 65, 85], fill=white)

if frame == 1:

draw.arc([40, 70, 55, 80], 0, 180, fill=black, width=2)

else:

draw.arc([40, 70, 55, 80], 30, 150, fill=black, width=2)

img.save(f"images/{filename}")

create_dog_image("normal_1.png", frame=1)

create_dog_image("normal_2.png", frame=2)

create_dog_image("sleep_1.png", is_sleeping=True, frame=1)

create_dog_image("sleep_2.png", is_sleeping=True, frame=2)

create_dog_image("walk_1.png", is_walking=True, frame=1)

create_dog_image("walk_2.png", is_walking=True, frame=2)

create_dog_image("happy_1.png", is_happy=True, frame=1)

create_dog_image("happy_2.png", is_happy=True, frame=2)

create_dog_image("eat_1.png", is_eating=True, frame=1)

create_dog_image("eat_2.png", is_eating=True, frame=2)

if __name__ == "__main__":

create_folder_structure()

print("文件夹和小狗图片创建完成!")

        好的,这段程序运行后就会在当前目录下生成一个images文件夹来存放生成的素材。 

        我设置的小狗样式就是这个样子的,大家可以发挥自己的想法设计自己的宠物,可以在评论区分享各位的宠物样式。

4、主程序

        2.然后现在开始实现主程序设计,主要是包括宠物自身的动作,然后活动的范围,以及与人的互动过程。

        代码依旧附下:(注释都在代码中)

import sys

import random

from PyQt5.QtWidgets import (QApplication, QMainWindow, QLabel, QMenu,

QSystemTrayIcon, QAction, QMessageBox)

from PyQt5.QtCore import Qt, QTimer, QPoint

from PyQt5.QtGui import QPixmap, QIcon

class DesktopPet(QMainWindow):

def __init__(self):

super().__init__()

self.is_following_mouse = False

self.is_sleeping = False

self.current_action = "normal"

self.animations = {}

try:

self.animations = {

"normal": [

self.load_and_verify_image("images/normal_1.png"),

self.load_and_verify_image("images/normal_2.png")

],

"sleeping": [

self.load_and_verify_image("images/sleep_1.png"),

self.load_and_verify_image("images/sleep_2.png")

],

"walking": [

self.load_and_verify_image("images/walk_1.png"),

self.load_and_verify_image("images/walk_2.png")

],

"happy": [

self.load_and_verify_image("images/happy_1.png"),

self.load_and_verify_image("images/happy_2.png")

],

"eating": [

self.load_and_verify_image("images/eat_1.png"),

self.load_and_verify_image("images/eat_2.png")

]

}

except Exception as e:

print(f"加载图片时出错: {e}")

sys.exit(1)

self.current_frame = 0

self.initUI()

self.setupTimers()

self.screen = QApplication.primaryScreen().geometry()

self.movement_area = {

'left': self.screen.width() // 2,

'top': 0,

'right': self.screen.width(),

'bottom': self.screen.height() // 2

}

self.movement_timer = QTimer(self)

self.movement_timer.timeout.connect(self.auto_move)

self.movement_timer.start(3000)

self.target_pos = None

self.is_dragging = False

self.is_happy = False

self.pet_mood = 100

self.energy = 100

self.status_timer = QTimer(self)

self.status_timer.timeout.connect(self.update_status)

self.status_timer.start(10000)

def initUI(self):

self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.SubWindow)

self.setAttribute(Qt.WA_TranslucentBackground)

self.pet_label = QLabel(self)

self.pet_label.setPixmap(self.animations["normal"][0])

self.pet_label.setFixedSize(128, 128)

self.pet_label.move(0, 0)

self.resize(self.pet_label.size())

self.create_tray_icon()

self.show()

def setupTimers(self):

self.animation_timer = QTimer(self)

self.animation_timer.timeout.connect(self.update_animation)

self.animation_timer.start(16)

self.action_timer = QTimer(self)

self.action_timer.timeout.connect(self.random_action)

self.action_timer.start(5000)

def create_tray_icon(self):

self.tray_icon = QSystemTrayIcon(self)

self.tray_icon.setIcon(QIcon(self.animations["normal"][0]))

tray_menu = QMenu()

action_wake = QAction("唤醒", self)

action_wake.triggered.connect(self.wake_up)

action_sleep = QAction("睡觉", self)

action_sleep.triggered.connect(self.sleep)

action_quit = QAction("退出", self)

action_quit.triggered.connect(QApplication.quit)

action_feed = QAction("喂食", self)

action_feed.triggered.connect(self.feed)

action_pat = QAction("摸摸头", self)

action_pat.triggered.connect(self.pat)

action_status = QAction("查看状态", self)

action_status.triggered.connect(self.show_status)

tray_menu.addAction(action_wake)

tray_menu.addAction(action_sleep)

tray_menu.addAction(action_quit)

tray_menu.addAction(action_feed)

tray_menu.addAction(action_pat)

tray_menu.addAction(action_status)

tray_menu.addSeparator()

self.tray_icon.setContextMenu(tray_menu)

self.tray_icon.show()

def update_animation(self):

"""更新动画帧"""

print(f"当前动作: {self.current_action}, 当前帧: {self.current_frame}")

if not self.is_sleeping:

animations = self.animations[self.current_action]

self.current_frame = (self.current_frame + 1) % len(animations)

pixmap = animations[self.current_frame]

if pixmap.width() != 128 or pixmap.height() != 128:

pixmap = pixmap.scaled(128, 128, Qt.KeepAspectRatio, Qt.SmoothTransformation)

self.pet_label.setPixmap(pixmap)

else:

self.pet_label.setPixmap(self.animations["sleeping"][0])

def random_action(self):

if not self.is_sleeping and not self.is_following_mouse:

if self.energy < 30:

self.sleep()

elif self.pet_mood < 30:

if random.random() < 0.3:

self.sleep()

else:

actions = ["normal", "walking"]

self.current_action = random.choice(actions)

if self.current_action == "walking":

self.random_walk()

def random_walk(self):

if self.current_action == "walking":

current_pos = self.pos()

random_x = max(self.movement_area['left'],

min(self.movement_area['right'] - self.width(),

current_pos.x() + random.randint(-30, 30)))

random_y = max(self.movement_area['top'],

min(self.movement_area['bottom'] - self.height(),

current_pos.y() + random.randint(-30, 30)))

self.move(random_x, random_y)

def sleep(self):

print("进入睡觉状态")

self.is_sleeping = True

self.current_action = "sleeping"

self.update_animation()

def wake_up(self):

self.is_sleeping = False

self.current_action = "normal"

def mousePressEvent(self, event):

if event.button() == Qt.LeftButton:

self.is_dragging = True

self.dragPosition = event.globalPos() - self.frameGeometry().topLeft()

if self.energy > 30:

self.current_action = "happy"

event.accept()

elif event.button() == Qt.RightButton:

self.tray_icon.contextMenu().exec_(event.globalPos())

def mouseMoveEvent(self, event):

if event.buttons() == Qt.LeftButton:

self.move(event.globalPos() - self.dragPosition)

self.current_action = "walking"

event.accept()

def mouseDoubleClickEvent(self, event):

if event.button() == Qt.LeftButton:

if self.is_sleeping:

self.wake_up()

else:

self.sleep()

def auto_move(self):

"""自动在区域内移动"""

if not self.is_sleeping and self.current_action != "walking":

target_x = random.randint(

self.movement_area['left'],

self.movement_area['right'] - self.width()

)

target_y = random.randint(

self.movement_area['top'],

self.movement_area['bottom'] - self.height()

)

self.target_pos = QPoint(target_x, target_y)

self.current_action = "walking"

self.start_movement_animation()

def start_movement_animation(self):

"""创建平滑移动动画"""

if self.target_pos:

current_pos = self.pos()

dx = self.target_pos.x() - current_pos.x()

dy = self.target_pos.y() - current_pos.y()

step = 5

distance = (dx**2 + dy**2)**0.5

if distance > step:

dx = dx / distance * step

dy = dy / distance * step

new_x = current_pos.x() + dx

new_y = current_pos.y() + dy

self.move(int(new_x), int(new_y))

QTimer.singleShot(50, self.start_movement_animation)

else:

self.move(self.target_pos)

self.target_pos = None

self.current_action = "normal"

def set_movement_area(self, left, top, right, bottom):

"""设置活动范围"""

self.movement_area = {

'left': max(0, left),

'top': max(0, top),

'right': min(self.screen.width(), right),

'bottom': min(self.screen.height(), bottom)

}

def load_and_verify_image(self, path):

"""加载并验证图片"""

pixmap = QPixmap(path)

if pixmap.isNull():

raise Exception(f"无法加载图片: {path}")

return pixmap

def update_status(self):

"""定期更新宠物状态"""

if not self.is_sleeping:

self.energy -= 1

if self.energy < 30:

self.pet_mood -= 2

if self.pet_mood < 0:

self.pet_mood = 0

if self.energy < 0:

self.energy = 0

self.sleep()

def feed(self):

"""喂食"""

if not self.is_sleeping:

self.current_action = "eating"

self.energy = min(100, self.energy + 30)

self.pet_mood = min(100, self.pet_mood + 10)

QTimer.singleShot(2000, self.back_to_normal)

def pat(self):

"""摸头"""

if not self.is_sleeping:

self.current_action = "happy"

self.pet_mood = min(100, self.pet_mood + 15)

QTimer.singleShot(2000, self.back_to_normal)

def back_to_normal(self):

"""恢复正常状态"""

if not self.is_sleeping:

self.current_action = "normal"

def show_status(self):

"""显示状态信息"""

status = f"心情值: {self.pet_mood}%n能量值: {self.energy}%"

QMessageBox.information(self, "宠物状态", status)

def mouseReleaseEvent(self, event):

if event.button() == Qt.LeftButton:

self.is_dragging = False

if not self.is_sleeping:

self.current_action = "normal"

if __name__ == '__main__':

app = QApplication(sys.argv)

pet = DesktopPet()

screen = app.primaryScreen().geometry()

pet.set_movement_area(

screen.width() // 2,

screen.height() // 2,

screen.width(),

screen.height()

)

sys.exit(app.exec_())

        在运行代码前一定先安装一下代码中所需的库文件,然后将文件路径设置好,直接运行即可。无素材纯代码。

        各位也可以做完之后打包起来发给你的小姐姐们,也算是你们共同创造的一个小生命哦!

相关知识

Python实现桌面挂件,做一只可爱的桌面宠物~
用Python实现自制桌面宠物,变出一个桌面小挂件
【附源码】教你用Python代码制作一只你的专属宠物,桌面体验感升级100%!!
【Python程序】用200行Python代码制作有趣的桌面宠物(源码可分享),大打工人解压放松程序,如何用Python制作一个桌面宠物!
【附源码】用Python代码,制作出一只专属桌面宠物,确定不来一只?保姆级教程,小白也能学会!!
Python实现宠物医院基础功能
python 练习题
【Python教程】教你用Python代码制作一个桌面宠物,专属桌宠,体验感升级1000%(附源码)
Python宠物美容项目预约服务管理系统设计与实现
在Sublime Text 3上实现python交互功能(SublimeREPL插件安装)

网址: python实现赛博宠物(纯代码无需素材) https://m.mcbbbk.com/newsview560243.html

所属分类:萌宠日常
上一篇: 狗狗排行榜前10强 狗狗排行榜大
下一篇: 如何预防宠物狗狗寄生虫?(全面了