Log In
Interaction Multiplier IconFighting Weather Castform Don't have an account yet? Register now!
.

Forum Thread

old diary that might come in handy later

Forum-Index Diaries old diary that might come in handy later
BoomBoy
OFFLINE
Trainerlevel: 77

Forum Posts: 600
Posted: Tue, 02/02/2021 10:02 (3 Years ago)


so this is basically a place where ima post bits of handy code, generally pokeheroes-related, or BBCodes. fyi i usually write in python and i use windows.

you may use the code in here but please do not re-publish it or take it as your own and always credit me wherever possible

still havent figured out how to upload python codes to a public domain lol

usage instructions and any images/file locations will be indicated where applicable.

DO NOT POST IN THIS THREAD

many of my projects use simple libraries like time or random. another one i use often is graphics.py, which on windows you can install with
pip install graphics.py
in cmd on windows. no idea for mac, but you could also create a file named graphics.py with the following code in:
Show hidden content
# graphics.py
"""Simple object oriented graphics library

The library is designed to make it very easy for novice programmers to
experiment with computer graphics in an object oriented fashion. It is
written by John Zelle for use with the book "Python Programming: An
Introduction to Computer Science" (Franklin, Beedle & Associates).

LICENSE: This is open-source software released under the terms of the
GPL (http://www.gnu.org/licenses/gpl.html).

PLATFORMS: The package is a wrapper around Tkinter and should run on
any platform where Tkinter is available.

INSTALLATION: Put this file somewhere where Python can see it.

OVERVIEW: There are two kinds of objects in the library. The GraphWin
class implements a window where drawing can be done and various
GraphicsObjects are provided that can be drawn into a GraphWin. As a
simple example, here is a complete program to draw a circle of radius
10 centered in a 100x100 window:

--------------------------------------------------------------------
from graphics import *

def main():
win = GraphWin("My Circle", 100, 100)
c = Circle(Point(50,50), 10)
c.draw(win)
win.getMouse() # Pause to view result
win.close() # Close window when done

main()
--------------------------------------------------------------------
GraphWin objects support coordinate transformation through the
setCoords method and mouse and keyboard interaction methods.

The library provides the following graphical objects:
Point
Line
Circle
Oval
Rectangle
Polygon
Text
Entry (for text-based input)
Image

Various attributes of graphical objects can be set such as
outline-color, fill-color and line-width. Graphical objects also
support moving and hiding for animation effects.

The library also provides a very simple class for pixel-based image
manipulation, Pixmap. A pixmap can be loaded from a file and displayed
using an Image object. Both getPixel and setPixel methods are provided
for manipulating the image.

DOCUMENTATION: For complete documentation, see Chapter 4 of "Python
Programming: An Introduction to Computer Science" by John Zelle,
published by Franklin, Beedle & Associates. Also see
http://mcsp.wartburg.edu/zelle/python for a quick reference"""

__version__ = "5.0"

# Version 5 8/26/2016
# * update at bottom to fix MacOS issue causing askopenfile() to hang
# * update takes an optional parameter specifying update rate
# * Entry objects get focus when drawn
# * __repr_ for all objects
# * fixed offset problem in window, made canvas borderless

# Version 4.3 4/25/2014
# * Fixed Image getPixel to work with Python 3.4, TK 8.6 (tuple type handling)
# * Added interactive keyboard input (getKey and checkKey) to GraphWin
# * Modified setCoords to cause redraw of current objects, thus
# changing the view. This supports scrolling around via setCoords.
#
# Version 4.2 5/26/2011
# * Modified Image to allow multiple undraws like other GraphicsObjects
# Version 4.1 12/29/2009
# * Merged Pixmap and Image class. Old Pixmap removed, use Image.
# Version 4.0.1 10/08/2009
# * Modified the autoflush on GraphWin to default to True
# * Autoflush check on close, setBackground
# * Fixed getMouse to flush pending clicks at entry
# Version 4.0 08/2009
# * Reverted to non-threaded version. The advantages (robustness,
# efficiency, ability to use with other Tk code, etc.) outweigh
# the disadvantage that interactive use with IDLE is slightly more
# cumbersome.
# * Modified to run in either Python 2.x or 3.x (same file).
# * Added Image.getPixmap()
# * Added update() -- stand alone function to cause any pending
# graphics changes to display.
#
# Version 3.4 10/16/07
# Fixed GraphicsError to avoid "exploded" error messages.
# Version 3.3 8/8/06
# Added checkMouse method to GraphWin
# Version 3.2.3
# Fixed error in Polygon init spotted by Andrew Harrington
# Fixed improper threading in Image constructor
# Version 3.2.2 5/30/05
# Cleaned up handling of exceptions in Tk thread. The graphics package
# now raises an exception if attempt is made to communicate with
# a dead Tk thread.
# Version 3.2.1 5/22/05
# Added shutdown function for tk thread to eliminate race-condition
# error "chatter" when main thread terminates
# Renamed various private globals with _
# Version 3.2 5/4/05
# Added Pixmap object for simple image manipulation.
# Version 3.1 4/13/05
# Improved the Tk thread communication so that most Tk calls
# do not have to wait for synchonization with the Tk thread.
# (see _tkCall and _tkExec)
# Version 3.0 12/30/04
# Implemented Tk event loop in separate thread. Should now work
# interactively with IDLE. Undocumented autoflush feature is
# no longer necessary. Its default is now False (off). It may
# be removed in a future version.
# Better handling of errors regarding operations on windows that
# have been closed.
# Addition of an isClosed method to GraphWindow class.

# Version 2.2 8/26/04
# Fixed cloning bug reported by Joseph Oldham.
# Now implements deep copy of config info.
# Version 2.1 1/15/04
# Added autoflush option to GraphWin. When True (default) updates on
# the window are done after each action. This makes some graphics
# intensive programs sluggish. Turning off autoflush causes updates
# to happen during idle periods or when flush is called.
# Version 2.0
# Updated Documentation
# Made Polygon accept a list of Points in constructor
# Made all drawing functions call TK update for easier animations
# and to make the overall package work better with
# Python 2.3 and IDLE 1.0 under Windows (still some issues).
# Removed vestigial turtle graphics.
# Added ability to configure font for Entry objects (analogous to Text)
# Added setTextColor for Text as an alias of setFill
# Changed to class-style exceptions
# Fixed cloning of Text objects

# Version 1.6
# Fixed Entry so StringVar uses _root as master, solves weird
# interaction with shell in Idle
# Fixed bug in setCoords. X and Y coordinates can increase in
# "non-intuitive" direction.
# Tweaked wm_protocol so window is not resizable and kill box closes.

# Version 1.5
# Fixed bug in Entry. Can now define entry before creating a
# GraphWin. All GraphWins are now toplevel windows and share
# a fixed root (called _root).

# Version 1.4
# Fixed Garbage collection of Tkinter images bug.
# Added ability to set text atttributes.
# Added Entry boxes.

import time, os, sys

try: # import as appropriate for 2.x vs. 3.x
import tkinter as tk
except:
import Tkinter as tk


##########################################################################
# Module Exceptions

class GraphicsError(Exception):
"""Generic error class for graphics module exceptions."""
pass

OBJ_ALREADY_DRAWN = "Object currently drawn"
UNSUPPORTED_METHOD = "Object doesn't support operation"
BAD_OPTION = "Illegal option value"

##########################################################################
# global variables and funtions

_root = tk.Tk()
_root.withdraw()

_update_lasttime = time.time()

def update(rate=None):
global _update_lasttime
if rate:
now = time.time()
pauseLength = 1/rate-(now-_update_lasttime)
if pauseLength > 0:
time.sleep(pauseLength)
_update_lasttime = now + pauseLength
else:
_update_lasttime = now

_root.update()

############################################################################
# Graphics classes start here

