Nanpy Servo Control - python

*Nanpy allows for a Raspi to have an Arduino slave through python
Right now I'm having extreme difficulty in using the nanpy Servo package, and I cant get it to run correctly. I'm using it to make a robot that is wirelessly controlled from a computer, this is what I have for code:
from nanpy import (ArduinoApi, SerialManager)
import pygame
from nanpy import Servo
import time
pygame.init()
a=0
d=0
window = pygame.display.set_mode((800,600))
pygame.display.set_caption("Console")
try :
connection = SerialManager()
ard = ArduinoApi(connection = connection)
run = True
except:
print("Connection Failed!")
servoA = Servo(2)
servoD = Servo(4)
while run :
for event in pygame.event.get():
keys = pygame.key.get_pressed()
# if (event.type==pygame.KEYDOWN):
if keys[pygame.K_s] and keys[pygame.K_a]:
a=a-1
servoA.write(a)
elif keys[pygame.K_s] and keys[pygame.K_d]:
d=d-1
servoD.write(d)
elif keys[pygame.K_w]:
a=a+1
d=d+1
servoD.write(d)
servoA.write(a)
elif keys[pygame.K_s]:
a=a-1
d=d-1
servoD.write(d)
servoA.write(a)
elif keys[pygame.K_d]:
d=d+1
servoD.write(d)
elif keys[pygame.K_a]:
a=a+1
servoA.write(a)
elif keys[pygame.K_t]:
run=False
pygame.quit()
This is the error the python shell throws:
Traceback (most recent call last):
File "/home/pi/Desktop/nanpy/RobotCode.py", line 28, in <module>
servoA = Servo(2)
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/servo.py", line 9, in __init__
self.id = self.call('new', pin)
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/arduinoboard.py", line 150, in call
return _call(self.namespace, self.id, args, self.connection)
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/arduinoboard.py", line 47, in _call
ret = return_value(connection)
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/arduinoboard.py", line 18, in return_value
return serial_manager.readline().replace('\r\n', '')
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/serialmanager.py", line 101, in readline
raise SerialManagerError('Serial timeout!')
nanpy.serialmanager.SerialManagerError: Serial timeout!
How can I fix this, and/or what am I doing wrong?

You need to specify the port of the Arduino. So could you try:
connection = SerialManager(device='/dev/ttyACM0')
or whatever port you are using.

update the configuration file to use the servo and upload it to arduino using the IDE then run this program.
you can find the cfg.h file in nanpy-firmware/nanpy folder.

Related

Python error when trying to destroy an object in Ursina

