I am trying to create cookie clicker in python. I have implemented an autoclicker, however, each time I click it adds another autoclicker - python-3.7

I am fairly new to python and I have challenged myself to create a cookie clicker like game using python and Tkinter. I have just implemented an autoclicker but I am having an issue where each time I click, another autoclicker is added.
I want it so that the user can continue to click, but when the auto clicker is activated, it will automatically add 1 click per second.
I have tried puting window.after(1000, nClick) on different lines as well as adjusting the value. I have tried making new functions but I just can't seem to get it working.
import sys
import random
import tkinter
import time
global counter
counter = 0
autoclicker = counter + 1
def nClick():
global counter
global autoclicker
counter += 1
mButton1.config(text = counter)
print(counter)
if counter >= 10:
autoclicker
window.after(1000, nClick)
window = tkinter.Tk()
# to rename the title of the window
window.title("GUI")
# pack is used to show the object in the window
mButton1 = tkinter.Button(text = counter, command = nClick, fg = "darkgreen", bg = "white")
mButton1.pack()
mButton1.config(font=("Courier", 44))
window.mainloop()
#input('Press ENTER to exit')
I expect the counter to automatically + 1 to counter after 10 clicks. It does this until the user clicks again where it automatically adds the click to the autoclicker

You need to separate out the things "user clicks to add a cookie", "autoclicker adds a cookie", and "turn autoclicker on/off", so there are clear places where those things happen. e.g.
import sys
import random
import tkinter
import time
global counter
counter = 0
autoclicker_enabled = False
# autoclicker gets its own function to call,
# which updates the counter,
# and calls itself
def autoClick():
global counter
counter += 1
mButton1.config(text = counter)
window.after(1000, autoClick)
def nClick():
global counter
global autoclicker_enabled
counter += 1
mButton1.config(text = counter)
print(counter)
if counter >= 10:
# autoclicker_enabled is a toggle,
# so autoclicker can only be enabled once.
# It starts the autoClick self-loop,
# and then sets itself so that won't happen again.
if not autoclicker_enabled:
window.after(1000, autoClick)
autoclicker_enabled = True
window = tkinter.Tk()
# to rename the title of the window
window.title("GUI")
# pack is used to show the object in the window
mButton1 = tkinter.Button(text = counter, command = nClick, fg = "darkgreen", bg = "white")
mButton1.pack()
mButton1.config(font=("Courier", 44))
window.mainloop()
You can then see that the autoClick function does not print the text as well, and that the counter increase and button text change code is repeated, and maybe move that out to its own function, which both clicks use..

Related

Saving synchronised 7T fMRI Triggers received via USB connected NNL SyncBox, on every TR and Task Response Keypress (PsychoPy)