class GraphWin(tk.Canvas):

"""A GraphWin is a toplevel window for displaying graphics."""

def __init__(self, title="Graphics Window",
width=200, height=200, autoflush=True):
assert type(title) == type(""), "Title must be a string"
master = tk.Toplevel(_root)
master.protocol("WM_DELETE_WINDOW", self.close)
tk.Canvas.__init__(self, master, width=width, height=height,
highlightthickness=0, bd=0)
self.master.title(title)
self.pack()
master.resizable(0,0)
self.foreground = "black"
self.items = []
self.mouseX = None
self.mouseY = None
self.bind("<Button-1>", self._onClick)
self.bind_all("<Key>", self._onKey)
self.height = int(height)
self.width = int(width)
self.autoflush = autoflush
self._mouseCallback = None
self.trans = None
self.closed = False
master.lift()
self.lastKey = ""
if autoflush: _root.update()

def __repr__(self):
if self.isClosed():
return "<Closed GraphWin>"
else:
return "GraphWin('{}', {}, {})".format(self.master.title(),
self.getWidth(),
self.getHeight())

def __str__(self):
return repr(self)

def __checkOpen(self):
if self.closed:
raise GraphicsError("window is closed")

def _onKey(self, evnt):
self.lastKey = evnt.keysym


def setBackground(self, color):
"""Set background color of the window"""
self.__checkOpen()
self.config(bg=color)
self.__autoflush()

def setCoords(self, x1, y1, x2, y2):
"""Set coordinates of window to run from (x1,y1) in the
lower-left corner to (x2,y2) in the upper-right corner."""
self.trans = Transform(self.width, self.height, x1, y1, x2, y2)
self.redraw()

def close(self):
"""Close the window"""

if self.closed: return
self.closed = True
self.master.destroy()
self.__autoflush()


def isClosed(self):
return self.closed


def isOpen(self):
return not self.closed


def __autoflush(self):
if self.autoflush:
_root.update()


def plot(self, x, y, color="black"):
"""Set pixel (x,y) to the given color"""
self.__checkOpen()
xs,ys = self.toScreen(x,y)
self.create_line(xs,ys,xs+1,ys, fill=color)
self.__autoflush()

def plotPixel(self, x, y, color="black"):
"""Set pixel raw (independent of window coordinates) pixel
(x,y) to color"""
self.__checkOpen()
self.create_line(x,y,x+1,y, fill=color)
self.__autoflush()

def flush(self):
"""Update drawing to the window"""
self.__checkOpen()
self.update_idletasks()

def getMouse(self):
"""Wait for mouse click and return Point object representing
the click"""
self.update() # flush any prior clicks
self.mouseX = None
self.mouseY = None
while self.mouseX == None or self.mouseY == None:
self.update()
if self.isClosed(): raise GraphicsError("getMouse in closed window")
time.sleep(.1) # give up thread
x,y = self.toWorld(self.mouseX, self.mouseY)
self.mouseX = None
self.mouseY = None
return Point(x,y)

def checkMouse(self):
"""Return last mouse click or None if mouse has
not been clicked since last call"""
if self.isClosed():
raise GraphicsError("checkMouse in closed window")
self.update()
if self.mouseX != None and self.mouseY != None:
x,y = self.toWorld(self.mouseX, self.mouseY)
self.mouseX = None
self.mouseY = None
return Point(x,y)
else:
return None

def getKey(self):
"""Wait for user to press a key and return it as a string."""
self.lastKey = ""
while self.lastKey == "":
self.update()
if self.isClosed(): raise GraphicsError("getKey in closed window")
time.sleep(.1) # give up thread

key = self.lastKey
self.lastKey = ""
return key

def checkKey(self):
"""Return last key pressed or None if no key pressed since last call"""
if self.isClosed():
raise GraphicsError("checkKey in closed window")
self.update()
key = self.lastKey
self.lastKey = ""
return key

def getHeight(self):
"""Return the height of the window"""
return self.height

def getWidth(self):
"""Return the width of the window"""
return self.width

def toScreen(self, x, y):
trans = self.trans
if trans:
return self.trans.screen(x,y)
else:
return x,y

def toWorld(self, x, y):
trans = self.trans
if trans:
return self.trans.world(x,y)
else:
return x,y

def setMouseHandler(self, func):
self._mouseCallback = func

def _onClick(self, e):
self.mouseX = e.x
self.mouseY = e.y
if self._mouseCallback:
self._mouseCallback(Point(e.x, e.y))

def addItem(self, item):
self.items.append(item)

def delItem(self, item):
self.items.remove(item)

def redraw(self):
for item in self.items[:]:
item.undraw()
item.draw(self)
self.update()


class Transform:

"""Internal class for 2-D coordinate transformations"""

def __init__(self, w, h, xlow, ylow, xhigh, yhigh):
# w, h are width and height of window
# (xlow,ylow) coordinates of lower-left [raw (0,h-1)]
# (xhigh,yhigh) coordinates of upper-right [raw (w-1,0)]
xspan = (xhigh-xlow)
yspan = (yhigh-ylow)
self.xbase = xlow
self.ybase = yhigh
self.xscale = xspan/float(w-1)
self.yscale = yspan/float(h-1)

def screen(self,x,y):
# Returns x,y in screen (actually window) coordinates
xs = (x-self.xbase) / self.xscale
ys = (self.ybase-y) / self.yscale
return int(xs+0.5),int(ys+0.5)

def world(self,xs,ys):
# Returns xs,ys in world coordinates
x = xs*self.xscale + self.xbase
y = self.ybase - ys*self.yscale
return x,y


# Default values for various item configuration options. Only a subset of
# keys may be present in the configuration dictionary for a given item
DEFAULT_CONFIG = {"fill":"",
"outline":"black",
"width":"1",
"arrow":"none",
"text":"",
"justify":"center",
"font": ("helvetica", 12, "normal")}

class GraphicsObject:

"""Generic base class for all of the drawable objects"""
# A subclass of GraphicsObject should override _draw and
# and _move methods.

def __init__(self, options):
# options is a list of strings indicating which options are
# legal for this object.

# When an object is drawn, canvas is set to the GraphWin(canvas)
# object where it is drawn and id is the TK identifier of the
# drawn shape.
self.canvas = None
self.id = None

# config is the dictionary of configuration options for the widget.
config = {}
for option in options:
config[option] = DEFAULT_CONFIG[option]
self.config = config

def setFill(self, color):
"""Set interior color to color"""
self._reconfig("fill", color)

def setOutline(self, color):
"""Set outline color to color"""
self._reconfig("outline", color)

def setWidth(self, width):
"""Set line weight to width"""
self._reconfig("width", width)

def draw(self, graphwin):

"""Draw the object in graphwin, which should be a GraphWin
object. A GraphicsObject may only be drawn into one
window. Raises an error if attempt made to draw an object that
is already visible."""

if self.canvas and not self.canvas.isClosed(): raise GraphicsError(OBJ_ALREADY_DRAWN)
if graphwin.isClosed(): raise GraphicsError("Can't draw to closed window")
self.canvas = graphwin
self.id = self._draw(graphwin, self.config)
graphwin.addItem(self)
if graphwin.autoflush:
_root.update()
return self


def undraw(self):

"""Undraw the object (i.e. hide it). Returns silently if the
object is not currently drawn."""

if not self.canvas: return
if not self.canvas.isClosed():
self.canvas.delete(self.id)
self.canvas.delItem(self)
if self.canvas.autoflush:
_root.update()
self.canvas = None
self.id = None


def move(self, dx, dy):

"""move object dx units in x direction and dy units in y
direction"""

self._move(dx,dy)
canvas = self.canvas
if canvas and not canvas.isClosed():
trans = canvas.trans
if trans:
x = dx/ trans.xscale
y = -dy / trans.yscale
else:
x = dx
y = dy
self.canvas.move(self.id, x, y)
if canvas.autoflush:
_root.update()

