<file_sep># -*- coding: utf-8 -*-
"""
Created on Wed Dec 11 15:18:04 2019

@author: Rowland 
"""

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import math

print(np.pi)

print(math.pi)

t = np.arange(0.0, np.pi, 0.01)
s = np.sin(2 * np.pi * t)

fig, ax = plt.subplots()
ax.plot(t, s)

ax.set(xlabel="x axis", ylabel="y axis", title="Here's a sin function")
ax.grid()

fig.savefig("test.png")
plt.show()
<file_sep>import random
import sys

frame_string = "---%--->_<---%---"
print(frame_string)

# face text art
print("|--------|")
print("|--O--O--|")
print("|--------|")
print("|---[]---|")
print("|--------|")

# opening problem, a simple one
def opening():
    # creepy terminator message
    print("Hello Human. Play a game with me.")
    num_to_guess = random.randint(lower_range, upper_range)
    print("I\'ve just thought of a number between %d and %d" % (lower_range, upper_range))
    # prompt the user
    print("guess my number: ")
    user_guess = input()
    # compare values
    if(int(user_guess) == int(num_to_guess)):
        print("That was correct! Thanks for playing with me.")
    # elif
    
    else:
        print("Oops. Wrong guess. Better luck next time, human.")

# has number of chances to guess, with hints
def correction():
    # message
    print("Okay. It's your first time playing. Maybe I'll give you some help")
    lives = 3
    print("We'll play by the same rules, but this time I'll give your %s chances" % str(lives))
    print("If I'm happy, I might even give you some hints")

    num_to_guess = random.randint(lower_range, upper_range)
    strikes = 0
    # three chanced
    while strikes < lives:
        print("Take a guess:")
        user_guess = input()
        if(int(user_guess) == int(num_to_guess)):
            print("Well done, human.")
            break;
        else:
            "Hmmm. Not quite."
            strikes += 1
            # giving corrections
            if(int(user_guess) > num_to_guess):
                print("that one was too large")
            else:
                # no need to check for equal
                print("that one was too small")
    if(strikes >= lives):
        print("You've lost. Try harder.")
    elif(strikes < lives):
        print("Good guess. That was correct! And you had %d chances left" % (lives-strikes))


upper_range = 11
lower_range = 1
opening()
correction()
print("Well, that was fun for me. See you next time, human.")
print(frame_string)
sys.exit(0)



<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Dec 19 01:31:46 2019

Project: (Crappy) Decision Maker
@author: <NAME>
@contact: <EMAIL>
"""

import tkinter as tk
from tkinter import *
import tkinter.ttk as ttk
from tkinter import messagebox
from tkinter import Menu
from tkinter.ttk import Progressbar
import random

"""global variables"""
window = tk.Tk()
window_width = 700
window_height = 400

"""function declaration"""

def window_setup():
    window.title("App")
    window.option_add('*font', ('verdana', 12, 'bold'))
    window.configure(bg="Honeydew")
    window.geometry(str(window_width) + "x" + str(window_height))
    
def make_label(c, r):
    l = tk.Label(window, text="Test", font=("Arial Bold", 30))
    l.grid(column=c, row=r)

def make_menu():
    menu = Menu(window)
    menuSub = Menu(menu, tearoff=0)
    menuSub.add_command(label="Open")
    menuSub.add_separator()
    menuSub.add_command(label="New")
    menuSub.add_command(label="Create")
    menuSub.add_command(label="Error", command=popup)
    menu.add_cascade(label="File", menu=menuSub)
    menu.add_command(label="Exit")
    window.config(menu=menu)

def popup():
    messagebox.showerror("Error from menu", "You clicked the Error tab from menu")

def make_ui():
    """
    General layout:
        9x9 grid
        [combobox] | [Entry] | [label]
        [] | [button] | []
        [] | [Entry] | []
    """
    #combo box
    combo = ttk.Combobox(window)
    combo["values"] = ("Should", "Can", "Would", "Will")
    combo.current(0)
    #combo.grid(column=0, row=0)
    combo.pack()
    # combo.get(), similar to txtbox.get()
    #text box
    txtbox = tk.Entry(window, width=30)
    #txtbox.grid(column=1, row=0)
    txtbox.pack()
    txtbox.focus()
    # label
    label = tk.Label(window, text="?", font=("Arial Bold", 20))
    #label.grid(column=2, row=0)
    label.pack()
    
    def respond():
        num = random.randint(0, 1)
        if num == 0:
            output = "Yes"
        if num == 1:
            output = "No"
        response_label.configure(text="I think the answer is %s" % output)
    
    # button
    btn = tk.Button(window, text="Answer", command=respond)
    btn.configure(bg="sky blue", fg="azure")
    #btn.grid(column=1, row=1)
    btn.pack()
    # response label
    response_label = tk.Label(window, text="", font=("Arial Bold", 20))
    #response_label.grid(column=1, row=2)
    response_label.pack()

def main():
    window_setup()
    make_menu()
    make_ui()
    window.mainloop()
    
main()<file_sep># Beginner Python Project Collection
A collection of simple python programs I've written to document my journey of learning Python

## Project Contents thus far
### in chronological order
- hello world
- guess the number
- rock paper scissors
- matplotlib graphing test
- hangman
- tkinter gui experiment
- dummy decision maker
<file_sep># -*- coding: utf-8 -*-
"""
Created on Sun Dec 15 19:51:01 2019

