Example #1
0
def play_bot_bot(value1, value2):
    if value1 == 1 or value2 == 1:
        chooseDif()
    drawBoard()
    drawCheckers()
    while Board.hasWon(Board.board) == 0:
        print("_______________NEW CYCLE_______________")
        print("Total Moves",
              globalVariables.counter1 + globalVariables.counter2)
        print("Total Attacks", globalVariables.attacks)
        print("Moves without attack:", globalVariables.moves_without_attack)
        print("No. of black checkers:", globalVariables.blacks)
        print("No. of white checkers:", globalVariables.whites)
        sleep(0.01)
        Board.King(Board.board)
        if value1 == 1:
            runMinmax(False)
        elif value1 == 2:
            runRandom(False)
        globalVariables.moves_without_attack += 1
        Board.King(Board.board)
        redraw()
        win.update()
        if Board.hasWon(Board.board) != 0:
            break
        if value2 == 1:
            runMinmax(True)
        elif value2 == 2:
            runRandom(True)
        globalVariables.moves_without_attack += 1
    winWindow = graphics.GraphWin("Game over")
    if Board.hasWon(Board.board) == 1:
        text = graphics.Text(Point(winWindow.width / 2, winWindow.height / 2),
                             "White Won! ")
        text.draw(winWindow)
        print("Total Number of Black Moves in Game:", globalVariables.counter1)
        print("Average Time to Make Each Black Move:",
              globalVariables.timesum1 / globalVariables.counter1)
        print("Total Number of White Moves in Game:", globalVariables.counter2)
        print("Average Time to Make Each White Move:",
              globalVariables.timesum2 / globalVariables.counter2)
        sleep(3)
    elif Board.hasWon(Board.board) == -1:
        text = graphics.Text(Point(winWindow.width / 2, winWindow.height / 2),
                             "Black Won! ")
        text.draw(winWindow)
        print("Total Number of Black Moves in Game:", globalVariables.counter1)
        print("Average Time to Make Each Black Move:",
              globalVariables.timesum1 / globalVariables.counter1)
        print("Total Number of White Moves in Game:", globalVariables.counter2)
        print("Average Time to Make Each White Move:",
              globalVariables.timesum2 / globalVariables.counter2)
        sleep(3)
    elif Board.hasWon(Board.board) == 2:
        text = graphics.Text(Point(winWindow.width / 2, winWindow.height / 2),
                             "Its a draw")
        text.draw(winWindow)
        print("Total Number of Black Moves in Game:", globalVariables.counter1)
        print("Average Time to Make Each Black Move:",
              globalVariables.timesum1 / globalVariables.counter1)
        sleep(3)
    message = graphics.Text(
        Point(winWindow.getWidth() / 2,
              winWindow.getHeight() / 2 + 20),
        'Click anywhere within the window to quit.')
    message.setTextColor('red')
    message.setStyle('italic')
    message.setSize(8)
    message.draw(winWindow)

    winWindow.getMouse()
    winWindow.close()
    return
Example #2
0
def rectangle(tx: float, ty: float, bx: float, by: float) -> Rectangle:
    return Rectangle(Point(tx, ty), Point(bx, by))
Example #3
0
def draw_sun(win: GraphWin) -> Circle:
    sun = Circle(Point(-40, 40), 30)
    fill_outline(sun, color(233, 189, 21))
    sun.draw(win)
    return sun
            if t2 > r:
                t2 = r
        print(t1, t2, r)
    print(t1, t2)
    if t1 < t2:
        x11 = x1 + t1 * p[1]
        x22 = x1 + t2 * p[1]
        y11 = y1 + t1 * p[3]
        y22 = y1 + t2 * p[3]
        print("(x1: %d , y1 : %d),(x2: %d , y2 : %d)" % (x11, y11, x22, y22))
        clip_line = Line(Point(int(x11), int(y11)), Point(int(x22), int(y22)))
        clip_line.draw(win)


if __name__ == "__main__":
    window = Rectangle(Point(x_min, y_min), Point(x_max, y_max))
    window.draw(win)
    line1 = Line(Point(50, 375), Point(700, 600))
    line1.draw(win)
    line2 = Line(Point(150, 200), Point(300, 500))
    line2.draw(win)
    line3 = Line(Point(425, 425), Point(550, 500))
    line3.draw(win)
    win.getMouse()
    win.delete("all")
    window = Rectangle(Point(x_min, y_min), Point(x_max, y_max))
    window.draw(win)
    liang_barsky_clip(50, 375, 700, 600)
    liang_barsky_clip(150, 200, 300, 500)
    liang_barsky_clip(425, 425, 550, 500)
Example #5
0
 def __init__(self, color, lower_x, lower_y, size):
     Character.__init__(self)
     self.rect = Rectangle(Point(lower_x, lower_y),
                           Point(lower_x + size, lower_y + size))