I would like to get synchronised timings and number of triggers for each single pulse sent by the 7T MRI scanner together with each single SPACEBAR keypress as a participant’s response when particular letters (A, B, C, X, Y) are presented on the screen, also the stimulus start time with each corresponding trigger.
So far I have added a “Waiting for scanner” routine where I get the first pulse via USB connected NNL Synbox saved in the .csv data file but I want to save each single pulse (TR) and timings. Triggers are automatically emulated as letter ‘s’ sent by the NNL Synbox.
# Code component: Creat routine "Wait for Scanner"
text_wait = visual.TextStim(win=win, name='text_wait',
text='Waiting for scanner...',
font='Arial',
pos=(0, 0), height=0.8, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
#Set first MR Trigger
mr_trigger_number = [] # list for triggers
mr_trigger_time = [] # list for time of each trigger
ScannerKeyboard = keyboard.Keyboard() # set keyboard
count_mr_trigger = 0 # counts amount of MR scanner trigger, starts with zero
start_trigger = ScannerKeyboard.getKeys(keyList=['s'], waitRelease = False) # experiment starts with MR Scanner "s"
# Draw waiting Screen until "s" is sent from NNL Syncbox
while len(start_trigger) == 0: # if no trigger was sent show:
text_wait.draw() # Text "Waiting for scanner"
win.flip()
start_trigger = ScannerKeyboard.getKeys(keyList=['s'], waitRelease = False) # show text_wait until one "s" was received
# Get timing information and store trigger number
onset = core.getTime() # get Onset time of trigger
count_mr_trigger = count_mr_trigger + 1 # count MR Scanner trigger, add "1!
# Save time and number of MR Trigger
thisExp.addData('MR_trigger_time',onset) # save trigger time of onset
thisExp.addData('MR_trigger_number',count_mr_trigger)
And also I used the following code component in > Each Frame tab of 2 trials conditions to save the stimuli onset timings when a pulse 's' is received. This works fine but stimulus start time > stimulus_start_time = globalClock.getTime() - mr_trigger_time is saved based on first pulse only as I am unable to save each pulse timings.
#save stimulus onset time for two types of trial conditions
if trials.thisN == 0 and frameN == 0:
loop_start_time = globalClock.getTime() - mr_trigger_time
elif frameN == 1:
stimulus_start_time = globalClock.getTime() - mr_trigger_time
# store the data:
thisExp.addData('stimulus_start_time', stimulus_start_time)
if trials_2.thisN == 0 and frameN == 0:
loop_start_time = globalClock.getTime() - mr_trigger_time
elif frameN == 1:
stimulus_start_time = globalClock.getTime() - mr_trigger_time
# store the data:
thisExp.addData('stimulus_start_time', stimulus_start_time)
However, I want to record and save timings of each trigger pulse when a SPACEBAR response is pressed on a target letter (stimulus) by a participant, to compare the timings with accuracy and reaction times of the task with each corresponding trigger timings.
I would really appreciate your valuable suggestions on how to work around this, as I am quite new to the PsychoPy. I also posted to the PsychoPy forum but haven't got any update so far.
Thanks in advance!

How to pass the number of total users to simulate and spawn rate in the locust script itself

How do I pass the number of total users to simulate and spawn rate in the Web UI when I run the locust file, instead, I would like to pass them as variables in the script itself?
class QuickstartUser(HttpUser):
wait_time = between(1, 2.5)
users = 10
spawn_rate = 1
#task
def on_start(self):
filenumber="ABC"
# Get file info
response = self.client.get(f"/files/" + filenumber)
json_var = response.json()
print("response Json: ", json_var)
time.sleep(1)
You could probably do it by accessing the Runner in code, but it would be much easier if you used a Load Shape.
class MyCustomShape(LoadTestShape):
time_limit = 600
spawn_rate = 20
def tick(self):
run_time = self.get_run_time()
if run_time < self.time_limit:
# User count rounded to nearest hundred.
user_count = round(run_time, -2)
return (user_count, spawn_rate)
return None
tick is called automatically, you just have to return a tuple of the user count and spawn rate you want. You can do whatever work you want to calculate what the users and rate should be. There are more examples in the GitHub repo.

Does GPIO.IN need to be linked to GPIO.OUT in RPi.GPIO in order for it to work properly?

I was writing code on an raspbian emulator with GPIO. I am able to get it to work, but for some reason when I change the order of GPIO.HIGH and the print statement in the conditionals, it does not run properly and stops after the first click. Anyone know if this is an issue with the emulator or just a property of raspberry pi and hooking it up to hardware? It also does not work at all if I do not link the GPIO.IN with a GPIO.OUT.
this gif shows what happens when I change order or remove - It turns on the first time, but it does not turn off or on again after that. It for some reason breaks it out of the while loop.
Here is the code I am using:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
import time
#initialise a previous input variable to 0 (assume button not pressed last)
prev_input = 0
prev_input1 = 0
inputs = [11, 13, 15]
outputs = [3, 5, 7]
GPIO.setup(inputs, GPIO.IN)
GPIO.setup(outputs, GPIO.OUT)
secs = 0
def main():
while True:
button_press(15, 7)
timer = add_secs(11, 5, 2)
#print(timer)
def button_press(button1, button2):
#take a reading
global prev_input
inputa = GPIO.input(button1)
#if the last reading was low and this one high, print
if ((not prev_input) and inputa):
print("Light on")
GPIO.output(button2, GPIO.HIGH) #code does not work if I remove/reorder this statement
if((not inputa) and prev_input):
print("Light off")
GPIO.output(button2, GPIO.LOW) #code does not work if I remove/reorder this statement
#update previous input
prev_input = inputa
#slight pause to debounce
time.sleep(0.05)
def add_secs(button1, button2, num):
global prev_input1
secs = 0
inputa = GPIO.input(button1)
if((not prev_input1) and inputa):
secs = num
print(secs)
GPIO.output(button2, GPIO.LOW) #code does not work if I remove/reorder this statement
prev_input1 = inputa
time.sleep(0.05)
return secs
main()
I contacted the developer of the emulator and he let me know there was an issue with the emulator that is now resolved.
The code runs properly after clearing the browsing data in chrome and re-running the program.

Storage values using os.stat(filename)

I'm trying to create an EDUCATIONAL PURPOSES ONLY virus. I do not plan on spreading it. It's purpose is to grow a file to the point your storage is full and slow your computer down. It prints the size of the file every 0.001 seconds. With that, I also want to know how fast it is growing the file. The following code doesn't seem to let it run:
class Vstatus():
def _init_(Status):
Status.countspeed == True
Status.active == True
Status.growingspeed == 0
import time
import os
#Your storage is at risk of over-expansion. Please do not let this file run forever, as your storage will fill continuously.
#This is for educational purposes only.
while Vstatus.Status.countspeed == True:
f = open('file.txt', 'a')
f.write('W')
fsize = os.stat('file.txt')
Key1 = fsize
time.sleep(1)
Key2 = fsize
Vstatus.Status.growingspeed = (Key2 - Key1)
Vstatus.Status.countspeed = False
while Vstatus.Status.active == True:
time.sleep(0.001)
f = open('file.txt', 'a')
f.write('W')
fsize = os.stat('file.txt')
print('size:' + fsize.st_size.__str__() + ' at a speed of ' + Vstatus.Status.growingspeed + 'bytes per second.')
This is for Educational Purposes ONLY
The main error I keep getting when running the file is here:
TypeError: unsupported operand type(s) for -: 'os.stat_result' and 'os.stat_result'
What does this mean? I thought os.stat returned an integer Can I get a fix on this?
Vstatus.Status.growingspeed = (Key2 - Key1)
You can't subtract os.stat objects. Your code also has some other problems. Your loops will run sequentially, meaning that your first loop will try to estimate how quickly the file is being written to without writing anything to the file.
import time # Imports at the top
import os
class VStatus:
def __init__(self): # double underscores around __init__
self.countspeed = True # Assignment, not equality test
self.active = True
self.growingspeed = 0
status = VStatus() # Make a VStatus instance
# You need to do the speed estimation and file appending in the same loop
with open('file.txt', 'a+') as f: # Only open the file once
start = time.time() # Get the current time
starting_size = os.fstat(f.fileno()).st_size
while status.active: # Access the attribute of the VStatus instance
size = os.fstat(f.fileno()).st_size # Send file desciptor to stat
f.write('W') # Writing more than one character at a time will be your biggest speed up
f.flush() # make sure the byte is written
if status.countspeed:
diff = time.time() - start
if diff >= 1: # More than a second has gone by
status.countspeed = False
status.growingspeed = (os.fstat(f.fileno()).st_size - starting_size)/diff # get rate of growth
else:
print(f"size: {size} at a speed of {status.growingspeed}")

How do I make a working team changer GUI in roblox?

In 2018 Roblox switched coding platforms I believe, most scripts have survived, however I have failed to find a working team changer for myself this year that changes your team when clicked depending if you are in certian groups or not. My scripter says that it works in studio, but an error pops up in game that says "
TeamColor is not a valid member of PlayerGui
Stack Begin
Script 'Players.Benyal.PlayerGui.Starter GUI.TeamGui.Frame.Research and Development.LocalScript', Line 8
Stack End"
My scipter tried many different ways but it just wont work! Any seggustions?
This solution uses two scripts (one LocalScript and one Script), follow the steps below to make a team changing GUI!
local teams = game:GetService("Teams")
local settings = {
["GUIHeight"] = 30, --put in a number over 20, or 100 if you want it to fill the screen
["GUIWidth"] = 40, --put in a number over 20, or 100 if you want it to fill the screen
["GUIColor"] = Color3.fromRGB(240,240,240), --color of the team changer gui
["TitleText"] = "Team Changer", --title text in the gui
["TitleFont"] = "ArialBold", --font of title
}
repeat wait() until game.Players.LocalPlayer and game.Players.LocalPlayer.PlayerGui
local plr = game.Players.LocalPlayer
local teamGUI = Instance.new("ScreenGui",plr.PlayerGui)
local frame = Instance.new("Frame",teamGUI)
frame.AnchorPoint,frame.Size,frame.Position,frame.BackgroundColor3 = Vector2.new(0.5,0.5),UDim2.new(settings.GUIWidth/100,0,settings.GUIHeight/100,0),UDim2.new(0.5,0,0.5,0),settings.GUIColor
local title = Instance.new("TextLabel",frame)
title.Text,title.Font,title.Size,title.TextScaled,title.BackgroundTransparency = settings.TitleText,settings.TitleFont,UDim2.new(1,0,0.15,0),true,0.5
local closebutton = Instance.new("TextButton",title)
closebutton.Size,closebutton.Position,closebutton.BackgroundColor3,closebutton.Text = UDim2.new(0.1,0,1,0),UDim2.new(0.9,0,0,0),Color3.fromRGB(255,155,155),"Close"
local list = Instance.new("ScrollingFrame",frame)
list.Size,list.Position,list.BackgroundTransparency = UDim2.new(1,0,0.85,0),UDim2.new(0,0,0.15,0),1
local UILayout = Instance.new("UIListLayout",list)
local serverTeamHandler = game.ReplicatedStorage:WaitForChild("teamChanger")
local getTeams = teams:GetChildren() --this part checks if you have teams in your game (you need to have put the teams in your game already)
for i,v in pairs(getTeams) do
print("[Team " .. i .. " found]: " .. v:GetFullName())
local teamButton = Instance.new("TextButton",list)
teamButton.BackgroundColor3 = v.TeamColor.Color
teamButton.Size = UDim2.new(1,0,0,40)
teamButton.Text,teamButton.TextColor3,teamButton.TextStrokeTransparency,teamButton.TextScaled = v.Name,Color3.fromRGB(255,255,255),0.7,true
teamButton.MouseButton1Down:connect(function()
print("You changed teams. You are now in: " .. v.Name)
serverTeamHandler:InvokeServer(v)
end)
end
closebutton.MouseButton1Click:connect(function()
frame:TweenPosition(UDim2.new(0.5,0,2,0),"Out","Quad",0.5)
local returnButton = Instance.new("TextButton",teamGUI)
returnButton.Size,returnButton.Position,returnButton.Text,returnButton.TextScaled = UDim2.new(0,200,0,50),UDim2.new(0.5,-100,1,-50),"Open Team Changer",true
returnButton.MouseButton1Down:connect(function()
returnButton:Destroy()
frame:TweenPosition(UDim2.new(0.5,0,0.5,0),"Out","Elastic",1,true)
end)
end)
Step 1 Insert a LocalScript into StarterGui
Step 2 Copy the stuff above and paste it into this LocalScript
Step 3 Insert a Script into either Workspace or ServerScriptService (your choice)
Step 4 Copy the stuff below and paste it into the Script
local teamChanger = Instance.new("RemoteFunction",game.ReplicatedStorage)
teamChanger.Name = "teamChanger"
local function changeTeam(client,team)
print(client.Name .. "changed teams: now in" .. team.Name)
client.Team = team
end
teamChanger.OnServerInvoke = changeTeam
If you followed these steps correctly, you should now have a working team changing GUI in your game! It works as long as you have already inserted Teams in your game. The first few lines in the LocalScript can also be customized as well!