Python Cookie Clicker: Auto Click Function? - python

My Background:
I have done quite a bit of programming with python, I would say I am not bad at it. I am familiar with most of the modules, OOP programming and stuff. You can check my pastebin profile to see what level I am actually in: www.pastebin.com/u/GameNationRDF/
The Code:
from tkinter import *
import time
master = Tk()
def uiPrint():
info()
print ("")
print (click)
blankLine()
def info():
print ("Double click purchases need 750 clicks!")
info()
click = 0
mult = 1
dcp1 = 0
def blankLine():
for i in range(20):
print ("")
def purchaseDoubleClicksCommand():
global click
global mult
if click < 750:
print ("Not enough clicks!")
blankLine()
elif click >= 750:
mult = mult*2
click = click - 750
print ("Double Clicks Purchased!")
blankLine()
def buttonCommand():
global click
global mult
click += 1*(mult)
uiPrint()
if click == 100:
print ('''Achievement Unlocked: Junior Clicker!
BONUS 100!''')
click += 100
elif click == 400:
print ('''Achievement Unlocked: Little Ninja Clicks!
BONUS 200!''')
click += 300
elif click == 900:
print ('''Achievement Unlocked: Legit Ninja!
DOUBLE CLICKS!''')
mult = mult * 2
elif click == 1500:
print ('''Achievement Unlocked: Click Ninja Master!
QUAD CLICKS!''')
mult = mult * 4
elif click == 3000:
print ('''Achievement Unlocked: Jackie Chan Style!
8 TIMES THE CLICKS!''')
mainClickButton = Button(master, text="Click!", command=buttonCommand)
mainClickButton.pack()
purchaseDoubleClickButton = Button(master, text="Purchase Double Clicks", command = purchaseDoubleClicksCommand)
purchaseDoubleClickButton.pack()
master.title("Clicker! v0.0.6")
master.geometry("%sx%s+%s+%s" % (200,70,512,512))
mainloop()
I need a way to be able to add a auto-clicker that would add certain amount of cookies in a given time. I want it to be purchased by a button. I couldnt get it to work though :(
Any help? Thanks :)

The PyUserInput project looks promising and straightforward:
from pymouse import PyMouse
m = PyMouse()
x_dim, y_dim = m.screen_size()
m.click(x_dim/2, y_dim/2, 1)
Why do you import * by the way? It's bad practice to import more dependencies than needed.
Also if I were you I would move the following section of code:
master = ()
info()
click = 0
mult = 1
dcp1 = 0
to reside above this line:
mainlickButton = Button(master, text="Click!", command=buttoncommand)
It's just cleaner to add declarations and functions. It doesn't make a GINORMOUS difference now, but when your file gets bigger and you have a lot of code it will be easier to read.

Related

What are valid appJar stretch function arguments

So far I've been attempting to create a 2 factor authentication script in python. It works very well now and I wanted to create a gui since this will be running nearly 24/7 on a raspberry pi.
TLDR; I don't understand what the docs mean by "stretch. Pass a string describing if rows/columns should stretch, to fill the entire GUI. "
#!/usr/bin/env python
import pyotp
import os
import sys
import math
import time
from appJar import gui
udstart = 1
app = gui("2FA Keys","480x320")
def count(n):
while n >= 0:
time.sleep(1)
n -= 1
if n == 0:
return 1
#Keygenertor function pass the base32 code
def keyGen(secret):
secretcalc = pyotp.TOTP(secret)
code = secretcalc.now()
Lcode = list(code)
Lcode.insert(3, " ")
Ocode = ''.join(Lcode)
return Ocode
#INIT CODES GO HERE
CoinbaseCode = keyGen("3JCAJVDGIW4KHUHL")
SiaCoinCode = keyGen("PFFO3KKKRQL6ACU5")
app.stretch(columns)
app.setFont(50)
app.addLabel("l2", "Sia Coin: " + SiaCoinCode, 0,0,0,0)
app.setLabelbg("l2", "blue")
app.addLabel("l1", "Coinbase: " + CoinbaseCode, 1,0,0,0) #Coinbase 2FA
app.setLabelBg("l1", "red")
while True:
if udstart == 1:
break
else:
time.sleep(30)
break
def update():
#UPDATE CODES GO HERE
CoinbaseCode = keyGen("3JCAJVDGIW4KHUHL") #Coinbase
SiaCoinCode = keyGen("PFFO3KKKRQL6ACU5")
app.setLabel("l2", "Sia Coin: " + SiaCoinCode)
app.setLabelBg("l2", "blue")
app.setLabel("l1", "Coinbase: " + CoinbaseCode)
app.setLabelBg("l1", "red")
#profit???
udstart = 0
app.registerEvent(update)
app.go()
I have no idea what to pass it.
If you look at the appJar source code on GitHub, you can identify what you should pass for stretch:
Looking at how strech is used:
def setStretch(self, exp):
self.setExpand(exp)
...
stretch = property(getStretch, setStretch)
Looking at the source for the setExpand we see the possible values for strech:
def setExpand(self, exp):
if exp.lower() == "none":
self.containerStack[-1]['expand'] = "NONE"
elif exp.lower() == "row":
self.containerStack[-1]['expand'] = "ROW"
elif exp.lower() == "column":
self.containerStack[-1]['expand'] = "COLUMN"
else:
self.containerStack[-1]['expand'] = "ALL"
As a result, the possible strings are (case insensitive) "None", "Row", "Column", or anything else (which will result in "ALL").
It's also documented here: http://appjar.info/pythonWidgetLayout/#set-stretch-sticky
none, row, column, both

