Python - how to clear screen when switch is toggled - python

Right now, i am trying to make the turtle graphic screen clear and reset everything when i toggle a new algorithm using the tab key. The toggle part works however i am unable to clear the whole screen when i toggle to a new algorithm.
My codes are as shown below:
from pynput import keyboard
from pynput.keyboard import Listener, Key, Controller
import keyboard
from turtle import Turtle, Screen, clearscreen, clear
import sys
def lefthand_Algo():
execfile('...')
def bfs_Algo():
execfile('...')
# Creates the title
def title():
t = Turtle()
t.color('white')
t.write('Hello, hit tab to start the algorithm!', font=('lemon',20,'normal'), align='center')
t.hideturtle()
screen = Screen()
clearscreen = clearscreen
clear = clear
screen.bgcolor("black") # Set the background colour
screen.setup(width=0.9, height=0.9) # Setup the dimensions of the working window
title = title()
current_state = bfs_Algo
next_state = lefthand_Algo
switch = False
def toggle():
global switch
switch = not switch
if switch:
next_state()
else:
current_state()
screen.onkeypress(toggle, "Tab")
screen.listen()
screen.mainloop()
Note: The algorithms are in separate files and this file is just for the toggling between the two files.
How do i clear the screen each time i toggle? Help will be greatly appreciated! :)

From #RhinoRunner in the comments:
Use turtle.reset().

Related

Roblox won't detect mouse movement from autopygui

I am trying to create a script that automatically rejoins a roblox game on disconnect. I have beeen using ctypes to obtain a pixel on the screen, and if the pixel matches a color, it should automatically press the rejoin button. the problem is that it wont press the button. After some troubleshooting, I have figured out that the mouse movement wont register with the game, as if I move my mouse manually, it clicks the button.
In short, the game won't detect mouse movement from autopygui. If I move my mouse manually, it registers.
Video example:
https://youtu.be/VvAfHHXul8Q
Code:
import pyautogui as py
import keyboard
import tkinter
import requests
from ctypes import windll
from time import sleep
key = "m"
toggled = False
rjcolor = 16777215
root = tkinter.Tk()
root.withdraw()
width, height = root.winfo_screenwidth(), root.winfo_screenheight()
dc= windll.user32.GetDC(0)
def getpixel(x,y):
return windll.gdi32.GetPixel(dc,x,y)
while True:
if keyboard.is_pressed(key):
toggled = not toggled
print("toggled to " + str(toggled))
sleep(0.5)
if toggled == True:
py.moveTo(width / 2, 800)
py.click(button='left')
if getpixel(1050, 600) == rjcolor:
print("disconnected, waiting until internet back online!")
while True:
try:
requests.head("http://www.google.com/", timeout=3)
print('The internet connection is active, rejoining.')
py.moveTo(1050, 590)
py.mouseDown(button='left')
sleep(0.1)
py.mouseUp(button='left')
break
except requests.ConnectionError:
print("The internet connection is down")
sleep(3)
sleep(0.1)
Pyautogui has issues with clicking on roblox, but i've found a workaround:
Replace py.click(button="left") with autoit.mouse_click("left")
import autoit
autoit.mouse_click("left")

Python Not Clicking in game or Webbrowser

I am making my own autoclicker. But its can not clicking. I try all alternatives which ones in stackoverflow. Is there a any helper please.
My Code:
import pyautogui
import python_imagesearch.imagesearch
import time
while True:
icon = python_imagesearch.imagesearch.imagesearch("clickme.png", 0.8)
print(icon)
icon_x = icon[0]
icon_y = icon[1]
icon_x = icon_x+5
icon_y = icon_y+5
# time.sleep(1.5)
pyautogui.leftClick(icon_x, icon_y)
time.sleep(0.1)
pyautogui.leftClick(icon_x, icon_y)
time.sleep(0.1)
I am trying the click here.
https://www.tetralark.com/ClickerJs/
It's solved. It is about other games anticheat blocking.
If your code is moving to your image already, you can click in the image by using:
pyautogui.click()
Or you can pass coordinates as Mouse Control Functions says:
pyautogui.click(x=100, y=200) # move to 100, 200, then click the left mouse button.

Pygame window freezes and stop responding, how could I fix this?