@author: <NAME>
"""

# imports
import turtle
import time
import math
import random

class Coordinate:
    def __init__(self, x, y): # two dashes
        self.x = x
        self.y = y
    def getX(self):
        return self.x
    def getY(self):
        return self.y
    def setCor(self, x, y):
        self.x = x
        self.y = y

# window setup
def window_setup():
    w = turtle.Screen()
    w.title("Classic Snake")
    w.bgcolor("skyBlue")
    w.setup(width=screen_width, height=screen_height)
    w.tracer(0) # turns off screen update
    return w

# snake head
def make_snake_head(): 
    h = turtle.Turtle()
    h.shape("square")
    h.speed(0) #animation speed? fastest
    h.color("black")
    h.penup() #imagin lifting pen up, not tracing a line
    h.goto(0, 0)
    h.direction = "stop"
    return h

# food
def make_snake_food():
    f = turtle.Turtle()
    f.shape("circle")
    f.speed(0)
    f.color("Honeydew")
    f.penup()
    # position foor with random_food later
    return f

# global var
screen_width = 600
screen_height = 600
tick_time = 0.1
step_size = 5
last_loc = Coordinate(0, 0)
food_eaten = 0

window = window_setup()
food = make_snake_food()
head = make_snake_head()

def go_up():
    head.direction = "up"
def go_down():
    head.direction = "down"
def go_left():
    head.direction = "left"
def go_right():
    head.direction = "right"

def move():
    # update last tick location
    last_loc.setCor(head.xcor(), head.ycor())
    if head.direction == "up":
        y = head.ycor()
        head.sety(y + step_size)
    if head.direction == "down":
        y = head.ycor()
        head.sety(y - step_size)
    if head.direction == "left":
        x = head.xcor()
        head.setx(x - step_size)
    if head.direction == "right":
        x = head.xcor()
        head.setx(x + step_size)

def bounds_check():
    x = head.xcor()
    y = head.ycor()
    # print(str(window.screensize()[0]) + ", " + str(window.screensize()[1]))
    if (-screen_width/2 < x < screen_width/2) and (-screen_height/2 < y < screen_height/2):
        # print("still on screen")
        return True
    print("%d - %d" % (last_loc.getX(), last_loc.getY()))
    head.goto(last_loc.getX(), last_loc.getY())
    print("ouh, my head")
    head.direction = "stop"
    
    if head.direction == "up":
        pass
    if head.direction == "down":
        pass
    if head.direction == "left":
        pass
    if head.direction == "right":
        pass

mouth_range = 5
# check if the snake head is onto of food    
def food_check():
    head_x = head.xcor()
    head_y = head.ycor()
    food_x = food.xcor()
    food_y = food.ycor()
    delt_x = head_x - food_x
    delt_y = head_y - food_y
    distance = math.sqrt(delt_x**2 + delt_y**2)
    if distance < mouth_range:
        global food_eaten
        food_eaten = food_eaten + 1
        print("Yum! Score = %d" % food_eaten)
        # pseudo generate new food
        random_food()
    
def random_food():
    x = random.randint(-screen_width/2, screen_width/2)    
    y = random.randint(-screen_height/2, screen_height/2)
    position_food(x, y)
    
# we will be using the same food object, moving it to new locations to simulate new food
def position_food(x, y):
    food.goto(int(x), int(y))
    
game_puased = False
# pause the game
def puase():
    head.
    head.direction = "stop"
    pass

# resume from pause, if called without puase then does nothing
def resume():
    if not game_puased:
        return
    

# key binding
def key_bind():
    window.listen()
    window.onkeypress(go_up, "w") # note: onkeypress seems to not allow a method with parameters
    window.onkeypress(go_left, "a")
    window.onkeypress(go_down, "s")
    window.onkeypress(go_right, "d")
    
    window.onkeypress(pause, "p")
    window.onkeypress(resume, "r")

def main():
    # global variable initializing methods call on variable declaration
    #window_setup()
    #make_snake_head()
    
    key_bind()
    random_food() # initialize a food location
    
    # main game loop
    while True:
        window.update()
        move()
        food_check()
        bounds_check()
        time.sleep(tick_time)
    
    window.mainloop() # is essentially replaced by the infinite update loop

# calling main function
main()
<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Dec 12 15:07:49 2019

@author: <NAME>
"""