def _reconfig(self, option, setting):
# Internal method for changing configuration of the object
# Raises an error if the option does not exist in the config
# dictionary for this object
if option not in self.config:
raise GraphicsError(UNSUPPORTED_METHOD)
options = self.config
options[option] = setting
if self.canvas and not self.canvas.isClosed():
self.canvas.itemconfig(self.id, options)
if self.canvas.autoflush:
_root.update()


def _draw(self, canvas, options):
"""draws appropriate figure on canvas with options provided
Returns Tk id of item drawn"""
pass # must override in subclass


def _move(self, dx, dy):
"""updates internal state of object to move it dx,dy units"""
pass # must override in subclass


class Point(GraphicsObject):
def __init__(self, x, y):
GraphicsObject.__init__(self, ["outline", "fill"])
self.setFill = self.setOutline
self.x = float(x)
self.y = float(y)

def __repr__(self):
return "Point({}, {})".format(self.x, self.y)

def _draw(self, canvas, options):
x,y = canvas.toScreen(self.x,self.y)
return canvas.create_rectangle(x,y,x+1,y+1,options)

def _move(self, dx, dy):
self.x = self.x + dx
self.y = self.y + dy

def clone(self):
other = Point(self.x,self.y)
other.config = self.config.copy()
return other

def getX(self): return self.x
def getY(self): return self.y

class _BBox(GraphicsObject):
# Internal base class for objects represented by bounding box
# (opposite corners) Line segment is a degenerate case.

def __init__(self, p1, p2, options=["outline","width","fill"]):
GraphicsObject.__init__(self, options)
self.p1 = p1.clone()
self.p2 = p2.clone()

def _move(self, dx, dy):
self.p1.x = self.p1.x + dx
self.p1.y = self.p1.y + dy
self.p2.x = self.p2.x + dx
self.p2.y = self.p2.y + dy

def getP1(self): return self.p1.clone()

def getP2(self): return self.p2.clone()

def getCenter(self):
p1 = self.p1
p2 = self.p2
return Point((p1.x+p2.x)/2.0, (p1.y+p2.y)/2.0)


class Rectangle(_BBox):

def __init__(self, p1, p2):
_BBox.__init__(self, p1, p2)

def __repr__(self):
return "Rectangle({}, {})".format(str(self.p1), str(self.p2))

def _draw(self, canvas, options):
p1 = self.p1
p2 = self.p2
x1,y1 = canvas.toScreen(p1.x,p1.y)
x2,y2 = canvas.toScreen(p2.x,p2.y)
return canvas.create_rectangle(x1,y1,x2,y2,options)

def clone(self):
other = Rectangle(self.p1, self.p2)
other.config = self.config.copy()
return other


class Oval(_BBox):

def __init__(self, p1, p2):
_BBox.__init__(self, p1, p2)

def __repr__(self):
return "Oval({}, {})".format(str(self.p1), str(self.p2))


def clone(self):
other = Oval(self.p1, self.p2)
other.config = self.config.copy()
return other

def _draw(self, canvas, options):
p1 = self.p1
p2 = self.p2
x1,y1 = canvas.toScreen(p1.x,p1.y)
x2,y2 = canvas.toScreen(p2.x,p2.y)
return canvas.create_oval(x1,y1,x2,y2,options)

class Circle(Oval):

def __init__(self, center, radius):
p1 = Point(center.x-radius, center.y-radius)
p2 = Point(center.x+radius, center.y+radius)
Oval.__init__(self, p1, p2)
self.radius = radius

def __repr__(self):
return "Circle({}, {})".format(str(self.getCenter()), str(self.radius))

def clone(self):
other = Circle(self.getCenter(), self.radius)
other.config = self.config.copy()
return other

def getRadius(self):
return self.radius


class Line(_BBox):

def __init__(self, p1, p2):
_BBox.__init__(self, p1, p2, ["arrow","fill","width"])
self.setFill(DEFAULT_CONFIG['outline'])
self.setOutline = self.setFill

def __repr__(self):
return "Line({}, {})".format(str(self.p1), str(self.p2))

def clone(self):
other = Line(self.p1, self.p2)
other.config = self.config.copy()
return other

def _draw(self, canvas, options):
p1 = self.p1
p2 = self.p2
x1,y1 = canvas.toScreen(p1.x,p1.y)
x2,y2 = canvas.toScreen(p2.x,p2.y)
return canvas.create_line(x1,y1,x2,y2,options)

def setArrow(self, option):
if not option in ["first","last","both","none"]:
raise GraphicsError(BAD_OPTION)
self._reconfig("arrow", option)


class Polygon(GraphicsObject):

def __init__(self, *points):
# if points passed as a list, extract it
if len(points) == 1 and type(points[0]) == type([]):
points = points[0]
self.points = list(map(Point.clone, points))
GraphicsObject.__init__(self, ["outline", "width", "fill"])

def __repr__(self):
return "Polygon"+str(tuple(p for p in self.points))

def clone(self):
other = Polygon(*self.points)
other.config = self.config.copy()
return other

def getPoints(self):
return list(map(Point.clone, self.points))

def _move(self, dx, dy):
for p in self.points:
p.move(dx,dy)

def _draw(self, canvas, options):
args = [canvas]
for p in self.points:
x,y = canvas.toScreen(p.x,p.y)
args.append(x)
args.append(y)
args.append(options)
return GraphWin.create_polygon(*args)

class Text(GraphicsObject):

def __init__(self, p, text):
GraphicsObject.__init__(self, ["justify","fill","text","font"])
self.setText(text)
self.anchor = p.clone()
self.setFill(DEFAULT_CONFIG['outline'])
self.setOutline = self.setFill

def __repr__(self):
return "Text({}, '{}')".format(self.anchor, self.getText())

def _draw(self, canvas, options):
p = self.anchor
x,y = canvas.toScreen(p.x,p.y)
return canvas.create_text(x,y,options)

def _move(self, dx, dy):
self.anchor.move(dx,dy)

def clone(self):
other = Text(self.anchor, self.config['text'])
other.config = self.config.copy()
return other

def setText(self,text):
self._reconfig("text", text)

def getText(self):
return self.config["text"]

def getAnchor(self):
return self.anchor.clone()

def setFace(self, face):
if face in ['helvetica','arial','courier','times roman']:
f,s,b = self.config['font']
self._reconfig("font",(face,s,b))
else:
raise GraphicsError(BAD_OPTION)

def setSize(self, size):
if 5 <= size <= 36:
f,s,b = self.config['font']
self._reconfig("font", (f,size,b))
else:
raise GraphicsError(BAD_OPTION)

def setStyle(self, style):
if style in ['bold','normal','italic', 'bold italic']:
f,s,b = self.config['font']
self._reconfig("font", (f,s,style))
else:
raise GraphicsError(BAD_OPTION)

def setTextColor(self, color):
self.setFill(color)


class Entry(GraphicsObject):

def __init__(self, p, width):
GraphicsObject.__init__(self, [])
self.anchor = p.clone()
#print self.anchor
self.width = width
self.text = tk.StringVar(_root)
self.text.set("")
self.fill = "gray"
self.color = "black"
self.font = DEFAULT_CONFIG['font']
self.entry = None

def __repr__(self):
return "Entry({}, {})".format(self.anchor, self.width)

def _draw(self, canvas, options):
p = self.anchor
x,y = canvas.toScreen(p.x,p.y)
frm = tk.Frame(canvas.master)
self.entry = tk.Entry(frm,
width=self.width,
textvariable=self.text,
bg = self.fill,
fg = self.color,
font=self.font)
self.entry.pack()
#self.setFill(self.fill)
self.entry.focus_set()
return canvas.create_window(x,y,window=frm)