I am creating a game but I am having a problem with my button class for my gui. There are no compile errors and no runtime errors either. The only problem is that on run it immediately freezes the pygame window. I don't know how to solve this.
I've tried fiddling around with the callback function (which I removed entirely) and with the update and draw loop as well but nothing seems to work.
Python 3.7.0 and Pygame 1.9.4
Button Class:
import sys
import time
import pygame
pygame.init()
class button:
def __init__(self, txt, location, bg=(255,255,255),fg=(0,0,0),size=(80,30),font_name="Times New Roman",font_size=16):
#bg is the colour of the button
#fg is the colour of the text
#location refers to the center points of the button
self.colour = bg
self.bg = bg
self.fg = fg
self.size = size
self.font = pygame.font.SysFont(font_name,font_size)
self.txt = txt
self.txt_surf = self.font.render(self.txt, 1, self.fg)
self.txt_rect = self.txt_surf.get_rect(center=[s//2 for s in self.size])
self.surface = pygame.surface.Surface(size)
self.rect = self.surface.get_rect(center=location)
def mouseover(self):
self.bg = self.colour
pos = pygame.mouse.get_pos()
if self.rect.collidepoint(pos):
self.bg = (200,200,200)
def draw(self, screen):
self.mouseover()
self.surface.fill(self.bg)
self.surface.blit(self.txt_surf, self.txt_rect)
screen.blit(self.surface, self.rect)
Actual update/draw loop
import gui
import pygame
import sys
import time
import win32api
pygame.init()
screen = pygame.display.set_mode((400,400))
button1 = gui.button("No", (200,200))
intro = True
while intro:
screen.fill((255,255,255))
button1.draw(screen)
if win32api.GetKeyState(0x01) == -127 or win32api.GetKeyState(0x01) == -128:
if button1.rect.collidepoint(pygame.mouse.get_pos()):
intro = False
pygame.quit()
sys.exit()
pygame.display.flip()
pygame.time.wait(20)
I really just want the window to stop freezing up on run and to actually have a button press work. What it should do is immediately quit the application when you press the button in the middle. Not actually do that though.
You have to let pygame process the events in the event queue by calling pygame.event.get (or pygame.event.pump, but you should stick to use get).
Otherwise, the queue will fill up and new events will be dropped. This includes internal events that tell your OS to draw the window etc, so your window will freeze.
Also, there's no reason to use win32api to get the state of the keyboard (you can use pygame.key.get_pressed instead), but that's another topic.

Disable keyboard but keep getting events

I have a touchscreen laptop that folds back enough to become like a tablet. If I put it down on the table, I don't want to be hitting keys accidentally, so I'm working on a script to disable the keyboard when I hit Ctrl-F10 and then re-enable it when I do that again. I'm using xlib from PyPI, and I've gotten this so far:
from Xlib.display import Display
from Xlib.ext import xinput
class Handler:
def __init__(self, display):
self.enabled = True
self.display = display
def handle(self, event):
if event.data['detail'] == 76 and event.data['mods']['base_mods'] == 4:
if self.enabled:
self.display.grab_server()
else:
self.display.ungrab_server()
self.enabled = not self.enabled
try:
display = Display()
handler = Handler(display)
screen = display.screen()
screen.root.xinput_select_events([
(xinput.AllDevices, xinput.KeyPressMask),
])
while True:
event = display.next_event()
handler.handle(event)
finally:
display.close()
It does disable the keyboard on Ctrl-F10, but as soon as I re-enable, all the keys I pressed when it was disabled are activated all at once. Is there a way to clear the queue before re-enabling, or a better way to disable the keyboard?
Try XGrabKeyboard: https://tronche.com/gui/x/xlib/input/XGrabKeyboard.html
(But this requires you to create your own window for grabbing; you can e.g. create a window of size 1x1 at position -10x-10)
I think the values for things like owner_events and keyboard_mode do not matter much. The main effect should be that the input focus goes to your own window. time should be CurrentTime (which is 0) and pointer_mode should be GrabModeAsync, so that you do not interfere with the pointer.

Pygame grabbing console input when using framebuffer

I have a Raspberry Pi with a PiTFT module. I'm wanting to use Pygame to display information on the module using the framebuffer (without X). I have all the display stuff working but the problem is that pygame is grabbing the input from the keyboard so that I can't even change the terminal with alt 1-7.
This task is supposed to run in the background so this is not desired behavior. I can't find any way to disable it though. It looked like pygame.event.set_grab() might have been appropriate but did not help. Here is a cut-down version of my code which exhibits the same issue.
import os
import pygame
import time
from time import gmtime,strftime,localtime
class pytest :
screen = None
def __init__(self):
os.environ["SDL_FBDEV"] = "/dev/fb1"
try:
pygame.display.init()
except pygame.error:
print 'Init failed.'
size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
pygame.event.set_grab(0)
pygame.font.init()
self.font = pygame.font.SysFont("", 30)
def __del__(self):
"Destructor to make sure pygame shuts down, etc."
def test(self):
lightblue = (92, 92, 176)
self.screen.fill(lightblue)
tm=time.strftime("%H:%M:%S",localtime())
t=self.font.render(tm,1,(255,255,155))
self.screen.blit(t,(240,00))
pygame.display.update()
scope = pytest()
while 1:
scope.test()
pygame.event.pump()
time.sleep(1)

Categories