I'm pretty new to coding in python but I have started a small little script. Its a first person shooter and right now I'm working on ammo boxes you can pick up. This is the code:
from ursina import *
from random import uniform
from ursina.shaders import lit_with_shadows_shader
from ursina.prefabs.first_person_controller import FirstPersonController
app = Ursina()
Entity.default_shader = lit_with_shadows_shader
player = FirstPersonController(model='cube', color=color.orange, origin_y=-.5, speed=8, position = (-52, 0, 57))
player.collider = BoxCollider(player, Vec3(0,1,0))
player.visible = False
ammo = 10
editor_camera = EditorCamera(enabled=False, ignore_paused=True)
ammoCounter = Text(text= ammo + ammo, position = (-0.4,-0.4), color = color.black)
def update():
ammoCounter.text = ammo
def pause_input(key):
if key == 'tab': # press tab to toggle edit/play mode
editor_camera.position = player.position
editor_camera.rotation = (90,180,0)
editor_camera.y = 50
editor_camera.enabled = not editor_camera.enabled
player.visible =True
player.visible_self = editor_camera.enabled
player.cursor.enabled = not editor_camera.enabled
gun.enabled = not editor_camera.enabled
mouse.locked = not editor_camera.enabled
application.paused = editor_camera.enabled
pause_handler = Entity(ignore_paused=True, input=pause_input)
def input(key):
global ammo
## destroy ammo crates##
if key == 'e':
if mouse.hovered_entity == ammo1:
if distance(player, ammo1) <= 5:
ammo += 10
destroy(ammo1)
if mouse.hovered_entity == ammo2:
if distance(player, ammo2) <= 5:
ammo += 10
destroy(ammo2)
if mouse.hovered_entity == ammo3:
if distance(player, ammo3) <= 5:
ammo += 10
destroy(ammo3)
if mouse.hovered_entity == ammo4:
if distance(player, ammo4) <= 5:
ammo += 10
destroy(ammo4)
if key == 'k':
print (player.position)
print (ammo)
if key=="left mouse down" and ammo > 0:
ammo -= 1
if mouse.hovered_entity and hasattr(mouse.hovered_entity, 'hp'):
mouse.hovered_entity.hp -= 10
mouse.hovered_entity.blink(color.red)
print (ammo)
Audio("gunshot")
if gun.position == (0.45,-0.2,0):
Animation("spark", parent=camera.ui, fps=5, scale=.15, position=(0.28, -0.01), loop=False)
print (ammo)
if gun.position == (0,-0.15,0):
Animation("spark", parent=camera.ui, fps=5, scale=.15, position=(-0.005,0.08,0), loop=False)
print (ammo)
if held_keys["q"]:
gun.position = (0,-0.15,0)
gun.rotation = (0,0,0)
Cursor = False
player.speed = 1
if held_keys["shift"]:
player.speed = 100
else:
gun.position = (0.45,-0.2,0)
gun.rotation = (5,30,0)
player.speed = 250 * time.dt
if held_keys["shift"]:
player.speed = 400 * time.dt
## ammo refill class#
class AmmoR(Entity):
def __init__(self, **kwargs):
super().__init__(model='cube', texture = 'ammobox', scale = 1, origin_y=-0.5, collider = "mesh", **kwargs)
## amount of amo refill boxes##
ammo1 = AmmoR()
ammo2 = AmmoR()
ammo3 = AmmoR()
ammo4 = AmmoR()
ammo1.position = (-9,2,53)
ammo2.position = (50,1,21)
ammo3.position = (-17,0,31)
ammo4.position = (15,0,8)
class Enemy(Entity):
def __init__(self, **kwargs):
super().__init__(model='cube', scale_y=2, origin_y=-0.5, color=color.light_gray, collider='box', **kwargs)
self.health_bar = Entity(parent=self, y=1.2, model='cube', color=color.red, world_scale=(1.5,.1,.1))
self.max_hp = 100
self.hp = self.max_hp
def update(self):
dist = distance_xz(player.position, self.position)
if dist > 40:
return
self.health_bar.alpha = max(0, self.health_bar.alpha - time.dt)
self.look_at_2d(player.position, 'y')
hit_info = raycast(self.world_position + Vec3(0,1,0), self.forward, 30, ignore=(self,))
if hit_info.entity == player:
if dist > 1:
self.position += self.forward * time.dt * 5
#property
def hp(self):
return self._hp
#hp.setter
def hp(self, value):
self._hp = value
if value <= 0:
destroy(self)
return
self.health_bar.world_scale_x = self.hp / self.max_hp * 1.5
self.health_bar.alpha = 1
## ENEMYS FIRST LEVEL
enemie1 = Enemy()
enemie2 = Enemy()
enemie3 = Enemy()
enemie4 = Enemy()
enemie5 = Enemy()
enemie6 = Enemy()
enemie7 = Enemy()
enemie8 = Enemy()
enemie9 = Enemy()
enemie10 = Enemy()
enemie11 = Enemy()
enemie1.position = (10,0,-2)
enemie2.position = (51.9096, 0, -57.6378)
enemie3.position = (53.7879, 0, -57.4827)
enemie4.position = (53.5366, 0, -39.0536)
enemie5.position = (50,0,-2)
enemie6.position = (50,0,-5)
enemie7.position = (22,0,-20)
enemie8.position = (55,0,-4)
enemie9.position = (15,0,-2)
Sky()
maze=Entity(model="maze", scale=10, texture="BK", color= color.gold,collider="mesh")
gun=Entity(model="colt", parent=camera.ui, scale=0.07, texture='tx', position=(0.45,-0.2,0), rotation=(5,30,0))
app.run()
The AmmoR class is the class for the ammo boxes and ammo1,ammo2,ammo3,and ammo4 are the ammo boxes. When I go to pick up the ammo boxes it works fine but when I try to pick up ammo2 Ursina Crashes giving me this error:
(3 aux display modules not yet loaded.)
:prc(warning): changing default value for ConfigVariable paste-emit-keystrokes from '1' to '0'.
:pnmimage:png(warning): iCCP: known incorrect sRGB profile
read obj at: c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\models_compressed\maze.obj
read obj at: c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\models_compressed\colt.obj
info: psd-tools3 not installed
warning: missing texture: 'tx'
screen resolution: (1920, 1080)
os: Windows
development mode: True
application successfully started
info: changed aspect ratio: 1.778 -> 1.778
PS C:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game> c:; cd 'c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game'; & 'C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\python.exe' 'c:\Users\MoerkerkeThomas\.vscode\extensions\ms-python.python-2022.18.2\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher' '50586' '--' 'c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\main game fps.py'
package_folder: C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina
asset_folder: c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game
:prc(warning): Invalid integer value for ConfigVariable win-size: 864.0
:prc(warning): Invalid integer value for ConfigVariable win-size: 1536.0
Known pipe types:
wglGraphicsPipe
(3 aux display modules not yet loaded.)
:prc(warning): changing default value for ConfigVariable paste-emit-keystrokes from '1' to '0'.
:pnmimage:png(warning): iCCP: known incorrect sRGB profile
read obj at: c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\models_compressed\maze.obj
read obj at: c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\models_compressed\colt.obj
info: psd-tools3 not installed
warning: missing texture: 'tx'
screen resolution: (1920, 1080)
os: Windows
development mode: True
application successfully started
info: changed aspect ratio: 1.778 -> 1.778
Assertion failed: !is_empty() at line 1045 of panda/src/pgraph/nodePath.cxx
Traceback (most recent call last):
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\EventManager.py", line 49, in eventLoopTask
self.doEvents()
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\EventManager.py", line 43, in doEvents
processFunc(dequeueFunc())
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\EventManager.py", line 99, in processEvent
messenger.send(eventName, paramList)
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\Messenger.py", line 337, in send
self.__dispatch(acceptorDict, event, sentArgs, foundWatch)
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\Messenger.py", line 422, in __dispatch
result = method (*(extraArgs + sentArgs))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\main.py", line 176, in input
__main__.input(key)
File "c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\main game fps.py", line 52, in input
if distance(player, ammo4) <= 5:
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\ursinamath.py", line 24, in distance
if hasattr(b, 'position'): b = b.position
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\entity.py", line 466, in position
return Vec3(*self.getPos())
^^^^^^^^^^^^^
AssertionError: !is_empty() at line 1045 of panda/src/pgraph/nodePath.cxx
:task(error): Exception occurred in PythonTask eventManager
Traceback (most recent call last):
File "c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\main game fps.py", line 197, in <module>
app.run()
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\main.py", line 237, in run
super().run()
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\ShowBase.py", line 3330, in run
self.taskMgr.run()
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\task\Task.py", line 553, in run
self.step()
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\task\Task.py", line 504, in step
self.mgr.poll()
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\EventManager.py", line 49, in eventLoopTask
self.doEvents()
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\EventManager.py", line 43, in doEvents
processFunc(dequeueFunc())
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\EventManager.py", line 99, in processEvent
messenger.send(eventName, paramList)
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\Messenger.py", line 337, in send
self.__dispatch(acceptorDict, event, sentArgs, foundWatch)
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\Messenger.py", line 422, in __dispatch
result = method (*(extraArgs + sentArgs))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\main.py", line 176, in input
__main__.input(key)
File "c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\main game fps.py", line 52, in input
if distance(player, ammo4) <= 5:
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\ursinamath.py", line 24, in distance
if hasattr(b, 'position'): b = b.position
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\entity.py", line 466, in position
return Vec3(*self.getPos())
^^^^^^^^^^^^^
AssertionError: !is_empty() at line 1045 of panda/src/pgraph/nodePath.cxx
PS C:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game>
I have tried changing the the if function to be structured differently but I think the statement is correct. The only thing I could think of being the issue is the distance between objects variable.

