Discuss Scratch

Redstone1080
Scratcher
1000+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

wvzack wrote:

My code that should make a newline is not working
time = datetime.now()
timestring = now.strftime("%d/%m/%Y %H:%M:%S")
notes = project.notes
project.set_notes(notes, + "/n", + timestring)
it returns
Traceback (most recent call last):
File "/home/pi/Python scripts/codestreamdowntime.py", line 12, in <module>
project.set_notes(notes, + "/n", + dt_string)
TypeError: bad operand type for unary +: 'str'
Don't use commas before the +, also the newline is \n, not /n

Maintainer of Snazzle | User of Linux (Fedora in particular) | Fan of Rockets
wvzack
Scratcher
500+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

Redstone1080 wrote:

wvzack wrote:

My code that should make a newline is not working
time = datetime.now()
timestring = now.strftime("%d/%m/%Y %H:%M:%S")
notes = project.notes
project.set_notes(notes, + "/n", + timestring)
it returns
Traceback (most recent call last):
File "/home/pi/Python scripts/codestreamdowntime.py", line 12, in <module>
project.set_notes(notes, + "/n", + dt_string)
TypeError: bad operand type for unary +: 'str'
Don't use commas before the +, also the newline is \n, not /n
thanks

Likes: Programing (python scratch Lua c++ I am bad at c++ a) Aiviation (B787 Queen of the sky F35) Mountain Biking and Messing around with computers (not a gamer at all)
My projects I am most happy with also the few “polished games I have:
Chiroyce
Scratcher
1000+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

wvzack wrote:

My code that should make a newline is not working
time = datetime.now()
timestring = now.strftime("%d/%m/%Y %H:%M:%S")
notes = project.notes
project.set_notes(notes, + "/n", + timestring)
it returns
Traceback (most recent call last):
File "/home/pi/Python scripts/codestreamdowntime.py", line 12, in <module>
project.set_notes(notes, + "/n", + dt_string)
TypeError: bad operand type for unary +: 'str'
the syntax is wrong, why is there a + after the comma? shouldn't it something like be this
project.set_notes(notes + "/n", dt_string)

Last edited by Chiroyce (Aug. 27, 2023 17:11:59)








April Fools' topics:
New Buildings in Scratch's headquarters
Give every Scratcher an M1 MacBook Air
Scratch should let users edit other Scratchers' projects
Make a statue for Jeffalo
Scratch Tech Tips™
Make a Chiroyce statue emoji


<img src=“x” onerror=“alert('XSS vulnerability discovered')”>

this is a test sentence
wvzack
Scratcher
500+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

Chiroyce wrote:

wvzack wrote:

My code that should make a newline is not working
time = datetime.now()
timestring = now.strftime("%d/%m/%Y %H:%M:%S")
notes = project.notes
project.set_notes(notes, + "/n", + timestring)
it returns
Traceback (most recent call last):
File "/home/pi/Python scripts/codestreamdowntime.py", line 12, in <module>
project.set_notes(notes, + "/n", + dt_string)
TypeError: bad operand type for unary +: 'str'
the syntax is wrong, why is there a + after the comma? shouldn't it something like be this
project.set_notes(notes + "/n", + dt_string)
yes i changed it now it works

Likes: Programing (python scratch Lua c++ I am bad at c++ a) Aiviation (B787 Queen of the sky F35) Mountain Biking and Messing around with computers (not a gamer at all)
My projects I am most happy with also the few “polished games I have:
LoIdesMio
Scratcher
100+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

wvzack wrote:

My code that should make a newline is not working
time = datetime.now()
timestring = now.strftime("%d/%m/%Y %H:%M:%S")
notes = project.notes
project.set_notes(notes, + "/n", + timestring)
it returns
Traceback (most recent call last):
File "/home/pi/Python scripts/codestreamdowntime.py", line 12, in <module>
project.set_notes(notes, + "/n", + dt_string)
TypeError: bad operand type for unary +: 'str'

Im not sure maybe try removing the , after notes and before the +

I make cloud Games! Using Scratchattach by @TimMcCool!
wvzack
Scratcher
500+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

LoIdesMio wrote:

wvzack wrote:

My code that should make a newline is not working
time = datetime.now()
timestring = now.strftime("%d/%m/%Y %H:%M:%S")
notes = project.notes
project.set_notes(notes, + "/n", + timestring)
it returns
Traceback (most recent call last):
File "/home/pi/Python scripts/codestreamdowntime.py", line 12, in <module>
project.set_notes(notes, + "/n", + dt_string)
TypeError: bad operand type for unary +: 'str'