Processing updating text and function parameters

This is my very first post on this website, and hopefully I can get some valuable insight and hints in regards to my problem as I'm a relative noob when it comes to programming. I am using Python mode in the Processing environment.
I was given a lecture problem (that the teacher will eventually go over) but I wanted to be able to solve it beforehand. Unfortunately I am not sure how to. I'm supposed to create a program that displays the amount of buns, franks and hotdogs that can be made from the amount of buns and franks, and I have keyboard inputs to increase the amount that is displayed for buns and franks.
Currently, I can't figure out how to get my text to update when I enter keyboard inputs nor can I figure out how to automatically update the number of hotdogs based on the amount of buns and franks I have.
I have attached two pictures of the question that will clear up any confusion if my explanation was not clear. I have also attached the current code I have.
picture 1
picture 2
Code:
#Variables/Model
meat = ""
buns = ""
dogs = min(12 * meat, 8 * buns)
def setup():
size(400,400)
def draw():
global meat, buns, dogs
background(255)
meat = 0
buns = 0
dogs = min(12 * meat, 8 * buns)
fill(0)
text("Packages of meat:" + str(meat), 50, 100)
text("Packages of buns:" + str(buns), 250, 100)
text("Dogs possibly made:" + str(dogs), 150, 200)
def make_hotdogs(totalMeat, totalBuns):
global meat, buns, dogs
if keyPressed == "f":
meat += 1
elif keyPressed == "g":
meat -= 1
elif keyPressed == "b":
buns += 1
elif keyPressed == "n":
buns -= 1
else:
print("Type b, n, f or g")
You're never calling your make_hotdogs() function, so you're never hitting the if statements that check which key is pressed.
You might want to look into the keyPressed() function. You can find more info in the reference.
But honestly, if you're confused, maybe you should just wait for the teacher to explain everything in the lecture.
It's been a week so let's assume that lecture has taken place and let's solve this problem. The issues I see with the OP's code is a lack of understanding of basic Python and the Processing environment. And a failure to take advantange of the problem terminology that's been provided.
Reworking the code to address the above issues and generate a viable picnic planner that runs in the Processing environment:
# Variables/Model
FRANKS_PER_PACKAGE = 12
BUNS_PER_PACKAGE = 8
frank_packages = 0
bun_packages = 0
def setup():
size(400, 400)
fill(0) # black text on a
background(255) # white background
def draw():
hotdogs = make_hotdogs(frank_packages, bun_packages)
text("Packages of franks: " + str(frank_packages), 50, 100)
text("Packages of buns: " + str(bun_packages), 250, 100)
text("Hotdogs possibly made: " + str(hotdogs), 150, 200)
def keyPressed():
global frank_packages, bun_packages
if key == "f":
frank_packages += 1
elif key == "g":
if frank_packages > 0:
frank_packages -= 1
elif key == "b":
bun_packages += 1
elif key == "n":
if bun_packages > 0:
bun_packages -= 1
background(255) # white out old calculations
def make_hotdogs(p_franks, p_buns):
return min(p_franks * FRANKS_PER_PACKAGE, p_buns * BUNS_PER_PACKAGE)
With the exception of make_hotdocs(), the Processing environment calls these functions for us. It calls setup() once at the start of the program; it calls draw() continuously over and over again; it calls keyPressed() whenever the user types on the keyboard, leaving the letter pressed in the key variable.
In Python, we only need to declare global variables where we plan to change their values, not where we simply intend to use their values.

