def draw_grid(size): squares = size - 1 win = GraphWin("Graphical traced walk", 50 * size, 50 * size) win.setCoords(0, size, size, 0) border_rectangle = Rectangle(Point(0.5, 0.5), Point(size - 0.5, size - 0.5)).draw(win) border_rectangle.setFill("gray") border_rectangle.setWidth(2) centre_square = Rectangle( Point(size / 2 - 0.5, size / 2 - 0.5), Point(size / 2 + 0.5, size / 2 + 0.5), ).draw(win) centre_square.setFill("cyan") centre_square.setOutline("") person = Circle(Point(size / 2, size / 2), 0.25).draw(win) person.setFill("red") square_texts = [[""] * squares for _ in range(squares)] for i in range(squares): for j in range(squares): # grid lines Line(Point(1.5 + j, 0.5), Point(1.5 + j, size - 0.5)).draw(win) Line(Point(0.5, 1.5 + j), Point(size - 0.5, 1.5 + j)).draw(win) # text within each square square_text = Text(Point(1 + j, 1 + i), "").draw(win) square_texts[i][j] = square_text return win, person, square_texts
class Button: def __init__(self, win, center, width, height, label): w, h = width / 2.0, height / 2.0 x, y = center.getX(), center.getY() self.xmax, self.xmin = x + w, x - w self.ymax, self.ymin = y + h, y - h p1 = Point(self.xmin, self.ymin) p2 = Point(self.xmax, self.ymax) self.rect = Rectangle(p1, p2) self.rect.setFill("lightgray") self.rect.draw(win) self.label = Text(center, label) self.label.draw(win) self.deactivate() def clicked(self, p): return (self.active and self.xmin <= p.getX() <= self.xmax and self.ymin <= p.getY() <= self.ymax) def getLabel(self): return self.label.getText() def activate(self): self.label.setFill("black") self.rect.setWidth(2) self.active = True def deactivate(self): self.label.setFill("darkgray") self.rect.setWidth(1) self.active = False def undraw(self): self.rect.undraw() self.label.undraw()
def main(): print("This program plots the growth of a 10-year investment!") principal = eval(input("Enter the initial principal: ")) apr = eval(input("Enter the annualized interest rate: ")) win = GraphWin("Investment Growth Chart", 320, 240) win.setBackground("white") win.setCoords(-1.75, -200, 11.5, 10400) Text(Point(-1, 0), "0.0K").draw(win) Text(Point(-1, 2500), "2.5K").draw(win) Text(Point(-1, 5000), "5.0K").draw(win) Text(Point(-1, 7500), "7.5K").draw(win) Text(Point(-1, 10000), "10.0K").draw(win) bar = Rectangle(Point(0, 0), Point(1, principal)) bar.setFill("green") bar.setWidth(2) bar.draw(win) for year in range(1, 11): principal = principal * (1 + apr) bar = Rectangle(Point(year, 0), Point(year + 1, principal)) bar.setFill("green") bar.setWidth(2) bar.draw(win) input("Press <Enter> to quit.") win.close()
def main() : # Introduction print ( " This program plots the growth of a 10-year investment . " ) # Get principal and interest rate principal = float(input ("Enter the initial principal : ")) apr = float(input("Enter the annualized interest rate : ")) # Create a graphics window with labels on left edge win = GraphWin ("Investment Growth Chart ", 320 , 240) win.setBackground ("white") win.setCoords (-1.75, -200 , 11.5, 10400) Text(Point (- 1, 0) , ' 0.0K').draw (win) Text(Point (- 1, 2500) , '2.5K').draw (win) Text(Point (- 1, 5000) , ' 5.0K').draw (win) Text(Point (- 1, 7500) , ' 7.5k').draw (win) Text(Point (- 1, 10000) , '10.0K').draw (win) # Draw bar f or init ial princ ipal bar = Rectangle (Point (0, 0) , Point (1, principal)) bar.setFill ("green") bar.setWidth (2) bar.draw (win) # Draw a bar for each subsequent year for year in range (1, 11) : principal = principal * ( 1 + apr) bar = Rectangle (Point (year, 0), Point (year+ 1 , principal )) bar.setFill ("green") bar.setWidth (2) bar.draw(win) input(" Press <Enter> to quit.") win.close ()
def main(): # Introduction print("This program plots the growth of a 10-year investment.") # Get principal and interest rate principal = float(input(" Enter the initial principal: ")) apr = float(input(" Enter the annualized interest rate: ")) # Create a graphics window with labels on left edge win = GraphWin("Investment Growth Chart ", 320, 240) win.setBackground("white") Text(Point(20, 230), ' 0.0K').draw(win) Text(Point(20, 180), ' 2.5K').draw(win) Text(Point(20, 130), ' 5.0K').draw(win) Text(Point(20, 80), ' 7.5K').draw(win) Text(Point(20, 30), '10.0K').draw(win) # Draw bar for initial principal height = principal * 0.02 bar = Rectangle(Point(40, 230), Point(65, 230 - height)) bar.setFill("green") bar.setWidth(2) bar.draw(win) # Draw bars for successive years for year in range(1, 11): # calculate value for the next year principal = principal * (1 + apr) # draw bar for this value xll = year * 25 + 40 height = principal * 0.02 bar = Rectangle(Point(xll, 230), Point(xll + 25, 230 - height)) bar.setFill("green") bar.setWidth(2) bar.draw(win) input(" Press <Enter> to quit ") win.close()
def draw_hold_button(): # hold button points hold_a = Point(WIN.getWidth() * 2 / 11 - 100, WIN.getHeight() * 3 / 12) hold_b = Point(hold_a.getX() + 200, hold_a.getY() + 100) hold_button = Rectangle(hold_a, hold_b) hold_button.setFill("green") hold_button.setOutline("black") hold_button.setWidth(5) # Obtains the center point of the hold button center_hold_button = Point(0.5 * (hold_a.getX() + hold_b.getX()), 0.5 * (hold_a.getY() + hold_b.getY())) # Text class hold_text = Text(center_hold_button, "Hold") # Style the text hold_text.setFace("helvetica") hold_text.setSize(26) hold_text.setStyle("bold") hold_text.setTextColor("black") hold_button.draw(WIN) hold_text.draw(WIN) return hold_a, hold_b
class Button: def __init__(self, win, center, width, height, label='Button'): """ Creates a rectangular button. Example usage: ============== centerPoint = Point(x, y) button = Button(win, centerPoint, width, height, 'Click Me!') """ # Get most extreme vertices of button half_width = width / 2.0 half_height = height / 2.0 x, y = center.getX(), center.getY() self.x_min, self.y_min = x - half_width, y - half_height self.x_max, self.y_max = x + half_width, y + half_height # Create button outline point1 = Point(self.x_min, self.y_min) point2 = Point(self.x_max, self.y_max) self.rect = Rectangle(point1, point2) self.rect.setFill('lightgrey') self.rect.draw(win) # Create button text self.label = Text(center, label) self.label.draw(win) self.deactivate() def activate(self): """ Sets this button to "active". """ self.label.setFill('black') self.rect.setWidth(2) self.active = True def deactivate(self): """ Sets this button to "inactive". """ self.label.setFill('darkgrey') self.rect.setWidth(1) self.active = False def clicked(self, point): """ Tests to see if the point clicked resides within the button's rectangle, and if the button is active. """ if self.active: if (self.x_min <= point.getX() and self.y_min <= point.getY() and self.x_max >= point.getX() and self.y_max >= point.getY()): return True return False def getLabel(self): return self.label.getText()
class Button(object): def __init__(self, win, center, width, height, label): w, h = width/2, height/2 x, y = center.getX(), center.getY() self.xmax, self.xmin = x+w, x-w self.ymax, self.ymin = y+h, y-h p1 = Point(self.xmin, self.ymin) p2 = Point(self.xmax, self.ymax) self.rect = Rectangle(p1, p2) self.rect.setFill('lightgray') self.rect.draw(win) self.label = Text(center, label) self.label.draw(win) self.deactivate() def clicked(self, p): return self.active and self.xmin <= p.getX() and self.xmax >= p.getX() and self.ymin <= p.getY() and self.ymax >= p.getY() def getLabel(self): return self.label.getText() def activate(self): self.label.setFill('black') self.rect.setWidth(2) self.active = True def deactivate(self): self.label.setFill('darkgrey') self.rect.setWidth(1) self.active = False
def main(): win = graphics.GraphWin('Investment Grow Chart',320,240) win.setBackground('White') win.setCoords(-1.75,-9000,11.5,15400) Text(Point(4.87,13500),'Future Value Calculator').draw(win) Text(Point(4.5,-2000),'Input first principal:').draw(win) inputP = Entry(Point(9,-2000),6) inputP.setText('0') inputP.draw(win) Text(Point(3,-4000),' Input interest rate in decimal:').draw(win) inputR = Entry(Point(9,-4000),6) inputR.setText('0.0') inputR.draw(win) button = Rectangle(Point(2,-6000),Point(8,-8500)) button.setFill('Green') button.draw(win) buttontext = Text(Point(5,-7250),'Show Result!:') buttontext.draw(win) win.getMouse() p = eval(inputP.getText()) r = eval(inputR.getText()) Text(Point(-1,0),'0 K').draw(win) Text(Point(-1,2500),'2.5K').draw(win) Text(Point(-1,5000),'5 K').draw(win) Text(Point(-1,7500),'7.5K').draw(win) Text(Point(-1,10000),'10 K').draw(win) bar = Rectangle(Point(0,0),Point(1,p)) bar.setFill('green') bar.setWidth(2) bar.draw(win) for i in range(1,11): p = p*(1+r) bar= Rectangle(Point(i,0),Point(i+1,p)) bar.setFill('Green') bar.setWidth(2) bar.draw(win) buttontext.setText('Quit.') win.getMouse() win.close()
def main(): win = graphics.GraphWin('Investment Grow Chart', 320, 240) win.setBackground('White') win.setCoords(-1.75, -9000, 11.5, 15400) Text(Point(4.87, 13500), 'Future Value Calculator').draw(win) Text(Point(4.5, -2000), 'Input first principal:').draw(win) inputP = Entry(Point(9, -2000), 6) inputP.setText('0') inputP.draw(win) Text(Point(3, -4000), ' Input interest rate in decimal:').draw(win) inputR = Entry(Point(9, -4000), 6) inputR.setText('0.0') inputR.draw(win) button = Rectangle(Point(2, -6000), Point(8, -8500)) button.setFill('Green') button.draw(win) buttontext = Text(Point(5, -7250), 'Show Result!:') buttontext.draw(win) win.getMouse() p = eval(inputP.getText()) r = eval(inputR.getText()) Text(Point(-1, 0), '0 K').draw(win) Text(Point(-1, 2500), '2.5K').draw(win) Text(Point(-1, 5000), '5 K').draw(win) Text(Point(-1, 7500), '7.5K').draw(win) Text(Point(-1, 10000), '10 K').draw(win) bar = Rectangle(Point(0, 0), Point(1, p)) bar.setFill('green') bar.setWidth(2) bar.draw(win) for i in range(1, 11): p = p * (1 + r) bar = Rectangle(Point(i, 0), Point(i + 1, p)) bar.setFill('Green') bar.setWidth(2) bar.draw(win) buttontext.setText('Quit.') win.getMouse() win.close()
class Button(UIBase): def __init__( self, callback, canvas, center, width=100, height=100, label="Button", font_size=14 ): """Creates a button that fires a callback when clicked""" self.callback = callback self.canvas = canvas w, h = width/2.0, height/2.0 x, y = center.getX(), center.getY() self.xmax, self.xmin = x+w, x-w self.ymax, self.ymin = y+h, y-h p1 = Point(self.xmin, self.ymin) p2 = Point(self.xmax, self.ymax) self.rect = Rectangle(p1, p2) self.rect.setFill('lightgray') self.label = Text(center, label) self.label.setSize(font_size) self.draw() self.activate() def clicked(self, p): """Fires callback if active p is inside""" if (self.active and self.xmin <= p.getX() <= self.xmax and self.ymin <= p.getY() <= self.ymax): return self.callback() def get_label(self): return self.label.getText() def activate(self): self.label.setFill('black') self.rect.setWidth(2) self.active = 1 def deactivate(self): self.label.setFill('darkgrey') self.rect.setWidth(1) self.active = 0 def draw(self): self.rect.draw(self.canvas) self.label.draw(self.canvas) def undraw(self): self.rect.undraw() self.label.undraw()
def draw(self, color=None): if not INTERFACE: return square = self.getSquare() rectangleLength = 2 * self.board.squareSize + self.board.innerSize rectangleWidth = self.board.innerSize if (self.direction == Fence.DIRECTION.HORIZONTAL): rectangle = Rectangle( Point(square.left, square.top - rectangleWidth), Point(square.left + rectangleLength, square.top)) else: rectangle = Rectangle( Point(square.left - rectangleWidth, square.top), Point(square.left, square.top + rectangleLength)) rectangle.setFill(self.player.color.value if color is None else color) rectangle.setWidth(0) rectangle.draw(self.board.window)
def update_status_message(self, text): center_x = self.win.getWidth() / 2 center_y = 20 back_color = color_rgb(240, 240, 240) msg_width = 300 msg_height = 20 rect = Rectangle(Point(center_x - msg_width, center_y - msg_height), Point(center_x + msg_width, center_y + msg_height)) rect.setFill(back_color) rect.setOutline(back_color) rect.setWidth(1) # width of boundary line rect.draw(self.win) message = Text(Point(center_x, center_y), text) message.setTextColor('red') message.setStyle('bold') message.setSize(20) message.draw(self.win)
def displayState(state, playerNames, selectedSquare, currentMove=None, moveProgress=0): win.delete('all') textPos = [boardWidth * squareSize / 4, boardWidth * squareSize * 3 / 4] for p in range(2): if state.gameOver == False: if state.playerToMove == playerCode[p]: t = Text(Point(textPos[p], textHeight / 2), '<< ' + playerNames[p] + ' >>') else: t = Text(Point(textPos[p], textHeight / 2), playerNames[p]) else: if np.sign(state.points) == playerCode[p]: t = Text(Point(textPos[p], textHeight / 2), '!!! ' + playerNames[p] + ' !!!') t.setStyle("bold") else: t = Text(Point(textPos[p], textHeight / 2), playerNames[p]) t.setFace("arial") t.setSize(min([int(textHeight / 3), 36])) t.setTextColor(pieceColors[p]) t.draw(win) # Show squares and pieces for x in range(boardWidth): for y in range(boardHeight): r = Rectangle(Point(squareSize * x, textHeight + squareSize * y), Point(squareSize * (x + 1), textHeight + squareSize * (y + 1))) if selectedSquare == (x, y): r.setFill("white") else: r.setFill(squareColors[(x + y) % 2]) r.setWidth(0) r.draw(win) if state.board[x, y] != 0 and (currentMove == None or currentMove[:2] != (x, y)): drawPiece(state.board[x, y], squareSize * x, textHeight + squareSize * y) # Show moving piece somewhere between its start and end points (moveProgress between 0 and 1) if currentMove != None: x = moveProgress * (currentMove[2] - currentMove[0]) + currentMove[0] y = moveProgress * (currentMove[3] - currentMove[1]) + currentMove[1] drawPiece(state.playerToMove, squareSize * x, textHeight + squareSize * y) if currentMove == None: update() else: update(60)
class Button: def __init__(self, win, center, width, height, label='Button'): #Set extreme verticies half_width = width / 2.0 half_height = height / 2.0 x, y = center.getX(), center.getY() self.x_min, self.y_min = x - half_width, y - half_height self.x_max, self.y_max = x + half_width, y + half_height #Create button outline point1 = Point(self.x_min, self.y_min) point2 = Point(self.x_max, self.y_max) self.rect = Rectangle(point1, point2) self.rect.setFill('lightgrey') self.rect.draw(win) self.label = Text(center, label) self.label.draw(win) self.deactivate() #set button to active def activate(self): self.label.setFill('black') self.rect.setWidth(2) self.active = True #set button to inactive def deactivate(self): self.label.setFill('darkgrey') self.rect.setWidth(1) self.active = False def clicked(self): if self.active: if (self.x_min <= point.getX() and self.y_min <= point.getY() and self.x_max >=point.getX() and self.y_max >= point.getY()): return True return False def getLabel(self): return self.label.getText()
def rectangle(self, i, j): rect = Rectangle( Point(j * square_size, i * square_size), Point(j * square_size + square_size, i * square_size + square_size)) rect.setWidth(3) if self.type is grass_type: rect.setFill(color_rgb(25, 255, 102)) if self.type is forest_type: rect.setFill(color_rgb(0, 135, 45)) if self.type is water_type: rect.setFill(color_rgb(0, 81, 196)) if self.type is mountain_type: rect.setFill(color_rgb(109, 109, 109)) if self.type is road_type: rect.setFill(color_rgb(132, 104, 58)) if self.type is start_point: rect.setFill(color_rgb(18, 206, 53)) if self.type is goal_point: rect.setFill(color_rgb(206, 18, 34)) return rect
def draw_deck_border(deck): # Abritatry value to gives a nice spacing. deck_border = 10 deck_width = deck.getWidth() deck_height = deck.getHeight() # Goes to middle of screen and minus' deck width minus border border_top_left = Point( WIN.getWidth() / 2 - deck_width / 2 - deck_border, WIN.getHeight() * 5 / 19 - deck_height / 2 - deck_border) border_bottom_right = Point( WIN.getWidth() / 2 + deck_width / 2 + deck_border, WIN.getHeight() * 5 / 19 + deck_height / 2 + deck_border) # Draws and styles it! deck_border = Rectangle(border_top_left, border_bottom_right) deck_border.setOutline("black") deck_border.setWidth(5) deck_border.draw(WIN)
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())
def draw_patch_box(x, y): patch_box = Rectangle(Point(x, y), Point(x + 100, y + 100)) patch_box.setWidth(5) return patch_box
frown.draw(win) frown_cover = Circle(Point(299, 650), 260) frown_cover.setFill(color_rgb(90, 255, 84)) frown_cover.setWidth(0) frown_cover.draw(win) # Tongue - Circle & Polygon Combo with Black Vertical Line tongue_tip = Circle(Point(299, 405), 30) tongue_tip.setFill(color_rgb(90, 255, 84)) tongue_tip.setWidth(3) tongue_tip.draw(win) tongue = Rectangle(Point(269, 403), Point(329, 348)) tongue.setFill(color_rgb(90, 255, 84)) tongue.setWidth(0) tongue.draw(win) tongue_ctr = Line(Point(299, 348), Point(299, 385)) tongue_ctr.setWidth(4) tongue_ctr.draw(win) tongue_edge_L = Line(Point(269, 348), Point(269, 410)) tongue_edge_L.setFill('black') tongue_edge_L.setWidth(3) tongue_edge_L.draw(win) tongue_edge_R = tongue_edge_L.clone() tongue_edge_R.move(60, 0) tongue_edge_R.draw(win)
def draw_bar(window, year, height): bar = Rectangle(Point(year, 0), Point(year + 1, height)) bar.setFill("green") bar.setWidth(2) bar.draw(window)
pathLength_text = Text(Point(100, 455), "Path Length Score: ") pathLength_text.setTextColor(color="white") pathLength_text.setSize(10) pathLength_text.setStyle("bold") pathLength_text.draw(win) pathLength_text = Text(Point(175, 455), '') pathLength_text.setTextColor(color="white") pathLength_text.setSize(10) pathLength_text.setStyle("bold") pathLength_text.draw(win) a_rect = Rectangle(Point(900, 400), Point(950, 450)) a_rect.setOutline(color="white") a_rect.setWidth(3) a_rect.draw(win) Astar_text = Text(Point(925, 425), "A*") Astar_text.setSize(25) # Astar_text = Text(Point(925,425), "BFS") # Astar_text.setSize(15) # Astar_text = Text(Point(925,425), "DiJ") # Astar_text.setSize(15) Astar_text.setTextColor(color="white") # Astar_text.setTextColor(color_rgb(66, 134, 244)) Astar_text.setStyle("bold") Astar_text.draw(win) Description_text = Text( Point(500, 435), "* Click within the window to start search\n"
def battle(self, enemy): pygame.mixer.music.stop() # musicChoice = (randint(1,2) # if musicChoice == '1': # battle_music = pygame.mixer.music.load("Battle_Music.wav") # pygame.mixer.music.play(-1) # else: # battle_music2 = pygame.mixer.music.load("battle2.mp3") # pygame.mixer.music.play(-1) battle_music = pygame.mixer.music.load("Battle_Music.wav") pygame.mixer.music.play(-1) prior = len(glbl.gw.items) battle_background = Rectangle(Point(-2, -2), Point(1002, 502)) battle_background.setFill(color_rgb(150, 150, 150)) battle_background.draw(glbl.gw) e_name_box = Rectangle(Point(11, 11), Point(len(enemy.name) * 20 + 22, 50)) e_name_box.setFill(color_rgb(50, 50, 50)) e_name_box.setWidth(3) e_name_box.draw(glbl.gw) e_name = Text(Point(22, 16), enemy.name) e_name.setAnchor('nw') e_name.setStyle('bold') e_name.setSize(20) e_name.draw(glbl.gw) e_name.draw(glbl.gw) e_health = Bar(enemy.current_HP, enemy.base_HP, 'red', Point(11, 55), Point(331, 81)) e_health.show() p_name_box = Rectangle(Point(978 - (len(self.name) * 20), 11), Point(989, 50)) p_name_box.setFill(color_rgb(50, 50, 50)) p_name_box.setWidth(3) p_name_box.draw(glbl.gw) p_name = Text(Point(978, 16), self.name) p_name.setAnchor('ne') p_name.setStyle('bold') p_name.setSize(20) p_name.draw(glbl.gw) p_health = Bar(self.current_HP, self.base_HP, 'red', Point(669, 55), Point(989, 81)) p_health.show() p_exp = Bar(self.current_EXP, self.next_EXP, 'green', Point(719, 86), Point(989, 100), show_text=False) p_exp.show() while True: # Check to see if the player has died. if self.current_HP <= 0: raise GameOver('lost battle') #this calls the menu and takes the input to be called here. # returns a valid player selection x = self.battleInput() if x == 'Attack': self.attack_enemy(enemy) elif x in '012': self.abilities[int(x)].execute(self, enemy) elif x.count('Potion') > 0: self.use_potion() elif x == 'Run': self.run(enemy) # Since the player attacked the enemy, update their health bar. e_health.update(enemy.current_HP) # Check to see if the enemy died last turn. # If so, give out rewards, and maybe level up. if enemy.current_HP <= 0: pygame.mixer.music.stop() dialogue(f'{enemy.name} died!', speed=.01, right=True) if enemy.name == 'Orc': glbl.game_stats['orc_dead'] = True raise GameOver('orc dead') else: pygame.mixer.music.stop() town_music = pygame.mixer.music.load("Overworld_Music.mp3") pygame.mixer.music.play(-1) line = f'{self.name} gained {enemy.current_EXP} XP' if enemy.gold > 0: line += f'and {enemy.gold} gold' line += '.' dialogue(line, speed=.01, right=True) self.current_EXP += enemy.current_EXP self.gold += enemy.gold p_exp.update(self.current_EXP) while self.current_EXP >= self.next_EXP: self.level_up() p_exp.update(self.current_EXP, self.next_EXP) sleep(1) glbl.gw.clear(prior) return enemy.take_turn(self) p_health.update(self.current_HP)
def drawSensors(field): # Set initial coordinates to potentially draw sensors and empty list # of sensor locations x = 40 y = 40 sensors = [] goodsensors = [] # Initialize loop to create horizontal sensors for column in range(10): for row in range(10): # Create random number between 0 and 1 h_chance_border = random() v_chance_border = random() # Creates 40% chance horizontal sensor will be drawn if h_chance_border >= 0.6: # Define, draw, and append location of sensor horizontal_sensor = Rectangle(Point(x - 35.5, y), Point(x - 4.5, y)) horizontal_sensor.setWidth(2.5) horizontal_sensor.setOutline("orange") horizontal_sensor.draw(field) h_x = horizontal_sensor.getCenter().getX() h_y = horizontal_sensor.getCenter().getY() sensors.append([h_x, h_y]) # Creates 40% chance horizontal sensor will be drawn if v_chance_border >= 0.6: # Define, draw, and append location of sensor vertical_sensor = Rectangle(Point(x, y - 35.5), Point(x, y - 4.5)) vertical_sensor.setWidth(2.5) vertical_sensor.setOutline("orange") vertical_sensor.draw(field) v_x = vertical_sensor.getCenter().getX() v_y = vertical_sensor.getCenter().getY() sensors.append([v_x, v_y]) # Move to next row y += 40 # Set back to first row after finishing final row y = 40 # Move to the next column x += 40 x = 40 y = 40 # Initialize loop to create good horizontal sensors for column in range(9): for row in range(9): # Create random number between 0 and 1 h_chance_border = random() v_chance_border = random() # Creates 40% chance horizontal sensor will be drawn if h_chance_border <= .25: # Define, draw, and append location of sensor horizontal_sensorgood = Rectangle(Point(x - 35.5, y), Point(x - 4.5, y)) horizontal_sensorgood.setWidth(2.5) horizontal_sensorgood.setOutline("green") h_xg = horizontal_sensorgood.getCenter().getX() h_yg = horizontal_sensorgood.getCenter().getY() if [h_xg, h_yg] not in sensors: horizontal_sensorgood.draw(field) goodsensors.append([h_xg, h_yg]) # Creates 40% chance horizontal sensor will be drawn if v_chance_border <= 0.25: # Define, draw, and append location of sensor vertical_sensorgood = Rectangle(Point(x, y - 35.5), Point(x, y - 4.5)) vertical_sensorgood.setWidth(2.5) vertical_sensorgood.setOutline("green") v_xg = vertical_sensorgood.getCenter().getX() v_yg = vertical_sensorgood.getCenter().getY() if [v_xg, v_yg] not in sensors: vertical_sensorgood.draw(field) goodsensors.append([v_xg, v_yg]) # Move to next row y += 40 # Set back to first row after finishing final row y = 40 # Move to the next column x += 40 # Draw vertical sensors return sensors, goodsensors
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