I have this error : raise turtle.Terminator

I hope it run and do not stop.
I'm making Conway's Game of Life,
if my code look stupid, please help me, I'm only 11.
I use the details from wiki, if it's wrong , please tell me.
Thankyou!
import turtle,random
START_POSITION=[]
def ReStart():
global START_POSITION
#START_POSITION.clear()
y=500
x=-500
for i in range(1,26):
for a in range(1,26):
START_POSITION.append(eval(f"({x},{y})"))
x+=20
x=(0-300)
y-=20
return True
ReStart()
screen=turtle.Screen()
class Cell:
def __init__(self):
self.cells=[]
self.make_body()
self.a()
self.Alive(screen)
def make_body(self):
global START_POSITION
for i in START_POSITION:
seg=turtle.Turtle(shape="square")
seg.color("White")
seg.penup()
seg.goto(i[0],i[1])
self.cells.append(seg)
The error saids:
Traceback (most recent call last):
File "C:/Users/****/Desktop/寫程式/the life game.py", line 145, in <module>
cell=Cell()
File "C:/Users/****/Desktop/寫程式/the life game.py", line 20, in __init__
self.make_body()
File "C:/Users/****/Desktop/寫程式/the life game.py", line 29, in make_body
seg.goto(i[0],i[1])
File "C:\Users\****\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 1777, in goto
self._goto(Vec2D(x, y))
File "C:\Users\****\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 3180, in _goto
self._update()
File "C:\Users\****\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 2661, in _update
self._update_data()
File "C:\Users\****\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 2647, in _update_data
self.screen._incrementudc()
File "C:\Users\****\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 1293, in _incrementudc
raise Terminator
turtle.Terminator
I'm totally stuck on this,please help me.
I've reworked your code fragment into what I believe you are trying to do. Avoid eval as it can cause endless problems. Your use of global in this context isn't valid. See if this works for you:
from turtle import Screen, Turtle
class Body:
def __init__(self, positions):
self.cells = []
self.make_body(positions)
# self.a()
# self.Alive(screen)
def make_body(self, positions):
for position in positions:
cell = Turtle(shape='square')
cell.fillcolor('white')
cell.penup()
cell.goto(position)
self.cells.append(cell)
def restart():
start_positions.clear()
y = 250
for _ in range(25):
x = -250
for _ in range(25):
start_positions.append((x, y))
x += 20
y -= 20
start_positions = []
screen = Screen()
screen.setup(550, 550)
screen.bgcolor('black')
screen.tracer(False)
restart()
my_body = Body(start_positions)
screen.tracer(True)
screen.exitonclick()
Since I've turned off tracer() for speed, call screen.update() whenever you're ready for the user to see the most recent changes.