def getText(self):
return self.text.get()

def _move(self, dx, dy):
self.anchor.move(dx,dy)

def getAnchor(self):
return self.anchor.clone()

def clone(self):
other = Entry(self.anchor, self.width)
other.config = self.config.copy()
other.text = tk.StringVar()
other.text.set(self.text.get())
other.fill = self.fill
return other

def setText(self, t):
self.text.set(t)


def setFill(self, color):
self.fill = color
if self.entry:
self.entry.config(bg=color)


def _setFontComponent(self, which, value):
font = list(self.font)
font[which] = value
self.font = tuple(font)
if self.entry:
self.entry.config(font=self.font)


def setFace(self, face):
if face in ['helvetica','arial','courier','times roman']:
self._setFontComponent(0, face)
else:
raise GraphicsError(BAD_OPTION)

def setSize(self, size):
if 5 <= size <= 36:
self._setFontComponent(1,size)
else:
raise GraphicsError(BAD_OPTION)

def setStyle(self, style):
if style in ['bold','normal','italic', 'bold italic']:
self._setFontComponent(2,style)
else:
raise GraphicsError(BAD_OPTION)

def setTextColor(self, color):
self.color=color
if self.entry:
self.entry.config(fg=color)


class Image(GraphicsObject):

idCount = 0
imageCache = {} # tk photoimages go here to avoid GC while drawn

def __init__(self, p, *pixmap):
GraphicsObject.__init__(self, [])
self.anchor = p.clone()
self.imageId = Image.idCount
Image.idCount = Image.idCount + 1
if len(pixmap) == 1: # file name provided
self.img = tk.PhotoImage(file=pixmap[0], master=_root)
else: # width and height provided
width, height = pixmap
self.img = tk.PhotoImage(master=_root, width=width, height=height)

def __repr__(self):
return "Image({}, {}, {})".format(self.anchor, self.getWidth(), self.getHeight())

def _draw(self, canvas, options):
p = self.anchor
x,y = canvas.toScreen(p.x,p.y)
self.imageCache[self.imageId] = self.img # save a reference
return canvas.create_image(x,y,image=self.img)

def _move(self, dx, dy):
self.anchor.move(dx,dy)

def undraw(self):
try:
del self.imageCache[self.imageId] # allow gc of tk photoimage
except KeyError:
pass
GraphicsObject.undraw(self)

def getAnchor(self):
return self.anchor.clone()

def clone(self):
other = Image(Point(0,0), 0, 0)
other.img = self.img.copy()
other.anchor = self.anchor.clone()
other.config = self.config.copy()
return other

def getWidth(self):
"""Returns the width of the image in pixels"""
return self.img.width()

def getHeight(self):
"""Returns the height of the image in pixels"""
return self.img.height()

def getPixel(self, x, y):
"""Returns a list [r,g,b] with the RGB color values for pixel (x,y)
r,g,b are in range(256)

"""

value = self.img.get(x,y)
if type(value) == type(0):
return [value, value, value]
elif type(value) == type((0,0,0)):
return list(value)
else:
return list(map(int, value.split()))

def setPixel(self, x, y, color):
"""Sets pixel (x,y) to the given color

"""
self.img.put("{" + color +"}", (x, y))


def save(self, filename):
"""Saves the pixmap image to filename.
The format for the save image is determined from the filname extension.

"""

path, name = os.path.split(filename)
ext = name.split(".")[-1]
self.img.write( filename, format=ext)


def color_rgb(r,g,b):
"""r,g,b are intensities of red, green, and blue in range(256)
Returns color specifier string for the resulting color"""
return "#%02x%02x%02x" % (r,g,b)

def test():
win = GraphWin()
win.setCoords(0,0,10,10)
t = Text(Point(5,5), "Centered Text")
t.draw(win)
p = Polygon(Point(1,1), Point(5,3), Point(2,7))
p.draw(win)
e = Entry(Point(5,6), 10)
e.draw(win)
win.getMouse()
p.setFill("red")
p.setOutline("blue")
p.setWidth(2)
s = ""
for pt in p.getPoints():
s = s + "(%0.1f,%0.1f) " % (pt.getX(), pt.getY())
t.setText(e.getText())
e.setFill("green")
e.setText("Spam!")
e.move(2,0)
win.getMouse()
p.move(2,3)
s = ""
for pt in p.getPoints():
s = s + "(%0.1f,%0.1f) " % (pt.getX(), pt.getY())
t.setText(s)
win.getMouse()
p.undraw()
e.undraw()
t.setStyle("bold")
win.getMouse()
t.setStyle("normal")
win.getMouse()
t.setStyle("italic")
win.getMouse()
t.setStyle("bold italic")
win.getMouse()
t.setSize(14)
win.getMouse()
t.setFace("arial")
t.setSize(20)
win.getMouse()
win.close()

#MacOS fix 2
#tk.Toplevel(_root).destroy()

# MacOS fix 1
update()

if __name__ == "__main__":
test()


uh i think thats all? stay tuned :D
BoomBoy
OFFLINE
Trainerlevel: 77

Forum Posts: 600
Posted: Tue, 02/02/2021 10:12 (3 Years ago)

Title: AUTOMATIC CLICKLIST GENERATOR

clues in the title. instructions are in the code. the only library required is subprocess, for copying to the clipboard, but if you cant be bothered put a # before line 1 and line 49. line 49 may throw an error on mac; i think you need to change the "clip" parameter to something but not sure what lol.

code:
Show hidden content
import subprocess
print("Below each of the prompts copy-paste the pokemon profile, page, interaction screen or something with its id in, it doesnt really matter lol. to compile the clicklist, type 'stop'.")

def get():
links = []
link = input("link to add to clicklist: ")
while link != "stop" and link != "":
links.append(link)
link = input("link to add to clicklist: ")
return links

def splicer(links):
IDs = []
for link in links:
print(link)
idPassed = False
start = 0
for i in range(0,len(link)):
char = link[len(link)-i-1]
if char in "1234567890" and not idPassed:
idPassed = True
end = i
if not char in "1234567890" and idPassed:
start = i
break
IDs.append(link[len(link)-(start):len(link)-(end)])
return IDs

def compiler(IDs):
clicklist = "https://pokeheroes.com/pokemon_lite?cl_type=custom"
ret = input("Whos profile would you like this clicklist to return you to? Leave blank for none: ")
if ret != "":
clicklist += "&ret=userprofile?name%3D"
clicklist += ret

count=0
for ID in IDs:
print(ID)
clicklist += "&id%5B%5D="
clicklist += ID
count +=1
print("Your clicklist has "+str(count)+" mons in it :)")
return clicklist

loop = "abc"
while loop != "":
links = get()
print("\nworking...")
IDs = splicer(links)
clicklist = compiler(IDs)
subprocess.run("clip", universal_newlines=True, input=clicklist)
print("Your custom clicklist has been created and copied to your clipboard.\n\nClicklist:" + clicklist)
loop = input("\nWould you like to create another clicklist? if you would like to exit the program just hit enter, otherwise type anything: ")

its fairly simple: get() takes a list from a series of inputs; splicer() takes the last run of numbers from the string - you can put the pokemon id eg. "30966933", the pokemon page eg. "https://pokeheroes.com/pokemon?id=30966933" or anything basically containing the pokemon id eg. "so this is a bunch of text that the program is gonna ignore and the id of the pokemon is 30966933 and then a bit more text just to prove the program's potency" and all three when put through splicer will return 30966933; and compiler() will take the list of pokemon IDs, create the clicklist, ask if you want to return to someone's profile and iterate through the list adding each one to the link. fairly simple ig. oh yeah then the main block takes the link, prints it, copies it to your clipboard, and asks you if you would like to create another (for QoL ig)

any queries dont hesitate to palpad me :D
BoomBoy
OFFLINE
Trainerlevel: 77