I have an error in python with tkinter and need help(school project)

I have to create a little text adventure for school in python.
To detect keyboard inputs I decided to use tkinter and disable the window.
All is working fine but if I try to calculate with a variable after a key was pressed, I get the following error...This is the error message
This is the script I am using(I don't have much experience with python...)
import os
import sys
import tkinter
menueeintraege = ["Start", "Steuerung", "Credits", "Beenden"]
index = 0
def menueaufbauen():
os.system("cls")
print("Menue")
print("")
print("")
for i in range(4):
if i == index:
print(menueeintraege[i] + "<")
else:
print(menueeintraege[i])
menueaufbauen()
def startgame():
os.system("game.py");
def steuerung():
os.system("cls")
print("Steuerung")
print("")
print("Norden = Pfeiltaste Hoch")
print("Sueden = Pfeiltaste Runter")
print("Osten = Pfeiltaste Rechts")
print("Westen = Pfeiltaste Links")
print("Bestaetigen = Enter")
def credits():
os.system("cls")
print("Credits")
print("")
print("Jannik Nickel")
print("Thomas Kraus")
print("")
def exitgame():
sys.exit()
def menueauswahl(taste):
print(taste)
if taste == "Up":
if index > 0:
index -= 1
print(index)
elif taste == "Down":
if index < 3:
index += 1
menueaufbau()
def tasteneingabe(event):
tastenname = event.keysym
menueauswahl(tastenname)
fenster = tkinter.Tk()
fenster.bind_all('<Key>', tasteneingabe)
fenster.withdraw()
fenster.mainloop()
I think the mistake have to be in the last part of the script, I hope someone here knows a solution because it's really important for school.
Thanks for any help
(I'm using Visual Studio 2015)
Okay so I caught a couple of errors. The first is that you are referencing a global variable (index) inside of a function. To do that, you need to tell python that you are using a global variable.
def menueauswahl(taste):
global index
print(taste)
And also you need to change the function name in line 61 to menuaufbauen().

How do I have numbers increment slowly over a course of time throughout runtime

I am trying to make a text based game in which the user is a pilot in space. I want to create a movement system but am unsure how to do it. I want the user to be able to put in the desired grid coordinates, and his vehicle will begin to change its grid coords to get closer and closer to the ones he inputted.
Now, to do this I will probably need multithreading and a time element. But I am unsure how I can use a time element. Any advice is greatly appreciate, i'm just trying to learn here. Thanks guys!
from Gundam2 import Mobilesuits
#Main Variable/Object declarations:
Leo1=Mobilesuits(100,100,"Leo","leo desc","dockpit desc",100,[100,100,100])
Leo2=Mobilesuits(100,100,"Leo","leo desc","dockpit desc",100,[300,100,100])
Leo3=Mobilesuits(100,100,"Leo","leo desc","dockpit desc",100,[100,150,100])
currentmobilesuit=Leo1
#Main Function declarations
def commands(user_input,currentmobilesuit):
if user_input == "radar":
currentmobilesuit.radar()
elif user_input == "commands":
print("Command list:\nradar")
else:
print("Invalid command\nType 'commands' for a list of valid commands")
#Main execution
while True:
commands(raw_input(),currentmobilesuit)
class Mobilesuits:
#class global variables/methods here
instances = [] #grid cords here
def __init__(self,armor,speed,name,description,cockpit_description,\
radar_range, coordinates):
Mobilesuits.instances.append(self)
self.armor=armor
self.speed=speed
self.name=name
self.description=description
self.cockpit_description=cockpit_description
self.radar_range=radar_range
self.coordinates=coordinates
def can_detect(self, other):
for own_coord, other_coord in zip(self.coordinates, other.coordinates):
if abs(own_coord - other_coord) > self.radar_range:
return False
return True
def radar(self):
for other in Mobilesuits.instances:
if other is not self and self.can_detect(other):
print "%s detected at %s" % (other.description, other.coordinates)
Games typically have a "master loop" of some kind; yours does here:
#Main execution
while True:
commands(raw_input(),currentmobilesuit)
The simplest thing to do is to count in the loop:
#Main execution
turn_count = 0
while True:
commands(raw_input(),currentmobilesuit)
turn_count += 1
If you wanted the real time taken to have some impact on the counter, or be the counter, you can get the current time from the time module calling time.time().
#Main execution
import time
time_start = time.time()
time_elapsed = 0
while True:
commands(raw_input(),currentmobilesuit)
time_elapsed = time.time() - time_start
A couple other thoughts:
Make a Game class, and put the turn counter and game loop in that.
Have the commands function return a number that is the number of time units that took place during the command; for example, entering an invalid command might take 0 turns, while repairing a robot might take 5.
#Main execution
turn_count = 0
while True:
turns_taken = commands(raw_input(),currentmobilesuit)
turn_count += turns_taken
You can use non-blocking I/O. This will help you avoid the complications of threading. Here's your sample code implemented with a non-blocking read of stdin:
#!/usr/bin/python
import sys
import select
call_count = 0
#Main Function declarations
def commands(user_input):
global call_count
if len(user_input) > 0:
print('call count: ' + str(call_count) + ' user entered: ' + user_input)
def raw_input_no_block():
global call_count
call_count = call_count + 1
input_avail = select.select([sys.stdin], [], [], 0.1)[0] #wait for 0.1 seconds
if input_avail:
return sys.stdin.readline()
else:
return ''
#Main execution
while True:
commands(raw_input_no_block())

Python Curses: Returning to the Previous Menu

I have a menu system in ncurses.
Choosing one of the options takes you to another menu. But how do I get back?
import curses
def Main():
x = 0
while x!= ord('2'):
x = screen.getch()
screen.clear();screen.border();
screen.addstr(1,1, "Please choose:")
screen.addstr(3,1, "1 - Another Menu")
screen.addstr(4,1, "2 - Exit")
if x==ord('1'):
y = 0
while y!= ord('2'):
y = screen.getch()
screen.clear();screen.border();
screen.addstr(1,1, "Please choose from new menu:")
screen.addstr(3,1, "1 - Do Something new")
screen.addstr(4,1, "2 - Previous Menu")
if y == ord('1'): doSomething()
#Here I exit the internal loop. I need to go back to the previous menu, but I don't know how.
##
##exit outside loop and close program
##
curses.endwin(); exit();
screen = curses.initscr()
Main()
Ideally I'd need to use the GOTO module to jump between lines of code, but the device I'm using does not come with that module built-in.
Do you guys know any other methods? Really appreciate any help.
============ Update: ==================
Okay, I also realized that you can regenerate both menu's with ease:
import curses
def Main():
x = 0
while x!= ord('2'): #draws 1st menu
screen.clear();screen.border();
screen.addstr(1,1, "Please choose:")
screen.addstr(3,1, "1 - Another Menu")
screen.addstr(4,1, "2 - Exit")
x = screen.getch() #grab input AFTER first giving options :)
if x==ord('1'):
y = 0
z = 0
while y!= ord('2'): #draws 2nd menu
screen.clear();screen.border();
screen.addstr(1,1, "Please choose from new menu:")
screen.addstr(3,1, "1 - Do Something new")
screen.addstr(4,1, "2 - Previous Menu")
screen.addstr(6,1, "current loop : "+str(z))
y = screen.getch(); #grabs new input
while z!= -1: #never breaks from loop unless 'break' is called
if y == ord('1'):
z += 1
break #regenerates 2nd menu
break #regenerates 1st menu
#Here we exit the internal loop.
##
##exit outside loop and close program
curses.endwin(); exit();
screen = curses.initscr()
Main()
Add x = 0 after the second while loop ends.
(You need to reset x every time around the loop, not just the first. Otherwise exiting from the first menu will x set to "exit", so will also exit the second menu.)

Categories

Resources