Bot crashing from pyautogui

I am making a bot that makes the chrome dinosaur jump every time it sees a cactus.
The RGB for the cactus is (83,83,83)
I made a specific coordinate for my code to look at, and check if the RGB of that pixel matches the cactus (jump_place)
However, when I run it, it works for about 2 seconds, and then gives me this error:
Traceback (most recent call last):
File "c:\Users\dofia\OneDrive\Desktop\coding VS\Other Projects\DINO BOT\tempCodeRunnerFile.py", line 29, in <module>
if pyautogui.pixel(810, 635)[0] == 83:
File "C:\Users\dofia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pyscreeze\__init__.py", line 584, in pixel
return (r, g, b)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.496.0_x64__qbz5n2kfra8p0\lib\contextlib.py", line 124, in __exit__
next(self.gen)
File "C:\Users\dofia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pyscreeze\__init__.py", line 113, in __win32_openDC
raise WindowsError("windll.user32.ReleaseDC failed : return 0")
OSError: windll.user32.ReleaseDC failed : return 0
Here is my code:
from pyautogui import *
import pyautogui
import time
import keyboard
import random
time.sleep(3)
replay = (1127,591)
jump_place = (866,630)
def restart():
pyautogui.click(replay)
def jump():
pyautogui.keyDown('space')
time.sleep(0.5)
print("Jump!")
pyautogui.keyUp('space')
restart()
while keyboard.is_pressed('p') == False:
if pyautogui.pixel(810, 635)[0] == 83:
jump()
Is there anything I am doing wrong?
The link to the dinosaur game is: http://www.trex-game.skipser.com/