Example #6
0
def graphics():
    dict = {
        'jsmith': '1994',
        'rstein': '2010',
        'rong': '1945',
        'annah': '2020'
    }
    holder = {
        'jsmith': 'John Smith',
        'rstein': 'Rebecca Stein',
        'rong': 'Ronald Gray',
        'annah': 'Anna Heller'
    }
    from graphics import GraphWin, Rectangle, Entry, Text, Point, Circle

    win = GraphWin('Automated Transaction Machine', 500, 500)
    win.setCoords(0, 0, 40, 40)

    Welcome_message = Text(Point(20, 35),
                           'Welcome to the Automated Transaction Machine')

    Rect = Rectangle(Point(2, 2), Point(37, 37))
    Rect.draw(win)
    Welcome_message.draw(win)
    Pin_value = Text(Point(10, 32),
                     '\tPlease input your 1.UserID and 2. PIN below')
    Pin_value.setSize(10)
    Pin_value.draw(win)
    userID = Entry(Point(8, 30), 8)
    userID.draw(win)
    pin = Entry(Point(8, 26), 8)
    pin.draw(win)
    win.getMouse()
    x = pin.getText()
    y = userID.getText()
    Pin_value.undraw()
    userID.undraw()
    pin.undraw()

    while True:
        try:
            holder = CheckingAccount(y, x)
            break
        except ValueError:
            Incorrect_value = Text(Point(10, 32),
                                   '\tYour PIN is incorrect. Try Again')
            Incorrect_value.draw(win)
            pin = Entry(Point(8, 26), 8)
            pin.draw(win)
            win.getMouse()
            x = pin.getText()
            Incorrect_value.undraw()
            pin.undraw()
        except NameError:
            Incorrect_value = Text(Point(10, 32),
                                   '\tYour UserID is incorrect. Try Again')
            Incorrect_value.draw(win)
            userID = Entry(Point(8, 30), 8)
            userID.draw(win)
            win.getMouse()
            y = userID.getText()
            Incorrect_value.undraw()
            userID.undraw()

    userID.undraw()
    pin.undraw()
    Welcome = Text(
        Point(20, 25),
        "Welcome " + str(holder) + "! It is a pleasure serving you today!")
    Welcome.draw(win)
    win.getMouse()
    Welcome.undraw()
    Option = Text(Point(20, 25), 'Would you like to withdraw or deposit')
    Option.draw(win)
    win.getMouse()
Example #7
0
 def get_scaled_centre(self):
     return Point(scale_coordinate(self.c.x), scale_coordinate(self.c.y))
 def __init__(self, graphWin, p1=Point(100, 280), p2=Point(120, 300)):
     Rectangle.__init__(self, p1, p2)
     if graphWin.render:
         self.setFill(color_rgb(255, 0, 0))
         self.draw(graphWin)
 def drawHud(self):
     self.scoreText = Text(Point(730, 20), 'Score: 0')
     self.scoreText.setTextColor(color_rgb(255, 255, 255))
     self.scoreText.draw(self)
Example #10
0
#-*- coding:utf-8-*-
from graphics import Point, GraphWin
p = Point(50, 60)
p.getX()
p.getY()
win = GraphWin()
p.draw(win)
p2 = Point(140, 160)
p2.draw(win)
__author__ = 'ipetrash'


# SOURCE: https://habrahabr.ru/post/346146/


# pip install pyautogui
import pyautogui
from graphics import GraphWin, Circle, Point, Entry, color_rgb
import time

win = GraphWin("pipetka", 200, 200, autoflush=True)  # создаем графическую форму размером 200х200 и элементы на ней
x, y = pyautogui.position()  # получаем в x, y координаты мыши
r, g, b = pyautogui.pixel(x, y)  # получаем в r, g, b цвет

ColorDot = Circle(Point(100, 100), 25)  # создаем точку, отображающую цвет
ColorDot.setFill(color_rgb(r, g, b))  # устанавливает ей заливку из ранее полученных цветов
ColorDot.draw(win)  # рисуем на форме win

RGBtext = Entry(Point(win.getWidth() / 2, 25), 10)  # создаем RGB вывод
RGBtext.draw(win)  # рисуем на форме win

RGBstring = Entry(Point(win.getWidth() / 2, 45), 10)  # создаем вывод цвета в web стиле
RGBstring.draw(win)  # рисуем на форме win

Coordstring = Entry(Point(win.getWidth() / 2, 185), 10)  # создаем отображение координат
Coordstring.draw(win)  # рисуем на форме win

while True:  # цикл перереисовки формы
    time.sleep(0.1)  # задержка в 0.1 с, чтобы питон не сходил с ума