import random

# gloabal variable
targetWord = ""
stylelisticSeperator = "=============================="
unknown = "_"
chances = 5

# method definition

def main():
    print(stylelisticSeperator)
    print("Hello human. Welcom to a game of hangman.")
    global targetWord 
    targetWord = randomWord()
    print(stylelisticSeperator)
    queryUser()
    print(stylelisticSeperator)
    endGame()
    print(stylelisticSeperator)

def randomWord():
    file = open("words_Xethron.txt", "r")
    if file.mode == "r":
        print("using words from %s" % file.name)
        # contents = file.read()
        # print(contents)
        
        fileLines = file.readlines()
        
        lineCount = 0
        for line in fileLines:
            lineCount += 1
            line = line.strip()
            # print("%d - %s" % (lineCount, line))
        
        wordNum = random.randint(0, lineCount+1)
        randomWord = fileLines[wordNum].strip()
        print("DEBUG: num: %d, word: %s" % (wordNum, randomWord))
        return randomWord
    
    pass

def queryUser():
    prompt = "I expect you know the rules of the game.\nI will give you %d chances in total" % chances
    print(prompt)
    ask([], 0)
    pass

def ask(knowledge, strikes):
    if(strikes >= chances):
        print("Sorry human. It seems you have run out of chances to guess my word.\nBetter luck next time.")
        return
    print("You have %d chances left." % (chances-strikes))
    progress_so_far = currentKnowledge(knowledge)
    print(progress_so_far)
    if not(unknown in progress_so_far) :
        print("Congratulations. You've pieced together that the word is %s" % targetWord)
        return
    currentGuess = input("Make your guess: ")
    if(currentGuess == targetWord):
        print("That was correct! the answer is %s" % currentGuess)
        return
    if currentGuess in targetWord:
        print("the word does contain [%s]" % currentGuess)
        knowledge.extend(currentGuess)
        pass
    else:
        print("the word does not have [%s] in it" % currentGuess)
        strikes += 1
        pass
    ask(knowledge, strikes)
    
def currentKnowledge(knowledge):
    output = ""
    for a in targetWord:
        if (a in knowledge):
           output += a
           output += " "
        else:
           output += unknown
           output += " "
    return output.strip()
    pass

def endGame():
    prompt = "Thank you for playing hangman with me.\nI look forward to our next encouter."
    print(prompt)
    pass

# code execution
    
main()<file_sep>import random
import sys
import time

# Author: <NAME>
# <EMAIL>
# Last Modified: 12/11/1998

print("Welcome, human. Shall we play some rock, paper, scissors?")
want_to_play = input("y/n ?")

if want_to_play == "y":
    # continue
    pass
else:
    print("Okay. Until next time, perhaps")
    sys.exit(0)

print("Great. You know the rules.")
time.sleep(1)
print("rock...")
time.sleep(0.5)
print("paper...")
time.sleep(0.5)
print("scissors!")
time.sleep(0.5)

npc_move = random.randint(1,3+1)
# 1 --> rock, 2 --> paper, 3 --> scissors

player_move = "na"

def query():
    global player_move
    player_move = input("What do you play? r/p/s ?")
    if(player_move == "r"):
        # rock
        print("you\'ve chosen rock!")
    elif(player_move == "p"):
        # paper
        print("you\'ve chosen paper!")
    elif(player_move == "s"):
        # scissors
        print("you\'ve chosen scissors")
    else:
        print("not a valid response")
        query()

def tie():
    # a tie has occured
    print("A tie! It seems we are evenly matched.")

def win():
    # player has won
    print("Congratulations, human. You have bested me.")

def loss():
    # computer has won
    print("You have lost. I don\'t laugh. But if I could, I would be doing it now.")


query()
npc_play = ""
if npc_move == 1:
    npc_play = "rock"
elif npc_move == 2:
    npc_play = "paper"
elif npc_move == 3:
    npc_play = "scissors"
else:
    print("Error: unexpected npc_move")
    print("Terminating")
    sys.exit(0)