Error in Python Code 'Fatal Python Error: Segmentation Fault'

I have an error when I run my custom voice assistant program on Raspberry Pi 3B .This script is made from two programs from examples(assistant_library_demo.py and cloud_speech.py).Consequently the script does the both functions from those examples.
This is how the program code looks like:
import argparse
import locale
import logging
import RPi.GPIO as GPIO
from gpiozero import Servo
import signal
import sys
from google.assistant.library.event import EventType
from aiy.assistant import auth_helpers
from aiy.assistant.library import Assistant
from aiy.board import Board, Led
from aiy.cloudspeech import CloudSpeechClient
import aiy.voice.tts
def get_hints(language_code):
if language_code.startswith('en_'):
return ('turn on the light',
'turn off the light',
'blink the light',
'goodbye',
'repeat after me',
'lights on',
'lights off',
'minimum',
'middle',
'maximum')
return None
def locale_language():
language, _ = locale.getdefaultlocale()
return language
def process_event(led, event):
logging.basicConfig(level=logging.INFO)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(24,GPIO.OUT)
servo = Servo(6)
parser = argparse.ArgumentParser(description='Assistant service example.')
parser.add_argument('--language', default=locale_language())
args = parser.parse_args()
logging.info('Initializing for language %s...', args.language)
hints = get_hints(args.language)
client = CloudSpeechClient()
logging.info(event)
text = client.recognize(language_code=args.language,hint_phrases=hints)
if 'lights on' in text:
GPIO.output(24,GPIO.HIGH)
elif 'lights off' in text:
GPIO.output(24,GPIO.LOW)
elif 'maximum' in text:
servo.max()
elif 'minimum' in text:
servo.min()
elif 'middle' in text:
servo.mid()
if event.type == EventType.ON_START_FINISHED:
led.state = Led.BEACON_DARK # Ready.
logging.info('Say "OK, Google" then speak, or press Ctrl+C to quit...')
elif event.type == EventType.ON_CONVERSATION_TURN_STARTED:
led.state = Led.ON # Listening.
elif event.type == EventType.ON_END_OF_UTTERANCE:
led.state = Led.PULSE_QUICK # Thinking.
elif (event.type == EventType.ON_CONVERSATION_TURN_FINISHED
or event.type == EventType.ON_CONVERSATION_TURN_TIMEOUT
or event.type == EventType.ON_NO_RESPONSE):
led.state = Led.BEACON_DARK
elif event.type == EventType.ON_ASSISTANT_ERROR and event.args and
event.args['is_fatal']:
main()
def main():
credentials = auth_helpers.get_assistant_credentials()
with Board() as board, Assistant(credentials) as assistant:
for event in assistant.start():
process_event(board.led, event)
if name == 'main':
main()
This is how error text looks like:
The error text when i run the sketch from python shell:
Backend terminated (returncode: -11) Fatal Python error: Segmentation
fault
Thread 0x580fe470 (most recent call first):
File "/usr/lib/python3.5/threading.py", line 297 in wait File
"/usr/lib/python3.5/threading.py", line 549 in wait File
"/opt/aiy/projects-python/src/aiy/board.py", line 208 in _run File
"/usr/lib/python3.5/threading.py", line 862 in run File
"/usr/lib/python3.5/threading.py", line 914 in _bootstrap_inner File
"/usr/lib/python3.5/threading.py", line 882 in _bootstrap
Thread 0x76f66640 (most recent call first): File
"/usr/local/lib/python3.5/dist-packages-linux-armv7l/google/assistant/library/assistant.py", line 114 in exit File
"/opt/aiy/projects-python/src/examples/voice/myassistant.py", line 96
in main File
"/opt/aiy/projects-python/src/examples/voice/myassistant.py", line 99
in File "/usr/lib/python3/dist-packages/thonny/backend.py", line 1232
in _execute_prepared_user_code File
"/usr/lib/python3/dist-packages/thonny/backend.py", line 1158 in
wrapper File "/usr/lib/python3/dist-packages/thonny/backend.py", line
1171 in wrapper File
"/usr/lib/python3/dist-packages/thonny/backend.py", line 1219 in
execute_source File
"/usr/lib/python3/dist-packages/thonny/backend.py", line 853 in
_execute_source File "/usr/lib/python3/dist-packages/thonny/backend.py", line 840 in
_execute_file File "/usr/lib/python3/dist-packages/thonny/backend.py", line 400 in _cmd_Run File
"/usr/lib/python3/dist-packages/thonny/backend.py", line 217 in
handle_command File
"/usr/lib/python3/dist-packages/thonny/backend.py", line 162 in
mainloop File
"/usr/lib/python3/dist-packages/thonny/backend_launcher.py", line 70
in Use 'Stop/Restart' to restart the backend ...
The error text when I run the sketch from terminal:
Segmentation fault
I tried to search for this error in the web, but it gave no actual results. I hope you will help me to solve this issue.

