首页 > 编程语言 >python-Pygame 小游戏开发

python-Pygame 小游戏开发

时间:2023-04-04 18:45:23浏览次数:36  
标签:font Width python Height Start 小游戏 Pygame PWM pygame

AIServoPlatform

This Project is base on the raspberry hardware platform which be used for automatic face track and also person track filed in the future.

  1. AI Tech.
  2. Raspberry Programming.
  3. Hardware Update.

1. Stove Control Code

import pygame
from pygame.locals import *
import RPi.GPIO as GPIO
from sys import exit
import time
import sys
import os


if pygame.font is None:
    print("The font of pygame is not aviliable!")
    exit()
else:
    print("You can use the module named font!")

def show_text(surface_handle, pos, text, color, font_bold = False, font_size = 13, font_italic = False):
    cur_font = pygame.font.SysFont('arial', font_size)
    cur_font.set_bold(font_bold)
    cur_font.set_italic(font_italic)
    text_fmt = cur_font.render(text, 1, color)
    surface_handle.blit(text_fmt, pos)

PWM_Pinx = 14
PWM_Piny = 15
PWM_Frexy = 50
PWM_X_Duty = 5.0
PWM_Y_Duty = 5.0

GPIO.setmode(GPIO.BCM)
GPIO.setup(PWM_Pinx,GPIO.OUT)
GPIO.setup(PWM_Piny,GPIO.OUT)
GPIO.setwarnings(False)

px = GPIO.PWM(PWM_Pinx,PWM_Frexy)
py = GPIO.PWM(PWM_Piny,PWM_Frexy)

backgroundimage = 'background.jpg'
mouseimage = 'mouse.jpg'

pygame.init()
screen = pygame.display.set_mode((576, 576), 0, 32)
pygame.display.set_caption('Stove Control!')

background = pygame.image.load(backgroundimage).convert()
mouse_course = pygame.image.load(mouseimage).convert_alpha()

mouse_width_half = mouse_course.get_width()/2
mouse_height_half = mouse_course.get_height()/2
param1 = float(287.0)/90.0
param2 = float(10.0)/182.0

px.start(5.0)
py.start(5.0)

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
    screen.blit(background, (0, 0))
    x, y = pygame.mouse.get_pos()

    x -= mouse_width_half
    y -= mouse_height_half

    screen.blit(mouse_course, (x, y))
    
    V_degree = (float(y) - 286.0)/param1
    H_degree = (float(x) - 286.0)/param1

    text_pos = u"Position:(%.2f,%.2f)" % (V_degree, H_degree)
    # print(text_pos)
    show_text(screen,(410,10),text_pos,(0,0,255),False,13,True)
    pygame.display.update()

    PWM_X_Duty = 2.5+(H_degree+91-40)*param2
    PWM_Y_Duty = 2.5+(V_degree+91-40)*param2
    px.ChangeDutyCycle(PWM_X_Duty)
    py.ChangeDutyCycle(PWM_Y_Duty)

px.stop()
py.stop()
GPIO.cleanup()

2. Video RealTime Sample

# import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2

Height = 150
Width = 105
# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (Height,Width)
camera.framerate = 30
camera.hflip = False
camera.vflip = False
rawCapture = PiRGBArray(camera, size=(Height,Width))
# allow the camera to warmup
time.sleep(0.1)
# capture frames from the camera
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
	# grab the raw NumPy array representing the image, then initialize the timestamp
	# and occupied/unoccupied text
	image = frame.array
	# show the frame
	cv2.imshow("Frame",image)
	gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
	# cv2.imshow("Frame",gray)
	ret,mask = cv2.threshold(gray,175,255,cv2.THRESH_BINARY)
	# cv2.imshow("Frame", mask)
	
	Height,Width = mask.shape
	Start_Height = 0
	Start_Flag = 0
	Height_Count = 0
	Start_Width = Width-1
	NoPixel = 1

	for i in range(Height):
		for j in range(Width):
			if mask[i][j] != 0:
				if Start_Flag == 0:
					Start_Height = i
					Start_Flag = 1
				if Start_Width >j:
					Start_Width = j
				Height_Count = Height_Count + 1
				NoPixel = 0
				break
			else:
				NoPixel = 1
	print(Start_Height,Start_Width,Height_Count)
	Start_Height += Height_Count/2

	Position_One = [Start_Height,Start_Width+Height_Count/2]
	Position_Two = [Start_Height,Start_Width+Height_Count]
	Position_Thr = [Start_Height,Start_Width+Height_Count*3/2]

	Color_One = image[Position_One[0]][Position_One[1]]
	Color_Two = image[Position_Two[0]][Position_Two[1]]
	Color_Thr = image[Position_Thr[0]][Position_Thr[1]]
	print(Color_One)
	print(Color_Two)
	print(Color_Thr)
	
	key = cv2.waitKey(1) & 0xFF
	# clear the stream in preparation for the next frame
	rawCapture.truncate(0)
	# if the `q` key was pressed, break from the loop
	if key == ord("q"):
		break