Forum Posts: 600
Posted: Sun, 28/02/2021 10:43 (3 Years ago)

Title: Hangman practisificationiser

uh yeah so this one requires quite a few files :) but its pretty cool
images are linked btw

Quote from filesHANGMAN
-> hangman.py
-> graphics.py
-> scores.txt
-> hangmen
|--> 0.png
|--> 1.png
|--> 2.png
|--> 3.png
|--> 4.png
|--> 5.png
|--> 6.png

inside scores.txt write this:
Quote from scores.txt
0 current streak
0 highest streak
0 total won
0 total won this run


um. fairly self-explanatory i think? this also requires the random module :)
Show hidden content
from graphics import *
import random as r

database = ["concentration", "trainerpoints", "mew", "muk", "advent raffle ticket", "celadon city gym", "deep sea scale", "deep sea tooth", "dream world shop", "easter egg hunt", "egg radar chip", "elite four drake", "elite four glacia", "elite four phoebe", "ever grande city", "global trade station", "golden game chip", "golden game chips", "higher or lower", "ice cream cornet", "large candy bag", "mega easter lopunny", "mega mewtwo x", "mewton m meowth", "new bark town", "old amber fossil", "prof rowans lab", "red lunar wing", "roar of time", "suggest a word", "wonder trade station", "absorb bulb", "acid armor", "acro bike", "advanced path", "aerial ace", "aguav berry", "air balloon", "alpha sapphire", "amulet coin", "ancient cave", "anger point", "anniversary gift", "apicot berry", "armor fossil", "ash ketchum", "aspear berry", "aspertia city", "attack order", "auction house", "aura sphere", "aurora beam", "autumn abra", "autumn alakazam", "autumn kadabra", "babiri berry", "badge case", "badge set", "battle frontier", "battle shop", "battle team", "beginner path", "belue berry", "berry garden", "big mushroom", "big nugget", "big nuggets", "big root", "black kyurem", "blast burn", "blaze kick", "blue flute", "blue meteorite", "blue orb", "bluk berry", "brave bird", "bright beach", "brown sack", "bubble beam", "bug gem", "buried relic", "burn drive", "burn heal", "candy belly", "capture rate", "castform cast", "catch rate", "celadon city", "cerulean city", "cerulean gym", "champion alder", "champion cynthia", "champion diantha", "champion steven", "champion wallace", "charti berry", "cheri berry", "chesto berry", "chilan berry", "chill drive", "chople berry", "claw fossil", "coba berry", "colbur berry", "cornn berry", "cosplay pikachu", "cover fossil", "crystal crossing", "current weather", "cursed rapidash", "custap berry", "daily reward", "dark gem", "dark orb", "dark ponyta", "dawn stone", "day care", "daycare man", "daycare owner", "dazzling gleam", "desolate land", "dire hit", "discount coupon", "disguised exeggcute", "distortion world", "dome fossil", "doom desire", "double slap", "douse drive", "dowsing machine", "dowsing mchn", "draco meteor", "draco plate", "dragon ascent", "dragon dance", "dragon gem", "dragon rage", "dragon rush", "dragon scale", "dragon type", "draining kiss", "dread plate", "dream ball", "dream world", "drenched bluff", "drill rotom", "dubious disc", "durin berry", "dusk stone", "earth plate", "easter buneary", "easter bunnelby", "easter diggersby", "easter egg", "easter eggs", "easter event", "easter hunt", "easter lopunny", "egg hunt", "egg radar", "egg storage", "electric gem", "elite four", "emera bank", "emera beach", "emera mall", "emera square", "emera town", "endless path", "enigma berry", "enigma pearl", "enigma stone", "eon ticket", "eternal tower", "event distribution", "event egg", "event pass", "event pokemon", "event shop", "exp share", "explorer bag", "explorer kit", "fairy gem", "fan rotom", "fashion case", "festival gardevoir", "fiery furnace", "fiesta larvesta", "fighting gem", "figy berry", "fire blast", "fire fang", "fire gem", "fire punch", "fire stone", "fire type", "fist plate", "flame orb", "flame plate", "flame thrower", "flame wheel", "flare blitz", "flash fire", "flower boy", "flower girl", "flying gem", "foggy castform", "forum thread", "frenzy plant", "frost rotom", "full potion", "fury cutter", "fury swipes", "game center", "game chip", "game chips", "game freak", "gameboy advance", "ganlon berry", "gary oak", "gem collector", "gem cauldron", "gem exchange", "ghost gem", "giga impact", "giratina quest", "glacier palace", "glitch city", "golden pokeball", "golden slot", "gracidea flower", "grass gem", "great ball", "green orb", "grepa berry", "griseous orb", "ground gem", "gym badge", "haban berry", "halloween sweets", "harvest sprite", "hazy pass", "heal order", "heart scale", "heat rotom", "helix fossil", "helping hand", "hidden ability", "hidden power", "hoenn certificate", "hondew berry", "honey iar", "honey tree", "hydro cannon", "hydro pump", "hyper beam", "iapapa berry", "ice beam", "ice gem", "ice heal", "ice punch", "ice shard", "icicle plate", "indigo league", "insect plate", "iron defense", "iron plate", "iron tail", "item bag", "item delivery", "item shop", "jaboca berry", "jade orb", "jaw fossil", "johto certificate", "kalos certificate", "kanto certificate", "kanto league", "kasib berry", "kebia berry", "kee berry", "kelpsy berry", "key stone", "knight axew", "lake valor", "lansat berry", "lava cookie", "lavender town", "leaf stone", "leech life", "legendary dogs", "leppa berry", "liechi berry", "light ball", "light screen", "light stone", "lightstone cave", "link cable", "littleroot town", "lord salamance", "lum berry", "lunar wing", "mach bike", "machine part", "magical leaf", "mago berry", "magost berry", "maranga berry", "marine cave", "master ball", "max repel", "meadow plate", "medal rally", "mega able", "mega aggron", "mega alakazam", "mega audino", "mega banette", "mega charizard", "mega diancie", "mega evolution", "mega gallade", "mega garchomp", "mega gengar", "mega glalie", "mega lopunny", "mega mawile", "mega mewtwo", "mega pidgeot", "mega pokemon", "mega rayquaza", "mega ring", "mega sableye", "mega salamence", "mega scizor", "mega steelix", "mega stone", "mega yorebro", "metal coat", "meteorite castform", "mewtwonite y", "micle berry", "mind plate", "misc settings", "misdreavus cosplay", "mixer rotom", "moomoo milk", "moomoo ranch", "moon stone", "mossdeep city", "mossy forest", "mow rotom", "mr bagon", "mr mime", "mt moon", "mt silver", "mysterious tree", "mystery box", "mystery dungeon", "mystery egg", "mystery key", "nanab berry", "night slash", "nightmare munna", "nintendo ds", "nomel berry", "normal gem", "notification wall", "nurse ioy", "nuvema town", "oblivion wing", "occa berry", "odd incense", "officer ienny", "old amber", "omega ruby", "ominous wind", "oran berry", "orange islands", "oval stone", "pal pad", "pallet town", "pamtre berry", "paralyze heal", "pass orb", "passho berry", "payapa berry", "pecha berry", "permanent ban", "persim berry", "petal dance", "petaya berry", "pika pika", "pinap berry", "pixie plate", "plume fossil", "pocket monsters", "poison gem", "poke ball", "pokeheroes wiki", "pokemon amie", "pokemon league", "pokemon master", "pokemon movie", "pokemon ranger", "pokeradar chain", "poll manager", "pomeg berry", "power anklet", "power band", "power belt", "power bracer", "power lens", "power weight", "primal groudon", "primal kyogre", "primal reversion", "primordial sea", "princess smoochum", "prism scale", "prison bottle", "privacy policy", "private message", "prize exchange", "pro path", "prof birch", "prof rowan", "professor birch", "professor oak", "professor rowan", "psychic gem", "puzzle collection", "qualot berry", "queen iynx", "quick attack", "quick ball", "rabuta berry", "radio tower", "rain badge", "rain dance", "rainbow wing", "rambo rumble", "rare bone", "rare candy", "rawst berry", "razor claw", "razor fang", "razor leaf", "razz berry", "reaper cloth", "red meteorite", "red orb", "relic band", "relic copper", "relic crown", "relic gold", "relic silver", "relic statue", "relic vase", "resolute stone", "retro starters", "rindo berry", "rock blast", "rock gem", "rocky cave", "rodeo scraggy", "root fossil", "roseli berry", "rowap berry", "royal tunnel", "ruby valley", "rumble area", "rumble mission", "rumble missions", "run away", "sacred ash", "safari ball", "safari zone", "sail fossil", "salac berry", "santa birb", "santa bird", "scary glasses", "scope lens", "secret base", "seed bomb", "seller clothes", "shiny chaining", "shiny charm", "shiny ditto", "shiny hunt", "shiny sprite", "shiny stone", "shoal shell", "shock drive", "shuca berry", "silent forest", "silph co", "silver wing", "sinnoh certificate", "sir haxelot", "sir shelgon", "sitrus berry", "skull fossil", "sky pillar", "sky plate", "sky uppercut", "slow start", "small nugget", "snowy castform", "snowy mountains", "soda pop", "solar beam", "soothe bell", "space spinda", "spear pillar", "speed click", "spelon berry", "splash plate", "spooky manor", "spooky plate", "spray duck", "spring ampharos", "spring flaaffy", "spring mareep", "spring update", "ss anne", "ss aqua", "ss tidal", "star piece", "starf berry", "steam eruption", "steel gem", "steven stone", "stone plate", "string shot", "strong earthquakes", "sugar shock", "summer ampharos", "sun stone", "super breloomio", "super honey", "super rod", "super shroom", "super training", "surfing pikachu", "sweet heart", "swords dance", "tail whip", "tall grass", "tamato berry", "tanga berry", "team aqua", "team flare", "team magma", "team plasma", "team rocket", "technical machine", "terra cave", "thunder punch", "tiny mushroom", "tom nook", "toxic orb", "toxic plate", "trainer red", "treasure hunt", "twinleaf town", "ultra ball", "union cave", "union room", "unova certificate", "van bagon", "vaniville town", "vine whip", "viridian city", "volt absorb", "volt switch", "volt tackle", "vs seeker", "wacan berry", "wailmer pail", "wash rotom", "water gem", "water gun", "water stone", "watmel berry", "weather balloon", "weather channel", "weather forecast", "wepear berry", "whipped dream", "white hand", "white kyurem", "wide lens", "wiki berry", "windy prairie", "winter camerupt", "winter numel", "wonder guard", "wonder trade", "wood hammer", "x attack", "x defense", "x speed", "yache berry", "yellow forest", "yellow meteorite", "zap cannon", "zap plate", "zero isle", "abra", "aqua", "aron", "axew", "bold", "chef", "iynx", "natu", "onix", "sawk", "seel", "uxie", "xatu", "absol", "aipom", "almia", "anime", "azelf", "badge", "bagon", "beach", "berry", "black", "brock", "bugsy", "candy", "catch", "cilan", "clair", "curse", "deino", "ditto", "doduo", "eevee", "ekans", "ember", "emera", "ether", "event", "fairy", "fiore", "flare", "flash", "forum", "ghost", "gible", "gloom", "golem", "goomy", "grass", "growl", "hatch", "hoenn", "hoggy", "honey", "inkay", "iames", "iohto", "kalos", "kanto", "klang", "klink", "lance", "level", "lotad", "lugia", "luxio", "mimic", "minun", "misty", "mouse", "muggy", "munna", "nappy", "nessy", "numel", "omega", "paras", "party", "pichu", "quest", "ralts", "retro", "riolu", "rival", "rotom", "round", "route", "rowan", "royal", "rules", "salon", "shinx", "shiny", "snivy", "spore", "staff", "staid", "swift", "tepig", "throh", "timid", "toxic", "trade", "types", "unova", "unown", "users", "wally", "water", "yanma", "zorua", "zubat", "adaptability", "aromatherapy", "casteliacone", "crabominable", "deepseascale", "deepseatooth", "flamethrower", "interactions", "notification", "slowpoketail", "thundershock", "thunderstone", "tinymushroom", "trainerlevel", "trainerpoint", "undiscovered", "buttercream", "cocktaillon", "electirizer", "ferrerocoal", "fletchinder", "frustration", "gemcauldron", "gemexchange", "interaction", "lucarionite", "pachirisnow", "sandcrustle", "scattercube", "synchronize", "thunderbolt", "acrobatics", "aerodactyl", "applewoodo", "aromatisse", "barbaracle", "bellsprout", "bonemerang", "bouffalant", "butterfree", "carracosta", "catercream", "chandelure", "charmander", "charmeleon", "chesnaught", "cofagrigus", "conkeldurr", "crabhammer", "crabrawler", "darmanitan", "dirndltank", "earthquake", "eelektross", "electabuzz", "electivire", "escavalier", "feraligatr", "ferrothorn", "fletchling", "forretress", "friendship", "galvantula", "gamecenter", "generation", "gingergoat", "gothitelle", "groomicott", "helioptile", "herowalker", "hippopotas", "hitmonchan", "honeycombs", "ikkakugong", "incineroar", "iigglypuff", "kangaskhan", "karrablast", "kricketune", "krookodile", "lickilicky", "lillibride", "magmarizer", "masquerain", "misdreavus", "moderators", "playground", "pokedollar", "pokeheroes", "pokewalker", "roggenrola", "sandwebble", "scatterbug", "seismitoad", "spewbrella", "talonflame", "tentacruel", "togedemaru", "typhlosion", "valenfloon", "victreebel", "weepinbell", "whimsicott", "whirlipede", "wigglytuff", "abomasnow", "aegislash", "aggronite", "alomomola", "amoonguss", "awakening", "azumarill", "bastiodon", "beautifly", "bellossom", "blastoise", "blossomly", "bulbasaur", "cacophony", "carnivine", "charizard", "charjabug", "chikorita", "chingling", "clauncher", "clawfairy", "clawitzer", "clicklist", "combusken", "community", "constrict", "cosmoneon", "cottonblu", "crawdaunt", "cresselia", "cryogonal", "cuddlithe", "cyndaquil", "decidueye", "derpatung", "diggersby", "discharge", "dragonair", "dragonite", "druddigon", "dunsparce", "eelektrik", "electrike", "electrode", "everstone", "evolution", "excadrill", "exeggcute", "exeggutor", "ferroseed", "frogadier", "gardevoir", "girafarig", "gothorita", "gourgeist", "growlithe", "heliolisk", "heracross", "hippowdon", "hitmonlee", "hitmontop", "honchkrow", "honeycomb", "honeytree", "hydreigon", "igglybuff", "infernape", "iellicent", "iudgement", "klinklang", "kricketot", "larviprop", "latiasite", "leftovers", "legendary", "lepreowth", "lickitung", "lightblim", "lilligant", "lovemeter", "machotide", "magmortar", "magnemite", "magnezone", "mamoswine", "mandibuzz", "manectric", "marshtomp", "metacream", "metagross", "metronome", "mightyena", "mismagius", "missingno", "nidoqueen", "ninetails", "ninetales", "octazooka", "octillery", "pachirisu", "palossand", "palpitoad", "paralysis", "paralyzed", "pidgeotto", "piloswine", "pokeblock", "pokeradar", "pokeworld", "poliwhirl", "poliwrath", "poochyena", "probopass", "professor", "protector", "pumpkaboo", "quilladin", "rampardos", "regigigas", "registeel", "relicanth", "reuniclus", "rhyperior", "salamence", "sandshrew", "sandslash", "sandstorm", "sandygast", "scolipede", "serperior", "shiinotic", "shroomish", "spiritomb", "sprayduck", "staraptor", "stoutland", "sudowoodo", "tangrowth", "teddiursa", "telepathy", "tentacool", "terrakion", "thundurus", "toucannon", "toxicroak", "tranquill", "trevenant", "tyranitar", "tyrantrum", "valentine", "vanillish", "vanillite", "vanilluxe", "venoshock", "vespiquen", "vileplume", "volcarona", "wartortle", "wobbuffet", "zebstrika", "zigzagoon", "accelgor", "alakazam", "ampharos", "antidote", "apricorn", "arcaddly", "arcanine", "archeops", "articuno", "barboach", "beachamp", "beedrill", "beheeyem", "bergmite", "berrydex", "blaziken", "braviary", "bronzong", "bunnelby", "cacturne", "camerupt", "candaria", "carvanha", "castform", "caterpie", "champion", "chatquiz", "chimchar", "chimecho", "chinchou", "chocoluv", "cinccino", "clamperl", "clefable", "clefairy", "cloyster", "cobalion", "coinflip", "contrary", "corphish", "cottonee", "cranidos", "croagunk", "croconaw", "darumaka", "database", "delcatty", "delibird", "delivery", "doublade", "dragalge", "dralucha", "drifblim", "driflamp", "drifloon", "ducklett", "dusclops", "dusknoir", "electric", "empoleon", "eviolite", "fennekin", "floatzel", "frillish", "froslass", "gambling", "gametime", "garbodor", "garchomp", "genesect", "geomancy", "gigalith", "giratina", "glaciate", "gomaseel", "gorebyss", "gracidea", "granbull", "graveler", "greninja", "gumshoos", "gyarados", "hariyama", "hawlucha", "heartomb", "herochat", "hoothoot", "houndoom", "houndour", "illumise", "illusion", "interact", "iesterig", "iumpluff", "kabutops", "krokorok", "landorus", "larvesta", "larvitar", "leavanny", "lemonade", "lillipup", "ludicolo", "lumineon", "lunatone", "magcargo", "magikarp", "magneton", "makuhita", "maractus", "mareanie", "medicham", "meditite", "meganium", "meloetta", "meowstic", "mienshao", "mikoshao", "minccino", "monferno", "morelull", "mudsdale", "munchlax", "musharna", "mushroom", "nidoking", "nidorina", "nidorino", "nintendo", "nosepass", "oshawott", "overheat", "parasect", "pawniard", "pelipper", "perchaun", "phantump", "pokeball", "pokegear", "pokehero", "polestar", "politoed", "primeape", "prinplup", "purrloin", "quagsire", "qwilfish", "raitoshi", "ranklist", "rapidash", "raticate", "rayquaza", "regirock", "remoraid", "reshiram", "ribombee", "roleplay", "roserade", "rumbling", "samurott", "sapphire", "sceptile", "settings", "sewaddle", "sharpedo", "shedinja", "shellder", "shieldon", "shipping", "sigilyph", "simipour", "simisage", "simisear", "skarmory", "skiploom", "skuntank", "slowking", "slowpoke", "slowyore", "slurpuff", "smeargle", "smoochum", "snowbuck", "snowling", "snubbull", "spinarak", "spritzee", "squirtle", "stantler", "staravia", "stardust", "starters", "strength", "struggle", "stunfisk", "sunflora", "swadloon", "swampert", "tirtouga", "togekiss", "tornadus", "torracat", "torterra", "totodile", "training", "trapinch", "treasure", "trubbish", "trumbeak", "tsareena", "unfezant", "ursaring", "userlist", "username", "vaporeon", "venipede", "venomoth", "venusaur", "vigoroth", "virizion", "vivillon", "whiscash", "yoreking", "zangoose", "zweilous", "agility", "altaria", "ambipom", "anorith", "ariados", "armaldo", "auction", "aurorus", "avalugg", "azurill", "banette", "bayleef", "beartic", "begging", "bibarel", "binacle", "bisharp", "blissey", "blitzle", "boldore", "braixen", "breloom", "brionne", "bronzor", "buneary", "calcium", "carbink", "cascoon", "chansey", "cherrim", "cherubi", "chespin", "claydol", "contest", "corsola", "cosmoem", "cradily", "crustle", "cubchoo", "cynthia", "darkrai", "dartrix", "daycare", "dedenne", "defense", "delphox", "dewgong", "diancie", "diglett", "donphan", "drapion", "dratini", "drilbur", "drowzee", "dugtrio", "dungeon", "duosion", "duskull", "dwebble", "element", "emerald", "exploud", "fainted", "finneon", "fishing", "flaaffy", "flareon", "foongus", "fraxure", "froakie", "furfrou", "gallade", "gameboy", "geodude", "ghetsis", "glaceon", "glameow", "gliscor", "gloweon", "goldeen", "golduck", "gothita", "groudon", "grovyle", "grubbin", "grumpig", "gurdurr", "hangman", "happiny", "harvest", "hashtag", "haunter", "haxorus", "heatmor", "heatran", "herdier", "honedge", "huntail", "ivysaur", "iirachi", "iolteon", "iuniper", "kadabra", "kecleon", "ketchum", "kinesis", "kingdra", "kingler", "koffing", "lampent", "lanturn", "leafeon", "liepard", "linoone", "litwick", "lopunny", "lottery", "loudred", "lucario", "lumiday", "luvdisc", "machamp", "machoke", "malamar", "manaphy", "mantine", "mantyke", "marowak", "mesprit", "metapod", "mienfoo", "mikofoo", "milotic", "miltank", "mission", "moltres", "mudbray", "murkrow", "nincada", "ninjask", "noctowl", "noivern", "nuzleaf", "omanyte", "omastar", "pancham", "pangoro", "panpour", "pansage", "pansear", "persian", "petilil", "pidgeot", "pignite", "pikachu", "plushie", "pokedex", "pokemon", "pokerus", "poliwag", "porygon", "protein", "psychic", "psyduck", "pupibot", "pupitar", "purugly", "quilava", "rattata", "raylong", "remakes", "rhyhorn", "roselia", "rufflet", "sableye", "sandile", "satochu", "scanner", "scrafty", "scraggy", "scyther", "seaking", "seatran", "sentret", "servine", "seviper", "shaymin", "shelgon", "shelmet", "shiftry", "shinies", "shuckle", "shuppet", "silcoon", "skorupi", "slaking", "slakoth", "sliggoo", "slowbro", "sneasel", "snorlax", "snorunt", "solosis", "solrock", "spearow", "spriter", "starmie", "starter", "steelix", "steenee", "suicune", "sunkern", "surskit", "swagger", "swellow", "swirlix", "swoobat", "sylveon", "taillow", "tangela", "timburr", "togetic", "toraros", "torchic", "torkoal", "toxapex", "trading", "trainer", "treecko", "tropius", "turtwig", "tympole", "tyrogue", "umbreon", "venonat", "vibrava", "victini", "vitamin", "volbeat", "volkner", "voltorb", "vullaby", "wailmer", "wailord", "walrein", "watchog", "weather", "weavile", "weezing", "whismur", "wingull", "wurmple", "xerneas", "yanmega", "yorebro", "yveltal", "zomppet", "zoroark", "zygarde", "aggron", "amaura", "arceus", "archen", "attack", "audino", "aurora", "avatar", "baltoy", "battle", "beldum", "bidoof", "bonsly", "bubble", "buizel", "cacnea", "carbos", "celebi", "chatot", "clawfa", "cleffa", "combee", "crobat", "cubone", "deoxys", "dewott", "dialga", "dodrio", "dragon", "drampa", "durant", "dustox", "eggdex", "elekid", "elgyem", "emboar", "emolga", "espeon", "espurr", "fearow", "feebas", "flygon", "flying", "fossil", "frozen", "furret", "gabite", "gaming", "gastly", "gengar", "glalie", "gligar", "glitch", "gogoat", "golbat", "golett", "golurk", "goodra", "grimer", "grotle", "ground", "gulpin", "harden", "helper", "hoppip", "horsea", "impish", "joltik", "kabuto", "kakuna", "keldeo", "kirlia", "klefki", "komala", "krabby", "kyogre", "kyurem", "lairon", "lapras", "latias", "latios", "ledian", "ledyba", "legend", "lileep", "litleo", "lombre", "luxray", "machop", "magmar", "mankey", "mareep", "marill", "master", "masuda", "mawile", "meowth", "metang", "mewtwo", "milker", "mothim", "mudkip", "noibat", "normal", "nugget", "oddish", "palkia", "palpad", "patrat", "phanpy", "phione", "pickup", "pidgey", "pidove", "pineco", "pinsir", "piplup", "plusle", "poison", "ponyta", "potion", "primal", "puzzle", "pyroar", "raffle", "raichu", "raikou", "regice", "rescue", "revive", "rhydon", "rokkyu", "rumble", "sachet", "safari", "scizor", "seadra", "sealeo", "seedot", "serena", "sinnoh", "skiddo", "skitty", "skrelp", "skugar", "slugma", "snover", "spewpa", "spheal", "spinda", "spoink", "sprite", "starly", "staryu", "steven", "stunky", "summon", "swablu", "swalot", "swanna", "swinub", "tackle", "tauros", "togepi", "truant", "tunnel", "tynamo", "tyrunt", "uproar", "vulpix", "weedle", "woobat", "wooper", "wynaut", "yamask", "zapdos", "zekrom"]