"pygame.error: display Surface quit" while loading

So I'm making a game to test my programming skills and I'm trying to use pygame but when i try and load a level map it says the surface has quit. I have no idea why.
This is the load code:
def load(self):
print(os.listdir())
file = input('>>> file name = ')
try:
self.Dir = os.getcwd()
path = os.path.join(self.Dir, "maps", file)
data = pickle.load(open(path, 'rb'))
except OSError as error:
print('Not file ', path)
print(error)
else:
self.grid = data[0]
self.blocks = data[1]
Thanks in advance
EDIT:
this is the trace back
Traceback (most recent call last):
File "F:\PROGRAMS\snow\mapmaker_v2.py", line 169, in <module>
a.loop()
File "F:\PROGRAMS\snow\senpy.py", line 95, in loop
self.blocks.draw(self.screen)
File "F:\BMDSIT\Portable Python 3.2.5.1\App\lib\site-packages\pygame\sprite.py", line 475, in draw
self.spritedict[spr] = surface_blit(spr.image, spr.rect)
pygame.error: display Surface quit
EDIT 2:
This is the loop code where it happens:
(The load command is in the self.keyboard() function.)
def loop(self):
print('looping')
for event in pygame.event.get():
if event.type == pygame.QUIT:
print('quiting :(')
pygame.display.quit()
quit('User quit')
self.screen.fill((237, 237, 237))
self.keys = pygame.key.get_pressed()
self.mos = pygame.mouse.get_pressed()
self.mouse()
self.keyboard()
#screen.blit(player,player.pos)
self.blocks.draw(self.screen)
self.extraLoop()
pygame.display.flip()
print('done looping')
You can't pickle a Surface object.
If you want to pickle an object that contains a Surface, remove it before saving it to disk; and store the name of the image file or a string representation of the Surface instead in the object.

Categories