Example #12
0
def dialogue(line, choices = [], color=["white"], return_arg=False, right=False, speed=.02, type_length=0):

	# Initialize variables that will be used later.
	start = 500 if right else 0
	selection = 0
	prior = len(gw.items)
	if type(color) == str: color=[color]

	# Create the dialogue box
	dialogue_box = Rectangle(Point(start + 11, 403), Point(start + 489, 488))
	dialogue_box.setFill(color_rgb(50, 50, 50))
	dialogue_box.setWidth(3)
	dialogue_box.draw(gw)

	# Create the Text objects that will display dialogue.
	texts = []
	for i in color:
		text = Text(Point(start + 25, 418), "") 
		text.setTextColor(i)
		text.setSize(20)
		text.setAnchor("nw")
		text.draw(gw)
		texts.append(text)

	line = line.split()
	
	text_num = 0
	num_texts = len(texts)
	line_length = 0
	overflow = 0
	skip = False
	for word in line:

		word_length = len(word)
		if line_length + word_length + 1 > 29:
			word = '\n' + word
			line_length = 0
			overflow += 1
		line_length += word_length + 1
		
		if overflow > 1:
			for j in texts: j.setText(j.getText()[j.getText().index("\n") + 1:])
			overflow = 1

		for j in word + ' ':
			if j == '`':
				text_num += 1

			else:				
				for k in range(num_texts):

					key = gw.checkKey().lower()
					if key in ["return", "space", "escape"]:
						skip = True

					if k == text_num:
						texts[k].setText(texts[k].getText() + j)
					elif j == '\n':
						texts[k].setText(texts[k].getText() + '\n')
					else:
						texts[k].setText(texts[k].getText() + ' ')

			if not skip: sleep(speed)

	
	# If type_length is 0 and the array of choices that is passed in isn't empty, the player is supposed
	# 	to make a selection from a list of choices.	
	length_choices = len(choices)
	if type_length == 0:
		center = 374 - (30 * (length_choices - 1))
		selector = Polygon(Point(start + 478, center - 6), Point(start + 478, center + 6), Point(start + 461, center))
		selector.setFill("red")

		if length_choices > 0:
			answer = ""
			longest_answer = 0
			for i in choices:
				answer += f"{i}\n"
				longest_answer = max(longest_answer, len(i))
			answer = answer[:-1]

			choice_box = Rectangle(Point(start + 473 - (16 * (longest_answer + 2)), 382 - (30 * length_choices)), Point(start + 489, 395))
			choice_box.setFill(color_rgb(50, 50, 50))
			choice_box.setWidth(3)
			choice_box.draw(gw)


			choice_text = Text(Point(start + 453, 390), "")
			choice_text.setAnchor("se")
			choice_text.setJustification("right")
			choice_text.setSize(20)
			choice_text.draw(gw)

			

			choice_text.setText(answer)
			selector.draw(gw)

			
		while True:
			key = gw.checkKey().lower()

			if key != "":
				if key in ["space", "return"]:
					break

				elif key in ["escape"]:
					while selection < length_choices - 1:
						selector.move(0, 30)
						selection += 1

				elif key in ["m", "shift_l"]:
					pause_menu(not right)


				elif length_choices > 0:
					if key in ["up", "w", "left", "a"]:
						selection = (selection - 1) % length_choices
						if selection != length_choices - 1:
							selector.move(0, -30)
						else:
							selector.move(0, 30 * (length_choices - 1))


					elif key in ["down", "s", "right", "d"]:
						selection = (selection + 1) % length_choices
						if selection != 0:
							selector.move(0, 30)
						else:
							selector.move(0, -30 * (length_choices - 1))


	# Else, the player is typing in some response.
	# This is only used a couple times in play_game.py		
	elif type_length > 0:

		selection = ""

		shown_name = Text(Point(250 - (16 * type_length) // 2, 467))
		shown_name.setText("")
		shown_name.draw(gw)

		text_underline = shown_name.clone()
		text_underline.setText("-" * type_length)
		text_underline.move(0, 13)
		text_underline.draw(gw)

		bar = shown_name.clone()
		bar.move(-7, 0)
		bar.setText('|')
		bar.draw(gw)
		bar_flash = 0
		bar_shown = True

		while True:
			key = gw.checkKey()			

			if key:

				if len(selection) < type_length and key in alphabet + punctuation:
					if key == 'space': selection += ' '
					else: selection += key

					bar.move(16, 0)

				elif len(selection) > 0 and key == 'BackSpace':
					selection = selection[:-1]
					bar.move(-16, 0)

				elif key == 'Return':
					break
				
				bar_flash = 0
				if not bar_shown:
					bar_shown = True
					bar.draw(gw)
				shown_name.setText(selection)

			else:
				bar_flash += 1

				if bar_flash == 40000:
					bar_flash = 0
					if bar_shown:
						bar_shown = False
						bar.undraw()
					else:
						bar_shown = True
						bar.draw(gw)



	gw.clear(prior)

	if length_choices == 0 and type_length == 0: return -1
	elif return_arg: return choices[selection].split(":")[0]
	else: return selection
Example #13
0
def pause_menu(right):

	start = 500 if right else 0
	prior = len(gw.items)

	pause_overlay = Image(Point(500, 250), MAP / "pause_overlay.png")
	pause_overlay.draw(gw)


	# Everything for the Character Information
	info_box = Rectangle(Point(551 - start, 100), Point(959 - start, 400))
	info_box.setFill(color_rgb(50, 50, 50))
	info_box.setWidth(3)
	info_box.draw(gw)

	# The Character Icon
	info_icon = Image(Point(613 - start, 163), MAPS / "characters" / f"{player.character_class}_portrait.png")
	info_icon.draw(gw)

	# Shows the Header that includes the player's name and level.
	info_header = Text(Point(572 - start, 179))
	info_header.setAnchor("w")
	info_header.setSize(22)
	info_header.setText(f"      {player.name + f'LV: {player.lvl}'.rjust(16)[len(player.name):]}\n      HP:\n      EXP:\nItems:")
	info_header.draw(gw)

	# Draw the HP bar.
	hp_bar = Bar(player.current_HP, player.base_HP, "red", Point(750 - start, 149), Point(948 - start, 173))
	hp_bar.show()


	# Draws the EXP bar
	exp_bar = Bar(player.current_EXP, player.next_EXP, "green", Point(750 - start, 179), Point(948 - start, 203))
	exp_bar.show()

	# Lists off the player's current inventory.
	info_header_underline = Line(Point(573 - start, 240), Point(937 - start, 240))
	info_header_underline.setWidth(1)
	info_header_underline.setOutline("white")
	info_header_underline.draw(gw)
	info_footer = Text(Point(573 - start, 246))
	info_footer.setAnchor("nw")
	info_footer.setSize(14)
	info_footer.setText(inventory())
	info_footer.draw(gw)

	
	# Lists off the pause menu options.
	choice_box = Rectangle(Point(start + 125, 165), Point(start + 370, 335))
	choice_box.setFill(color_rgb(50, 50, 50))
	choice_box.setWidth(3)
	choice_box.draw(gw)

	choice_text = Text(Point(start + 260, 250))
	choice_text.setAnchor("c")
	choice_text.setSize(20)
	choice_text.setText("Resume\nDrink Potion\nEat Apple\nSave Game\nQuit Game")
	choice_text.draw(gw)
	

	selector = Polygon(Point(start + 137, 183), Point(start + 137, 195), Point(start + 154, 189))
	selector.setFill("red")
	selector.draw(gw)

	selection = 0
	saved = False

	while True:
		
		while True:
			key = gw.checkKey().lower()

			if key != "":
				if key in ["space", "return"]:
					break

				elif key in ["escape"]:
					while selection > 0:
						selector.move(0, -30)
						selection -= 1


				if key in ["up", "w", "left", "a"]:
					selection = (selection - 1) % 5
					if selection != 4:
						selector.move(0, -30)
					else:
						selector.move(0, 120)


				elif key in ["down", "s", "right", "d"]:
					selection = (selection + 1) % 5
					if selection != 0:
						selector.move(0, 30)
					else:
						selector.move(0, -120)

		# Resume Game
		if selection == 0:
			for i in gw.items[prior:]: i.undraw()
			return

		# Drink Potion
		if selection == 1:
			if player.items["Potions"] == 0:
				dialogue("You have no more potions to drink.", right=right)
			elif player.current_HP == player.base_HP:
				dialogue("You are already at max HP", right=right)
			else:
				player.items["Potions"] -= 1
				player.current_HP += round(randint(4, 10) * 4.2)
				if player.current_HP > player.base_HP:
					player.current_HP = player.base_HP
				hp_bar.update(player.current_HP, player.base_HP)

		# Eat Apple
		if selection == 2:
			if player.items["Apples"] == 0:
				dialogue("You have no more apples to eat.", right=right)
			elif player.current_HP == player.base_HP:
				dialogue("You are already at max HP", right=right)
			else:
				player.items["Apples"] -= 1
				player.current_HP += randint(1, 4)
				if player.current_HP > player.base_HP:
					player.current_HP = player.base_HP
				hp_bar.update(player.current_HP, player.base_HP)

		# Save Game
		if selection == 3:
			saved = True
			save_state = open("save_state.txt", "w")  
			
			stats_to_save = [player.character_class, player.name, player.lvl, player.attack, player.defense, 
				player.current_HP, player.base_HP, player.current_SP, player.base_SP, player.current_EXP, player.next_EXP,
				player.gold, player.items, game_stats
			]

			line_to_save = ''
			for i in stats_to_save:
				line_to_save = line_to_save + str(i) + "\n"

			save_state.write(b64encode(line_to_save.encode("UTF-8")).decode("UTF-8"))
			save_state.close()

			dialogue("Game saved.", right=right)

		# Quit Game
		if selection == 4:

			if not saved:
				dialogue(f"You have not saved recently.")

			if dialogue("Are you sure you want to quit?", ["Yes", "No"], right=right) == 0:
				raise GameOver('Town Quit')

		info_footer.setText(inventory())
Example #14
0
	'inn_stays': -1,
	"librarian": 0,
	"level_tutorial": True,
	'reginald': -1,
	'rat_name': 'Fief',
	"floor_key": [False, False, False, False, False, False, False, False, 
				  False, False, False, False, False, False, False, False],
	"portals": [],
	'orc_dead': False
	}

found_items = {
	"Potions": 0, "Apples": 0, "Herbs": 0, "magic_item": 0, 
	"Fire Scroll": 0, "Thunder Scroll": 0, "Ice Scroll": 0}

load_overlay = Image(Point(500, 250), MAP / "load_overlay.png")
map_background = Image(Point(750, 250), MAP / "map_background.png")
# load_overlay = Image(Point(500, 250), MAP / "null_icon.png")

not_walkable = ['T', 'W', 'R', 'x']

teleport_chars = ["`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "=", "+"]

alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", 'J', 'K', 'L', 'M', 
			'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
			'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
			'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

punctuation = ['space', '.', ',', "'", '"', '!', '?']

gw = GraphWin("Console Quest.py", 1000, 500)
Example #15
0
        colors = None
        for i, game in enumerate(hist):
            score = [0, 0]
            images = []
            names = game['players']
            size = int(game['size'])

            dim = 600
            left_marg = 50
            top_marg = 200
            win = GraphWin(game, dim + 2 * left_marg, dim + top_marg + 50)
            win.setBackground(color_rgb(255, 255, 255))

            if not colors:
                colors = {names[0]: 'blue', names[1]: 'red'}
                p1 = Text(Point(left_marg + dim // 2, 30), names[0])
                p1.setFill(colors[names[0]])
                p1.setSize(20)
                score1 = Text(Point(left_marg + dim // 6, 70), '0:0')
                score1.setFill(colors[names[0]])
                score1.setSize(30)

                vs = Text(Point(left_marg + dim // 2, 70), 'vs')
                vs.setFill('black')
                vs.setSize(20)

                p2 = Text(Point(left_marg + dim // 2, 110), names[1])
                p2.setFill(colors[names[1]])
                p2.setSize(20)
                score2 = Text(Point(left_marg + 5 * dim // 6, 70), '0:0')
                score2.setFill(colors[names[1]])
Example #16
0
 def draw(self) -> None:
     top_left = Point(self.x - self.__width / 2, self.y - self.__height / 2)
     bottom_right = Point(self.x + self.__width / 2, self.y + self.__height / 2)
     graphics.draw_rect(top_left, bottom_right, self.color)
Example #17
0
def main(
    title='Tiles',
    padding=10,
    density=0.5,
    size=5,
    most=10,
    dimensions={
        'x': 120,  # Pixels left to grid
        'y': 10,  # Pixels down to grid
        'width': 45,  # Width of tile
        'height': 45,  # Height of tile
    }):

    # These are used to construct the board
    x = dimensions['x']
    y = dimensions['y']

    #
    width = padding + x + most * dimensions['width']
    height = padding + y + most * dimensions['height']

    # The window is made just big enough to fit all components at max size
    win = GraphWin(title, width, height)

    # The squares for the game
    grid = Grid(dimensions, size).fill(density)

    # Labels which show the score and state of the game
    labels = {
        'score': Text(Point(x / 2, 140), '0'),
        'state': Text(Point(x / 2, 160), 'Hey There')
    }

    inputs = {
        'density': Input('Density', 0.5, Point(0.7 * x, 180), 4, 0, 1),

        # Minimum is 3, because less and the game is stupid
        'size': Input('Size', 5, Point(0.7 * x, 200), 4, 3, most)
    }

    # The best, reset and exit buttons
    buttons = [
        Button('Best', 'yellow', {
            'x': [padding, x - padding],
            'y': [10, 30]
        }, best(grid, labels)),
        Button('Reset', 'green', {
            'x': [padding, x - padding],
            'y': [40, 60]
        }, reset(win, grid, labels, inputs, dimensions)),
        Button('Exit', 'red', {
            'x': [padding, x - padding],
            'y': [70, 90]
        }, exit)
    ]

    # Bind mouse event handler to window
    win.bind("<Button-1>", click(win, grid, labels, buttons))

    # Bind keyboard press event handler to window
    # This is so the player can move using the directional keys
    win.bind("<Key>", key(move(grid, labels)))

    # Don't quit on me!
    draw(win, grid, labels, inputs, buttons).mainloop()
Example #18
0
                x = x_min

            if code_out == code1:
                x1 = x
                y1 = y
                code1 = computeCode(x1, y1)

            else:
                x2 = x
                y2 = y
                code2 = computeCode(x2, y2)
    if accept:
        LineDraw(x1, y1, x2, y2)
        print("(x1: %d , y1 : %d),(x2: %d , y2 : %d)" % (x1, y1, x2, y2))

    else:
        print("Line rejected")


if __name__ == "__main__":
    window = Rectangle(Point(x_max, y_max), Point(x_min, y_min))
    window.draw(win)
    LineDraw(50, 375, 700, 600)
    win.getMouse()
    win.delete("all")
    window = Rectangle(Point(x_max, y_max), Point(x_min, y_min))
    window.draw(win)
    cohenSutherlandClip(50, 375, 700, 600)
    win.getMouse()
    win.close()
Example #19
0
 def get_point(self):
     return Point(self.get_centre().x, self.get_centre().y)
Example #20
0
from graphics import Rectangle, Text, GraphWin, Point

win = GraphWin("Rectangle", 400, 400)

point_1 = win.getMouse()
point_2 = win.getMouse()

rect = Rectangle(point_1, point_2).draw(win)

x_len = abs(point_2.getX() - point_1.getX())
y_len = abs(point_2.getY() - point_1.getY())
Text(Point(150, 25), f"The area is {x_len*y_len}").draw(win)
Text(Point(150, 50), f"The perimeter is {2*(x_len+y_len)}").draw(win)
win.getMouse()
Example #21
0
 def buttonAdd(self, width, height, type=MenuButton.NONE, text="", c=color_rgb(105, 105, 105)):
     btnPos = Point(self.buttonPos.getX(), self.buttonPos.getY()+((height+self.buttonDis)*len(self.buttons)))
     self.buttons.append(Button(btnPos, width, height, type, c, text))
Example #22
0
def draw_classroom():
    win = GraphWin("Stick figure", 300, 200)

    head = Circle(Point(100, 60), 20)
    body = Line(Point(100, 80), Point(100, 120))
    arms = Line(Point(70, 90), Point(130, 90))
    leg_l = Line(Point(100, 120), Point(80, 170))
    leg_r = Line(Point(100, 120), Point(120, 170))

    for body_part in [head, body, arms, leg_l, leg_r]:
        body_part.draw(win)

    # Draw the Whiteboard
    whiteboard = Rectangle(Point(140, 50), Point(290, 150))
    whiteboard.setFill('white')
    whiteboard.draw(win)

    # Draw the blue marker pen base
    marker_pen = Rectangle(Point(120, 80), Point(128, 100))
    marker_pen.setFill('blue')
    marker_pen.draw(win)

    # Draw the blue marker pen tip
    marker_pen_tip = Rectangle(Point(122, 72), Point(126, 80))
    marker_pen_tip.setFill('blue')
    marker_pen_tip.draw(win)

    write_letters(win)
    marker_pen_tip.setFill('white')
Example #23
0
from graphics import calc_intersection_point_of_two_lines, Point

assert (Point(75, 75) == calc_intersection_point_of_two_lines(
    [Point(100, 100), Point(50, 50)],
    [Point(50, 100), Point(100, 50)]
)[0]), 'Incorrect intersection point'
Example #24
0
class SkewerUI(object):
    """
    Class: SkewerUI
    Description: A graphical display for the Skewer. It displays
        the items in on the skewer graphically, as they are added,
        removed and shifted around by the various commands.
    """

    __slots__ = (
        'win',  # the graphical window
        'items'  # the list of food items (strings) from top to bottom
    )

    def __init__(self, capacity):
        """
         Create the SkewerUI.
        :param capacity: the capacity of the skewer (for the window size)
        """
        # create the window
        self.create_window(capacity)  # (Sets value of win attribute.)
        self.items = []

    def close(self):
        """
        On destruction, close the graphical window.
        :param self: the SkewerUI being closed
        """

        self.win.close()

    def create_window(self, capacity):
        """
        Create the graphics window.
        :param capacity: the capacity of the skewer (for the window size)
        :return: None
        """

        self.win = GraphWin("Shish Kebab", 800, 200)
        self.win.setCoords(WIN_LOW_LEFT_X, WIN_LOW_LEFT_Y - 0.1,
                           WIN_LOW_LEFT_X + (capacity + 1) * FOOD_WIDTH,
                           WIN_UP_RIGHT_Y + 0.1)

        # draw skewer
        line = Line(Point(WIN_LOW_LEFT_X, WIN_LOW_LEFT_Y + WIN_HEIGHT / 2.0),
                    Point(capacity, WIN_LOW_LEFT_Y + WIN_HEIGHT / 2.0))
        line.setWidth(LINE_THICKNESS)
        line.draw(self.win)
        handle = Circle(
            Point(capacity - .1, WIN_LOW_LEFT_Y + WIN_HEIGHT / 2.0),
            SKEWER_HANDLE_RADIUS)
        handle.setFill(BKGD_COLOR)
        handle.setWidth(LINE_THICKNESS)
        handle.draw(self.win)
        self.items = []

    class _ShapeInfo():
        """
        Vegetables are circles and meats are rectangles.
        """

        __slots__ = 'shapeClass', 'ctorArgs'

        def __init__(self, shapeClass, ctorArgs):
            """
            Initialize the ShapeInfo.

            :param shapeClass: shape class
            :param ctorArgs: constructor arguments
            """
            self.shapeClass = shapeClass
            self.ctorArgs = ctorArgs

    Shapes = {
        True: _ShapeInfo(Circle, (Point(0, .5), .5)),
        False: _ShapeInfo(Rectangle, (Point(-.5, 0), Point(.5, 1)))
    }  # The bool is for vegetarian

    def add(self, food):
        """
        Called whenever an item is added to the Skewer, so the graphics
        can be updated.  It uses the KSpot class to get the food items
        and display them.
        :param food: the new food added to the skewer (KebabSpot)
        :return None
        """
        if food != None:
            shapeInfo = SkewerUI.Shapes[food.item.veggie]
            graphic = shapeInfo.shapeClass(*shapeInfo.ctorArgs)
            graphic.setFill(COLORS[food.item.name])
            graphic.draw(self.win)
            for prev in self.items:
                prev.move(1, 0)
            self.items.insert(0, graphic)

    def remove(self):
        """
        Called whenever an item is removed to the Skewer, so the graphics
        can be updated.  It uses the KSpot class to get the food items
        and display them.
        :param head: the head of the skewer (KSpot)
        :return None
        """
        if len(self.items) != 0:
            self.items[0].undraw()
            self.items.pop(0)
            for prev in self.items:
                prev.move(-1, 0)
Example #25
0
    def __init__(self, pair, live=False, numberOfCharts=1, strat=0, klineint=0, ss="", es="", graphics=True, ma5=True, handl=True):
        #sets kline interval to what the selected strat uses
        stratintervals = [Client.KLINE_INTERVAL_30MINUTE]
        if klineint == 0:
            klineint = stratintervals[strat]
            
            
        
        #graphs = [Client.KLINE_INTERVAL_30MINUTE, Client.KLINE_INTERVAL_5MINUTE]
        
        
        #Set startstamp to the highest kline interval chart and then pass it to the other charts
        #this starts the graphs at the same time, will makes things 999999999x easier
        if numberOfCharts != 1:
            self.chart3 = BotChart(pair,300,klineint, stringy=ss, endstring=es)
            startstamp = self.chart3.timestamps[0] // 1000
            self.chart2 = BotChart(pair,300,klineint, startstamp, stringy=ss, endstring=es)
        #startstamp = chart2.timestamps[0] // 1000
        #print(startstamp)
        
        #Changed chart to global var so I can access list values
        if numberOfCharts == 1:
            self.chart = BotChart(pair,300,klineint, stringy=ss, endstring=es)
        else:
            self.chart = BotChart(pair,300,klineint, startstamp, stringy=ss, endstring=es)
        chartmax = self.chart.getMax()
        chartmin = self.chart.getMin()
        
        #Get how many times one interval goes into another by minutes
        intervals = {"1":[6],"2":[2],"3":[2]}
        intervals = [6,2]
        
        
        chartlen = len(self.chart.data)
        if numberOfCharts != 1:
            chartlen2 = len(self.chart2.data)
            chartlen3 = len(self.chart3.data)
        
        #either multiply chartlen by a factor (6) and subtract chart2len
        #to get the extra at the end or find the closest 30 minute and 
        #see how many 5 minutes go into it from the current time
        #I'll start by doing the first
        interval = intervals[0]
        if numberOfCharts != 1:
            #need multiple extras
            extra1 = (len(self.chart.data) - 1) - (len(self.chart3.data) - 1) * 30
            extra2 = (len(self.chart2.data) - 1) - (len(self.chart3.data) - 1) * 6
            extra3 = 0
            extra = [extra1, extra2, extra3]
        
        
            #delete these from valuelist
            chartlengths = [chartlen,chartlen2,chartlen3]
            timestamps = [self.chart.timestamps,self.chart2.timestamps,self.chart3.timestamps]
            data = [self.chart.data,self.chart2.data,self.chart3.data]
            '''
            lmaxes = [chart.lmaxes,chart2.lmaxes,chart3.lmaxes]
            highs = [chart.highs,chart2.highs,chart3.highs]
            lows = [chart.lows,chart2.lows,chart3.lows]
            '''
        else:
            extra = [0]
            chartlengths = [chartlen]
            timestamps = [self.chart.timestamps]
        print("data chart length",len(self.chart.data))
        begin = time.time()
        #Might need some cleanup here
        
        #There's gotta be a better way
        #I think i should make prices be its own list like lmaxes and data etc - maybe do this with all the lists
        #there has to be multiple lists in valuelist because the lists become the same if they're not duplicated
        #valuelist = [[False,0,Point(0,0),0,[],0,"",[],[],[],0,0,0,False, False,[-1],0,0,[],1,0,[],False,False,True,0,[],[],True,[],0,0,[],[],[],[]],[False,0,Point(0,0),0,[],0,"",[],[],[],0,0,0,False, False,[-1],0,0,[],1,0,[],False,False,True,0,[],[],True,[],0,0,[],[],[],[]],[False,0,Point(0,0),0,[],0,"",[],[],[],0,0,0,False, False,[-1],0,0,[],1,0,[],False,False,True,0,[],[],True,[],0,0,[],[],[],[]]]
        valuelist = [False,0,Point(0,0),0,[],0,"",[],[],[],0,0,0,False, False,[-1],[-1],0,0,[],1,0,[],False,False,True,[],[],True,[],0,0,[],[],[],[],[]]

        print("chart.data:",self.chart.data)
        self.strategy = BotStrategy(strat, chartmax, chartmin, chartlengths, pair, numberOfCharts, self.chart.valuesAre, timestamps, extra, valuelist, intervals, int(self.chart.timestamps[0]), int(self.chart.timestamps[-1]), len(self.chart.timestamps),live,aggTrades=False,aggisNext=False, graphics=graphics, ma5on=ma5, handlon=handl)
        
        #Before doing this first migrate all data from graph to botstrategy
        #pass through all the different chart vars in strategy and scrap reinit
        #for candlestick in range(len(chart.data)):
        #    if (chart.timestamps[candlestick] == chart2.timestamps[candlestick]):
        #        strategy.tick(chart2.data[candlestick], 2)
        #    strategy.tick(chart.data[candlestick], 1)
        print("extra",extra)
        #I think chart is supposed to have the most klines
        for candlestick in range(len(self.chart.data)):
            print("\nTick number:",candlestick)
            #print(len(self.chart.data))
            #print(chart.timestamps[candlestick],chart2.timestamps[candlestick//5])
            #if (chart.timestamps[candlestick] == chart2.timestamps[candlestick//2] ):
                #if (chart2.timestamps[candlestick//5] == chart3.timestamps[candlestick//30]):
                #   strategy.tick(chart3.data[candlestick//30], "3")
                #strategy.tick(chart2.data[candlestick//2], "2", float(chart2.highs[candlestick//2]), float(chart2.lows[candlestick//2]), float(chart2.opens[candlestick//2]))
            if (candlestick == len(self.chart.data) - 1):
                #
                self.strategy.last = True
                #this is so dirty and I feel dirty for doing it
                #could mess up live run, move highs and lows to masterDick in botstrategy if so
                if graphics:
                    self.strategy.graph.addLists("1", self.chart.highs, self.chart.lows)
                end = time.time()
                print("time taken:",end - begin)
            print("Candestick Data:",self.chart.data[candlestick])
            self.strategy.tick(self.chart.data[candlestick], "1", float(self.chart.highs[candlestick]), float(self.chart.lows[candlestick]), float(self.chart.opens[candlestick]), float(self.chart.timestamps[candlestick]))
            #maybe run strategy.graph.listadd(params) every iteration-think of other strategies tho
        
        
        '''
        self.charts = True
        strategy.reinit(self.charts)
        for candlestick in chart2.data:
            strategy.tick(candlestick, "2")
        '''
        #this is the last chart
        '''
from graphics import Rectangle, Circle, GraphWin, Point
from math import floor
from random import randint

win = GraphWin("Connect4", 700, 700)
frame = Rectangle(Point(0, 0), Point(700, 700))
frame.setFill("blue")
frame.draw(win)

#Visual
board = [['-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-', '-', '-']]

def clearBoard():
    grid = []
    for i in range(7):
        grid.append([])
        for j in range(7):
            grid[i].append('-')
            board[i][j] = Circle(Point(i * 100 + 50, j * 100 + 50), 50)
            board[i][j].setFill("grey")
            board[i][j].draw(win)
    return grid

def drawBoard(grid):
    updateColours(grid)
    for i in range(len(board)):
        for j in range(len(board[i])):
            try:
                board[i][j].undraw()
            except:
                pass
Example #27
0
def polygon(*points: Tuple[float, float]) -> Polygon:
    return Polygon([Point(x, y) for x, y in points])
Example #28
0
def main():
    win = GraphWin("Face", 500, 500)
    Face(win, Point(50, 50), 30)
Example #29
0
def draw_fuzz(win: GraphWin, x: float, y: float, size: float, color: str):
    drop = Circle(Point(x, y), size)
    fill_outline(drop, color)
    drop.draw(win)
Example #30
0
def play_human_bot(value):
    if value == 1:
        chooseDif()
    drawBoard()
    drawCheckers()
    while Board.hasWon(Board.board) == 0:
        print("_______________NEW CYCLE_______________")
        print("Total Moves",
              globalVariables.counter1 + globalVariables.counter2)
        print("Total Attacks", globalVariables.attacks)
        print("Moves without attack:", globalVariables.moves_without_attack)
        print("No. of black checkers:", globalVariables.blacks)
        print("No. of white checkers:", globalVariables.whites)
        sleep(0.01)
        Board.King(Board.board)
        click1 = win.getMouse()
        checker = findsquare(click1)
        if checker is None or Board.board[
                int(checker[0]),
                int(checker[1])].checker is None or Board.board[
                    int(checker[0]), int(checker[1])].checker.black:
            continue
        click2 = win.getMouse()
        square = findsquare(click2)
        if square is None or (square[0] == checker[0]
                              and square[1] == checker[1]):
            continue
        partial_move = Minmax.Move(
            Board.board[int(checker[0]), int(checker[1])].checker,
            Board.board[int(square[0]), int(square[1])], "?")
        partial_move.checker.x = checker[0]
        partial_move.checker.y = checker[1]
        # TODO: Add move validation
        move = Board.getFullMove(partial_move)
        if move is None:
            continue
        else:
            move.apply(Board.board)
            globalVariables.counter2 += 1
            globalVariables.moves_without_attack += 1
        Board.King(Board.board)
        redraw()
        win.update()
        if Board.hasWon(Board.board) != 0:
            break
        if value == 1:
            runMinmax(True)
        elif value == 2:
            runRandom(True)
        globalVariables.moves_without_attack += 1
    winWindow = graphics.GraphWin("Game over")
    if Board.hasWon(Board.board) == 1:
        text = graphics.Text(Point(winWindow.width / 2, winWindow.height / 2),
                             "You Won! ")
        text.draw(winWindow)
        print("Total Number of Black Moves in Game:", globalVariables.counter1)
        print("Average Time to Make Each Black Move:",
              globalVariables.timesum1 / globalVariables.counter1)
        sleep(3)
    elif Board.hasWon(Board.board) == -1:
        text = graphics.Text(Point(winWindow.width / 2, winWindow.height / 2),
                             "You Lost :(")
        text.draw(winWindow)
        print("Total Number of Black Moves in Game:", globalVariables.counter1)
        print("Average Time to Make Each Black Move:",
              globalVariables.timesum1 / globalVariables.counter1)
        sleep(3)
    elif Board.hasWon(Board.board) == 2:
        text = graphics.Text(Point(winWindow.width / 2, winWindow.height / 2),
                             "Its a draw")
        text.draw(winWindow)
        print("Total Number of Black Moves in Game:", globalVariables.counter1)
        print("Average Time to Make Each Black Move:",
              globalVariables.timesum1 / globalVariables.counter1)
        sleep(3)
    message = graphics.Text(
        Point(winWindow.getWidth() / 2,
              winWindow.getHeight() / 2 + 20),
        'Click anywhere within the window to quit.')
    message.setTextColor('red')
    message.setStyle('italic')
    message.setSize(8)
    message.draw(winWindow)

    winWindow.getMouse()
    winWindow.close()

    return