print("computer has played %s" % npc_play)

if(player_move == "r"):
    if(npc_move == 1):
        tie()
    if(npc_move == 2):
        loss()
    if(npc_move == 3):
        win()
elif(player_move == "p"):
    if(npc_move == 1):
        win()
    if(npc_move == 2):
        tie()
    if(npc_move == 3):
        loss()
elif(player_move == "s"):
    if(npc_move == 1):
        loss()
    if(npc_move == 2):
        win()
    if(npc_move == 3):
        tie()
else:
    print("Error: unexpected input")
    print("Terminating program")
    sys.exit(0)

time.sleep(1)
print("Thank you for entertaining me, human. I am looking forward to our next encounter.")
print("--->.<---")
sys.exit(0)
<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Dec 12 22:03:05 2019

Based on tutorial@
https://likegeeks.com/python-gui-examples-tkinter-tutorial/#Add-a-combobox-widget

@author: <NAME>
@contact: <EMAIL>
"""

import tkinter as tk
import tkinter.ttk as ttk
from tkinter import messagebox
from tkinter import Menu
from tkinter.ttk import Progressbar

window = tk.Tk()
# window setup
window.title("App")
window.geometry("700x400")
# label
l = tk.Label(window, text="Hello", font=("Arial Bold", 30))
l.grid(column=1, row=0)

def clicked():
    l.configure(text="You typed %s" % txtbox.get())
# button
btn = tk.Button(window, text="click!", command=clicked)
btn.configure(bg="sky blue", fg="azure")
btn.grid(column=0, row=0)
#text box
txtbox = tk.Entry(window, width=15)
txtbox.grid(column=0, row=1)
txtbox.focus()
#combo box
combo = ttk.Combobox(window)
combo["values"] = (1, 2, 3, "Text")
combo.current(0)
combo.grid(column=1, row=1)
# combo.get(), similar to txtbox.get()

# check button
checkbutton = tk.Checkbutton(window, text="check bos", var=True)
checkbutton.grid(column=2, row=0)
# radio button
selectedRadio = tk.IntVar()
radioBt1 = tk.Radiobutton(window, text="option", value=1, variable=selectedRadio)
radioBt2 = tk.Radiobutton(window, text="something else", value=2, variable=selectedRadio)
radioBt1.grid(column=2, row=1)
radioBt2.grid(column=3, row=1)
# button for radio button
def radioCheck():
    l.configure(text=selectedRadio.get())
    
btn_radio = tk.Button(window, text="get radio value", comman=radioCheck)
btn_radio.grid(column=4, row=1)
# scrolled text
"""is an option, I just didn't bother with it"""
#message box
def popup():
    messagebox.showinfo("Message", combo.get())
messageBt = tk.Button(window, text="message", command=popup)
messageBt.grid(column=2, row=2)
#spin box
spinvar = tk.IntVar()
spinvar.set(10)
spin = tk.Spinbox(window, from_=0, to=100, width=5, textvariable=spinvar)
spin.grid(column=3, row=2)
# progress bar
"""using ttk.style to customize the progress bar"""
barstyle = ttk.Style()
barstyle.theme_use("default")
barstyle.configure("black.Horizontal.TProgressvar", background="black")
bar = Progressbar(window, length=100, style="black.Horizontal.TProgressbar")
bar["value"] = 60
bar.grid(column=0, row=2)
# Menu
def menu_error():
    messagebox.showerror("Error from menu", "You clicked the Error tab from menu")
menu = Menu(window)
menuSub = Menu(menu, tearoff=0)
menuSub.add_command(label="Open")
menuSub.add_separator()
menuSub.add_command(label="New")
menuSub.add_command(label="Create")
menuSub.add_command(label="Error", command=menu_error)
menu.add_cascade(label="File", menu=menuSub)
menu.add_command(label="Exit")
window.config(menu=menu)
# tabs
"""
Example
perhaps? TODO
"""

"""
window = Tk()
 
window.title("Welcome to LikeGeeks app")
 
tab_control = ttk.Notebook(window)
 
tab1 = ttk.Frame(tab_control)
 
tab2 = ttk.Frame(tab_control)
 
tab_control.add(tab1, text='First')
 
tab_control.add(tab2, text='Second')
 
lbl1 = Label(tab1, text= 'label1', padx=5, pady=5)
 
lbl1.grid(column=0, row=0)
 
lbl2 = Label(tab2, text= 'label2')
 
lbl2.grid(column=0, row=0)
 
tab_control.pack(expand=1, fill='both')
 
window.mainloop()
"""


window.mainloop()