def main(prev=0):
mainWin = GraphWin("",800,200)
bg = Rectangle(Point(0,0),Point(200,200))
bg.setFill("#FF3333")
bg.draw(mainWin)
if prev==1: text = Text(Point(100,100),"PLAY SINGLEPLAYER
AGAIN")
else: text = Text(Point(100,100),"PLAY SINGLEPLAYER")
text.setTextColor("#0000FF")
text.setStyle("bold")
text.draw(mainWin)

bg = Rectangle(Point(200,0),Point(400,200))
bg.setFill("#FF33FF")
bg.draw(mainWin)
if prev==2: text = Text(Point(300,100),"PLAY MULTIPLAYER
AGAIN")
else: text = Text(Point(300,100),"PLAY MULTIPLAYER")
text.setTextColor("#FFFF00")
text.setStyle("bold")
text.draw(mainWin)

bg = Rectangle(Point(400,0),Point(600,200))
bg.setFill("#3333FF")
bg.draw(mainWin)
text = Text(Point(500,100),"EXIT GAME")
text.setTextColor("#00FFFF")
text.setStyle("bold")
text.draw(mainWin)

bg = Rectangle(Point(600,0),Point(800,200))
bg.setFill("#000000")
bg.draw(mainWin)
text = Text(Point(700,100),"VIEW SCORES")
text.setTextColor("#FFFFFF")
text.setStyle("bold")
text.draw(mainWin)

click = 600
while click >= 600:
click = mainWin.getMouse().x
if click < 200:
mainWin.close()
choose(1)
elif click < 400:
mainWin.close()
choose(2)
elif click < 600: mainWin.close()
else: showScores()

def choose(players):
if players == 1:
word = database[r.randint(0,len(database)-1)]
#print(word)
guess(word,players)
else:
chooseWin = GraphWin("choose",600,100)
text = Text(Point(300,30),"CHOOSE A WORD FOR YOUR OPPONENT TO GUESS (make it hard :'P ) NO CAPS PLEASE")
text.setSize(12)
text.draw(chooseWin)
entry = Entry(Point(245,70),30)
entry.setFill("#CCCCCC")
entry.setText(database[r.randint(0,len(database))])
entry.draw(chooseWin)
button = Rectangle(Point(495,55),Point(595,95))
button.setFill("#00FF00")
button.draw(chooseWin)
text = Text(Point(545,75),"CHOOSE")
text.setSize(15)
text.setStyle("bold")
text.draw(chooseWin)

click = chooseWin.getMouse()
clickX,clickY = click.x,click.y

while clickX < 495 or clickX > 595 or clickY < 55 or clickY > 95:
click = chooseWin.getMouse()
clickX,clickY = click.x,click.y
chooseWin.close()
guess(entry.getText(),players)

def guess(word,players):
guessed = ""
for i in word:
if i == " ": guessed += " "
elif i in "abcdefghijklmnopqrstuvwxyz": guessed += "_"
else:
choose(players)
# print(guessed)
lives = 6
guessWin = GraphWin("guess",800,290)

Word = Text(Point(300,240),guessed)
Word.setSize(30)
Word.setFace("courier")
Word.draw(guessWin)

img = Image(Point(700,145),"hangmen/0.png")
img.draw(guessWin)
text = Text(Point(300,100),"TYPE A LETTER ON THE KEYBOARD")
text.draw(guessWin)

Guessed = False
while not Guessed and lives > 0:
guess = guessWin.getKey()
if not guess in "abcdefghijklmnopqrstuvwxyz": pass
else:
temp = ""

loseLife = True
Guessed = True
for i in range (len(word)):
# guessed += " "
if word[i] == " ": temp += " "
elif word[i] == guess:
temp += guess
loseLife = False
elif not (guessed[i] == "_"):
temp += guessed[i]
else:
temp += "_"
Guessed = False

if loseLife: lives -= 1
guessed = temp
Word.setText(temp)
Word.undraw()
Word.draw(guessWin)

img.undraw()
img = Image(Point(700,145),"hangmen/"+str(6-lives)+".png")
img.draw(guessWin)

scores = open("scores.txt","r")
curStreak = int(scores.readline()[0])
highStreak= int(scores.readline()[0])
totalWon = int(scores.readline()[0])
wonToday = int(scores.readline()[0])
scores.close()

if Guessed and players==1:
curStreak+=1
totalWon+=1
wonToday+=1
if curStreak > highStreak: highStreak = curStreak

elif lives==0 and players==1: curStreak=0

c = str(curStreak)
h = str(highStreak)
t = str(totalWon)
w = str(wonToday)

scores = open("scores.txt","w")
scores.write(c+" current streak
"+h+" highest streak
"+t+" total won
"+w+" total won this run")
scores.close()

guessWin.close()

main(players)


def showScores():
scores = open("scores.txt","r")
for i in scores:
print(i[2:len(i)-1]+": "+i[0])
scores.close()

#SCORES ARE ONLY FOR SINGLEPLAYER
scores = open("scores.txt","r")
curStreak = scores.readline()[0]
highStreak= scores.readline()[0]
totalWon = scores.readline()[0]
scores.close()

if curStreak > highStreak: highStreak=curStreak
scores = open("scores.txt","w")
scores.write(curStreak+" current streak
"+highStreak+" highest streak
"+totalWon+" total won
0 total won this run")
scores.close()
main()


i could explain all of this or i could go do something else.... i think ill pick the latter :) basically: i have a menu with 4 options in squares. it picks up your mouse click on each of the windows and runs the corresponding function, passing all the relevant parameters so the function knows which function to call next :) the main fuctions are main() which is the menu, choose() which either randomly chooses a word or creates a window for the second player to choose a word in, and guess() which is where the player guesses. annoyingly, if you type the same incorrect letter twice it counts both of those and continues drawing the hangman so its not perfect....

*me realising it doesnt show indentations in [code] blocks.... um... problem xD if you know how to fix that please let me know :D