AI Function

标签:font,Width,python,Height,Start,小游戏,Pygame,PWM,pygame
From: https://www.cnblogs.com/uestc-mm/p/9135096.html

相关文章

  • Python MySQL UsingGuide
    1.MySQLInstall2.MySQLBasicalTestDemonstrationimportpymysql.cursorsimporttime#ConnecttothedatabaseT1=time.time()connection=pymysql.connect(host='localhost',user='root',......
  • Python——Flask相关原理
    摘要主要是介绍的Flask的原理和实现。主要是的在python的开发中常用Flask的框架。本博文对Flask的原理和应用进行详细的学习和介绍。FlaskFlask本身相当于一个内核,其他几乎所有的功能都要用到扩展(邮件扩展Flask-Mail,用户认证Flask-Login,数据库Flask-SQLAIchemy),都需要用第三方的扩......
  • Python——异步编程案例
    摘要主要是讲解Python中的异步编程的下的实际的案例案例:异步操作redis案例:异步操作MySQL案例:FastAPl框架异步案例:异步爬虫课程总结......
  • python——异步编程代码实战
    摘要主要介绍python中相关的异步编程的原理和是代码的实战协程实现协程(Coroutine),也可以被称为微线程,是一种用户态内的上下文切换技术。简而言之,其实就是通过一个线程实现代码块相互切换执行。协程不是计算机提供,程序员人为创造。协程的优点:在一个线程中如果遇到IO等待时间,线程不......
  • Python——单元测试的实现
    摘要单元测试是用来对一个模块、一个函数或者一个类来进行正确性检验的测试工作。在软件开中的测试是很重要的一部分。python测试相关库unittest,内置库,模仿PyUnit写的,简洁易用,缺点是比较繁琐。nose,测试发现,发现并运行测试。pytest,笔者目前喜欢用这个,写起来很方便,并且很多知名开源项......
  • python PIL个人使用记录
    pythonPIL个人使用记录1、gif转pngdefgif_to_png(filename:str):"""gif图片一帧一帧转换为很多png图片:paramfilename::return:"""filename=filename.strip()filename=os.path.abspath(filename)assertos.path.s......
  • Python系列005
    控制设备仪器————电源初识importpyvisa#ConnecttotheGPIBinstrumentrm=pyvisa.ResourceManager()classPiDevice:def__init__(self,addressId):self.addressId=addressIddefPiPower(self):whoPower=rm.open_resource(self.a......
  • 学习笔记——Python基础
    字符串索引str='我是一名学生'print(str[0])#输出“我”print(str[-6])#输出“我”字符串切片:把数据对象的一部分拿出来str='我是一名学生'print(str[2:4])#输出“一名”print(str[-4:-2])#输出“一名”#获取字符串长度:len()str='我是一名学生'le......
  • 跟着查老四学Python Day 6:文件操作和异常处理
    文件操作例行寒暄之后,课程正式开始查老四:好的,我们来学习一下Python中的文件操作。文件操作是编程中非常基础和重要的一部分,它允许我们读取和写入文件。Python支持文本文件和二进制文件的读写,下面我们来逐一介绍。首先,我们需要打开一个文件。Python中使用open()函数来打开文件,它的语......
  • 【Python】ini解析ERROR:没有实例属性‘__getintem__’
    abaquspython搭配ini时,出现AttributeError:ConfigParserinstancehasnoattribute'getitem'20230404edit情况错误代码:fromConfigParserimportConfigParserconf=ConfigParser()conf.read(IniFilePath)layupFile=conf['DampCal']['lay......