Im not sure maybe try removing the , after notes and before the +
yeah i just chaged it that was the problem

Likes: Programing (python scratch Lua c++ I am bad at c++ a) Aiviation (B787 Queen of the sky F35) Mountain Biking and Messing around with computers (not a gamer at all)
My projects I am most happy with also the few “polished games I have:
wvzack
Scratcher
500+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

Sorry about asking again but i dont understand file saving with json hers what i have at the moment

open(“codestreamurl.json”, “w”) as f:
f.write(json.dumps(note))

thanks

Likes: Programing (python scratch Lua c++ I am bad at c++ a) Aiviation (B787 Queen of the sky F35) Mountain Biking and Messing around with computers (not a gamer at all)
My projects I am most happy with also the few “polished games I have:
rishi272011
Scratcher
99 posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

wvzack wrote:

Sorry about asking again but i dont understand file saving with json hers what i have at the moment

open(“codestreamurl.json”, “w”) as f:
f.write(json.dumps(note))

thanks
try putting a with before the open
like:
with open("codestreamurl.json", "w") as f:
    f.write(json.dumps(note))

you could also do:
with open("codestreamurl.json", "w") as f:
    json.dump(note, f)

Last edited by rishi272011 (Aug. 30, 2023 14:16:00)


__Falcon-Games__
Scratcher
1000+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

Corrected the post.

rishi272011 wrote:

wvzack wrote:

Sorry about asking again but i dont understand file saving with json hers what i have at the moment

open(“codestreamurl.json”, “w”) as f:
f.write(json.dumps(note))

thanks
try putting a with before the open
like:
with open("codestreamurl.json", "w") as f:
    f.write(json.dumps(note))

you could also do:
with open("codestreamurl.json", "w") as f:
    json.dump(note, f)

Try out Noml!
-cloudcoding-
Scratcher
1000+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

ajskateboarder wrote:

-RabbitWorld- wrote:

Is it possible to use python like php and store data? Make a login system?
If you want to use a markup language that works similar to PHP, try Flask (a Python web framework) with Jinja (the markup language).

Here's a primer on it: https://realpython.com/primer-on-jinja-templating/
I would highly recommend that primer

Last edited by kaj (Tomorrow 00:00:00)

-cloudcoding-

"[coding is] like clouds - always evolving and ready to transform!" - ChatGPT :)

Go check out my projects!
wvzack
Scratcher
500+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

rishi272011 wrote:

wvzack wrote:

Sorry about asking again but i dont understand file saving with json hers what i have at the moment

open(“codestreamurl.json”, “w”) as f:
f.write(json.dumps(note))

thanks
try putting a with before the open
like:
with open("codestreamurl.json", "w") as f:
    f.write(json.dumps(note))

you could also do:
with open("codestreamurl.json", "w") as f:
    json.dump(note, f)
i get a indentation error.

Likes: Programing (python scratch Lua c++ I am bad at c++ a) Aiviation (B787 Queen of the sky F35) Mountain Biking and Messing around with computers (not a gamer at all)
My projects I am most happy with also the few “polished games I have:
BobRocks20
Scratcher
100+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

Hi, sorry to interrupt the situation that's going on at the moment, but I have a question.

I'm a Python noob, and I've been using “Coding Projects in Python” by DK to grasp the basics. I have finished one of the programs there, “Starry Night.” However, I want to make it so you can draw a star wherever you click the mouse. The book talks about that briefly (pg. 97) but it doesn't go any further than to use the turtle.onScreenClick() function. How can I implement this function in my program?

I'd share my source code, but the book is All Rights Reserved and I'm worried that doing that would breach its copyright. I can tell you that if you have the book, you can find the code by going to page 205; my code is pretty much the same as in the book. Let me know if it's okay to share the code on here, and maybe I'll do just that.

Thank you for reading, and once again, I'm sorry to interrupt.

I quit Scratch, so I gave my signature to the kumquats.
rishi272011
Scratcher
99 posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

wvzack wrote:

rishi272011 wrote:

wvzack wrote:

Sorry about asking again but i dont understand file saving with json hers what i have at the moment

open(“codestreamurl.json”, “w”) as f:
f.write(json.dumps(note))

thanks
try putting a with before the open
like:
with open("codestreamurl.json", "w") as f:
    f.write(json.dumps(note))

you could also do:
with open("codestreamurl.json", "w") as f:
    json.dump(note, f)
i get a indentation error.

For me something like:
import json
note = {
    "test":"hello"
}#I dont know what is in here, this is just testing text
with open("codestreamurl.json", "w") as f:
    f.write(json.dumps(note))
works fine.

Try checking if all the indentations have four spaces.

Last edited by rishi272011 (Aug. 31, 2023 07:49:27)


-cloudcoding-
Scratcher
1000+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

BobRocks20 wrote:

I'd share my source code, but the book is All Rights Reserved and I'm worried that doing that would breach its copyright. I can tell you that if you have the book, you can find the code by going to page 205; my code is pretty much the same as in the book. Let me know if it's okay to share the code on here, and maybe I'll do just that.
as long as you change it which you slightly indicated when you said

BobRocks20 wrote:

my code is pretty much the same as in the book.
it should be fine

Last edited by kaj (Tomorrow 00:00:00)

-cloudcoding-

"[coding is] like clouds - always evolving and ready to transform!" - ChatGPT :)

Go check out my projects!
BobRocks20
Scratcher
100+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

-cloudcoding- wrote:

BobRocks20 wrote:

I'd share my source code, but the book is All Rights Reserved and I'm worried that doing that would breach its copyright. I can tell you that if you have the book, you can find the code by going to page 205; my code is pretty much the same as in the book. Let me know if it's okay to share the code on here, and maybe I'll do just that.
as long as you change it which you slightly indicated when you said

BobRocks20 wrote:

my code is pretty much the same as in the book.
it should be fine
Okay, I guess I'll do it then.
import turtle as t
from random import randint, random
def drawstar(points, size, color, x, y):
    t.penup()
    t.goto(x, y)
    t.pendown()
    angle = 180 - (180 / points)
    t.color(color)
    t.begin_fill()
    for i in range(points):
        t.forward(size)
        t.right(angle)
    t.end_fill()
# main!
t.hideturtle()
t.Screen().bgcolor('dark blue')
while True:
    ranPts = randint(2, 5) * 2 + 1
    ranSize = randint(10, 50)
    ranCol = (random(), random(), random())
    ranX = randint(-350, 300)
    ranY = randint(-250, 250)
    drawstar(ranPts, ranSize, ranCol, ranX, ranY)
As I said earlier, I'd like to know how I can use the function turtle.onScreenClick() in this program.

I quit Scratch, so I gave my signature to the kumquats.
wvzack
Scratcher
500+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

rishi272011 wrote:

wvzack wrote:

rishi272011 wrote:

wvzack wrote:

Sorry about asking again but i dont understand file saving with json hers what i have at the moment

open(“codestreamurl.json”, “w”) as f:
f.write(json.dumps(note))

thanks
try putting a with before the open
like:
with open("codestreamurl.json", "w") as f:
    f.write(json.dumps(note))

you could also do:
with open("codestreamurl.json", "w") as f:
    json.dump(note, f)
i get a indentation error.

For me something like:
import json
note = {
    "test":"hello"
}#I dont know what is in here, this is just testing text
with open("codestreamurl.json", "w") as f:
    f.write(json.dumps(note))
works fine.

Try checking if all the indentations have four spaces.
That fixed it thanks.

Likes: Programing (python scratch Lua c++ I am bad at c++ a) Aiviation (B787 Queen of the sky F35) Mountain Biking and Messing around with computers (not a gamer at all)
My projects I am most happy with also the few “polished games I have:
wvzack
Scratcher
500+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

Ok so i have made a script (more like 2) that will ping websites. It all works but i want it to be able to ping 2 websites. Here's my code that comunicats with scratch:
 import scratchattach as scratch3
import json
session = scratch3.login("username",  "passcode")
conn = session.connect_cloud("869257172") #replace with your project id
client = scratch3.CloudRequests(conn)
@client.request
def pingwebsite(argument1):
    with open("note.txt", "w") as f:
        try:
            old_note = f
            note = argument1
            note_json = str(old_note) + ", " + note
            f.write(note_json)
            return "Successfully dealt with request."
        except FileNotFoundError:
            return "The file does not exist."
        except Exception as error:
            return f"Error writing to file {error}"
def on_ready():
    print("Request handler is running")
client.run() #make sure this is ALWAYS at the bottom of your Python file
my other script that pings the website:

import io
import requests
def check_website(url):
    response = requests.get(url)
    if response.status_code == 200:
        return True
    else:
        return False
def main():
    with io.open("note.txt", "r") as f:
        note_text = f.read()
    note = note_text.strip()
    i = 1
    urlloop = None
    while i < note.count("http"):
        urlloop = str(note).split(",")[i]
        print("urlloop")
        i += 1
    if urlloop is not None:
        url = "http://" + urlloop
        is_up = check_website(url)
        if is_up:
            print("The website is up.")
        else:
            print("The website is down.")
if __name__ == "__main__":
    main()
I want this code to be able to ping multiple websites that are in the note.txt file any ideas on how this would work?

Likes: Programing (python scratch Lua c++ I am bad at c++ a) Aiviation (B787 Queen of the sky F35) Mountain Biking and Messing around with computers (not a gamer at all)
My projects I am most happy with also the few “polished games I have:
MonkeyBean2
Scratcher
100+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

Air_heads wrote:

MonkeyBean2 wrote:

I'm working on a minecraft renderer, and eventually fully featured client in scratch, and since I'm too lazy gzip in scratch would probably be too slow, and I don't want to try connecting over cloud variables yet, I've decided to write a “simple” (more like apocalyptic spaghetti mess) proxy in python to proxy websocket connections from a js script interacting with the scratch project to the raw tcp minecraft server (and the other way around too) (btw I would still need a very similar proxy if I had chosen to use cloud variables now), but unfortunately I get an error when I call sock.recvfrom(2097151) from inside a asyncio task.

Apart from proxying, the proxy does two things:
- Split up and combine chunks of the tcp stream to get individual minecraft packets
- Handle compression


Here's the error:
Task exception was never retrieved
future: <Task finished name='Task-8' coro=<serverToClient() done, defined at proxy/proxy.py:106> exception=OSError(9, 'Bad file descriptor')>
Traceback (most recent call last):
File "proxy/proxy.py", line 107, in serverToClient
tcp2web(sock, websocket, statestuff)
File "proxy/proxy.py", line 34, in tcp2web
data, thing = sock.recvfrom(2097151)
OSError: [Errno 9] Bad file descriptor

And here's my code:
proxy/main.py:
... snip ...

I don't think you need lib.py, as it doesn't have anything that directly interacts with the socket - it's just a library of helper functions.

“A socket can not be reused once the connection is closed, i.e. you can not call socket.connect() on a closed socket.” - Random stackoverflow post | You need to create a new socket every time the connection is closed.
ah, looking at this again, I immediately have a feeling it might have to do with making the socket, and then passing it to an async function… idk though as I've done a similar thing before and it worked…


9NAwRfSR-%dWFS$a$g&zBMTj2?;jvS?L5%^X%qpCX|A<*paJ=lU07c)wmt$v{TxL5



scratchGui.timeTravel.year = '2020'
rishi272011
Scratcher
99 posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

Hello, I was making a game in pygame, which uses tkinter for selecting the seed. I was making a prototype when i encountered a problem.
def askseed(self, initvalue):
        def askseed(self, initvalue):
        root = tkinter.Tk()
        root.title("Seed")
        root.geometry("400x300")
        root.resizable(False, False)
        seedvar = tkinter.IntVar()
        _seed = initvalue
        def submit():
            global _seed
            _seed = str(seedvar.get())
            print("test1", _seed)
            seedvar.set(0)
            # root.destroy()
            
        intro1 = tkinter.Label(root, text="New World", font=("Times", 16), justify='center').pack(anchor='center', side="top", pady=20)
        intro2 = tkinter.Label(root, text="Enter seed:", font=("Times", 14)).pack(pady=5)
        seed_entry = tkinter.Entry(root, textvariable = seedvar, font=('calibre',10,'normal')).pack(side="top", after=intro2, padx=20, pady=10)
        sub = tkinter.Button(root, text="          ok          ", command=submit).pack(pady=10)
        root.mainloop()
        # return askinteger(Main, text, initialvalue=initvalue)
        print("test2", _seed)
        return _seed

How to i send the value from inside the submit() function inside the askseed function to the askseed function. The submit function is triggered by a button. [The init value is randomly chosen]

The result is:


pygame 2.5.0 (SDL 2.28.0, Python 3.10.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
test1 83
test2 163002 ⬅ original randomly chosen


rishi272011
Scratcher
99 posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

bump

Powered by DjangoBB