Ejemplo n.º 1
0
def redraw_board():
    gameloop.init()
    theme.update()  # This is going to create the new theme if it doesn't exist

    # Force the game to update
    graphics.drawGame()
    graphics.update()
Ejemplo n.º 2
0
def main():
	winX = 440
	winY = 660
	winCenter = graphics.Point(winX / 2, winY / 2)
	winName = "| bullet.heck |"
	menu = engine.Menu()
	hud = engine.Hud()
	player = engine.Player()
	window = graphics.GraphWin(winName, winX, winY, autoflush=False)
	wallpaper = graphics.Image(winCenter, "assets/space.gif")
	window.setBackground("black")
	wallpaper.draw(window)

	while (window):
		menu.main(window)
		player.score = 0
		player.lives = 4
		patternNumber = 0
		nextSpawn = randint(125, 160)
		player = engine.Player()
		patternList = list()

		player.draw(window)
		hud.draw(window)
		hud.update_bar(window, player)
		hud.update_score(window, player.score)

		while (player.lives > 0):
			# Game loop starts here.
			press = window.checkKey()
			if (player.score % nextSpawn == 0):
				nextSpawn = randint(125, 160)
				patternList.append(engine.build_attack())
			player.hit = False
			player.move(press)
			for i in range (len(patternList)):
				patternList[i].fire(window)
				patternList[i].move()
				if (patternList[i].detect_hit(player)):
					player.hit = True
			player.score = player.score + 1
			player.update_hitframes()
			player.update_lives()
			player.update_shield(window)
			hud.update_bar(window, player)
			hud.update_score(window, player.score)
			hud.pause(press, window)
			if (player.lives == 0):
				for i in range (len(patternList)):
					patternList[i].undraw()
				player.undraw()
				hud.undraw(window)
				menu.game_over(window, player.score)
			sleep(.03)
			graphics.update(30)
			# Game loop ends here.

	return
def runMenuState(window, control):
    '''Says it on the tin'''
    titleText = common.createTitle(common.GAME_NAME, window)

    sprites,         \
    playButton,      \
    howToPlayButton, \
    highscoreButton, \
    exitButton       = createFrontMenuButtons(window)

    bg = common.createCenteredImage("menu_bg")
    bg.draw(window)

    menu_top = common.createCenteredImage("menu_top")
    menu_top.draw(window)

    apples = []
    for i in range(50):
        addApple(apples, window)

    def displayMenu(guiCreateFunction=None):
        drawer.undrawList([titleText] + sprites)
        showMenu(window, control, apples, guiCreateFunction)
        if window.closed:
            return True
        drawer.drawList([titleText] + sprites, window)
        return False

    start = time.time()
    while control["state"] == states.STATE_MENU and not window.closed:
        key = common.getKeyPress(window)
        point = window.checkMouse()
        elapsed = common.calculateTime(start)

        if button.isButtonPressed(point, playButton, window):
            common.switchState(window, control, states.STATE_PLAYING)
        elif button.isButtonPressed(point, howToPlayButton, window):
            drawer.undrawList([titleText] + sprites)
            displayHowToPlayMenu(window, control, apples)
            if window.closed:
                break
            drawer.drawList([titleText] + sprites, window)
        elif button.isButtonPressed(point, highscoreButton, window):
            if displayMenu(highscores.createHighscoresDisplay):
                break
        elif button.isButtonPressed(point, exitButton, window):
            common.switchState(window, control, states.EXIT)

        updateApples(apples, window)
        #make it so the title is ALWAYS on front
        drawer.redrawSprite(menu_top, window)
        drawer.redrawList([titleText] + sprites, window)
        gfx.update(common.UPDATE_SPEED)

    drawer.undrawList([titleText, bg, menu_top] + sprites + apples)
Ejemplo n.º 4
0
    def step(self, robot=None):
        reward = 0
        scored_bool = False
        died_bool = False
        curr_game_vars = self.game_vars()
        self.v += Game.a
        if robot is not None:
            if np.argmax(robot(np.asarray(curr_game_vars).reshape(
                    1, 2))):  #If the vector is [0 1] i.e. JUMP
                self.v = -200
                self.jumps += 1
        elif self.graph and self.win.checkKey() == 'space':
            self.v = -200
        self.rec.move(0, self.v * Game.dt)
        for i, pipe in enumerate(self.pipes):
            pipe.move()
            if pipe.check_coll(self) or self.check_bounds():
                if self.graph:
                    g.update(self.frame_rate)
                    time.sleep(2)
                    self.win.close()
                self.over = True
                died_bool = True
                #print('dead')
            elif pipe.check_kill(self):
                self.pipes[i] = Game.Pipe(Game.pipe_dx,
                                          Game.pipe_space * 3 - Game.pipe_dx,
                                          self.pipe_ran(), Game.pipe_v,
                                          self.pipe_dy, self.win)
                if self.graph:
                    self.pipes[i].draw(self)
                self.score += 1
                scored_bool = True

        if self.graph and (self.success_model is not None):
            self.draw_network_neurons()

        #Cookie allocation
        if died_bool:
            reward = -1
#        elif scored_bool:   #Reward for getting a point?
#            reward = 1
        else:
            tdist, ddist = curr_game_vars
            r2 = (tdist**2 + ddist**2)
            # reward = 0.01  + min(60**3/(r2**1.5), 1) #FOR SUCCESS 1-3
            #reward = np.exp(-0.5*r2/120**2) #Gaussian
            reward = 0.01 + min(45**3 / (r2**1.5), 1)  #For final success model
        done = died_bool or (self.score >= Game.thresh)
        self.t += Game.dt
        self.frame += 1
        if self.graph:
            g.update(self.frame_rate)  #20 slows it down, 60 is really fast
        return curr_game_vars, reward, done, (self.frame, self.score,
                                              self.jumps)
Ejemplo n.º 5
0
    def __init__(self, name="Twixt"):
        self.bottom = self.CELL*(2+self.SIZE)
	self.win = gr.GraphWin(name, self.CELL*(2+self.SIZE), self.bottom+self.CELL, autoflush=False)
	self.history = []
	self.known_moves = set()

	# Regular background
	self.win.setBackground(gr.color_rgb(244, 255,240))

        # bottom
        for i in range(20):
            peg = gr.Circle(self.center(i,25), self.PEG_RADIUS)
            peg.setWidth(0)
            peg.setFill(self._colors(i))
            peg.draw(self.win)
        
	# black/white end zones
	for i in range(4):
	    a = self.twopoints(i)
	    b = self.twopoints(i+1)
	    color = [gr.color_rgb(255,255,200), gr.color_rgb(200,200,200)][i&1]
	    poly = gr.Polygon(a[0], a[1], b[1], b[0])
	    poly.setOutline(color)
	    poly.setFill(color)
	    poly.draw(self.win)

	# peg holes
	for x in range(self.SIZE):
	    for y in range(self.SIZE):
		if x in (0, self.SIZE-1) and y in (0, self.SIZE-1):
		    continue

		c = gr.Circle(self.center(x, y), self.HOLE_RADIUS)
		c.setFill("black")
		c.draw(self.win)

	# labels
	for i in range(self.SIZE):
	    ctr = self.center(i, i)
	    row_label = "%d" % (i+1)
	    txt = gr.Text(gr.Point(self.CELL/2, ctr.y), row_label)
	    txt.draw(self.win)
	    txt = txt.clone()
	    txt.move(self.CELL*(self.SIZE+1), 0)
	    txt.draw(self.win)

	    col_label = chr(ord('A')+i)
	    txt = gr.Text(gr.Point(ctr.x, self.CELL/2), col_label)
	    txt.draw(self.win)
	    txt = txt.clone()
	    txt.move(0, self.CELL*(self.SIZE+1))
	    txt.draw(self.win)

	gr.update()
Ejemplo n.º 6
0
 def initialize_display(self, ants):
     """ causes the screen to be updated to current win data """
     for i in range(0, self.num_ants):
         # map lattice to screen pixels
         x_pixel = self.pixel_expand * ants[i][0]
         y_pixel = self.pixel_expand * ants[i][1]
         self.screen_ants[i] = Circle(Point(x_pixel, y_pixel),
                                      self.ant_size)
         self.screen_ants[i].setFill(self.ant_color)
         self.screen_ants[i].draw(self.win)
     update()
Ejemplo n.º 7
0
def move_card_down():

    border = 190

    back_of_card = Image(Point(WIN.getWidth() / 2,
                               WIN.getHeight() / 4), "images/deck.png")
    back_of_card.draw(WIN)

    # Moves card down
    while back_of_card.getAnchor().getY() < WIN.getHeight() - border:
        back_of_card.move(0, MOVEMENT_SPEED)
        update()

    return back_of_card
Ejemplo n.º 8
0
def runGame(window, control):
    '''Main loop of the game'''
    #Chooses state based on the main control
    while control["running"]:
        currentState = control["state"]
        if currentState == states.STATE_MENU:
            runMenuState(window, control) 
        elif currentState == states.STATE_PLAYING:
            score, elapsed = runPlayState(window, control)
        elif currentState == states.STATE_GAME_OVER:
            runGameOverState(window, control, score, elapsed)
        #Exit the game
        if window.closed or currentState == states.EXIT:
            control["running"] = False 
        gfx.update(common.UPDATE_SPEED)
Ejemplo n.º 9
0
    def bogo_sort(self):
        """Bogo sort for python list
        """
        shuffle(self.data)
        self.colors = ['white' for n in range(len(self.data))]
        self.bars.drawData(self.colors)

        while self.data != sorted(self.data):
            shuffle(self.data)
            self.colors = ['white' for n in range(len(self.data))]
            self.bars.drawData(self.colors)
            update(self.speed)

        self.colors = ['white' for n in range(len(self.data))]
        self.bars.drawData(self.colors)
Ejemplo n.º 10
0
def main():
    win = GraphWin("Fall Drawing", 600, 600, autoflush=False)

    draw_background(win)
    sun = draw_sun(win)
    draw_forest(win)

    end = False
    while not end:
        key = win.checkKey()
        if key == "q":
            end = True
            win.close()
        update(win, sun)
        graphics.update(30)
Ejemplo n.º 11
0
    def cycle_sort(self):
        """Cycle sort for python list
        """
        ans = 0

        for cycleStart in range(0, len(self.data) - 1):
            item = self.data[cycleStart]

            pos = cycleStart
            for i in range(cycleStart + 1, len(self.data)):
                if self.data[i] < item:
                    pos += 1

            if pos == cycleStart:
                continue

            while item == self.data[pos]:
                pos += 1
            self.data[pos], item = item, self.data[pos]
            self.colors = [
                'red' if n == pos or n == pos + 1 else 'green'
                for n in range(len(self.data))
            ]
            self.bars.drawData(self.colors)
            update(self.speed)
            ans += 1

            while pos != cycleStart:

                pos = cycleStart
                for i in range(cycleStart + 1, len(self.data)):
                    if self.data[i] < item:
                        pos += 1

                while item == self.data[pos]:
                    pos += 1
                self.data[pos], item = item, self.data[pos]

                self.colors = [
                    'red' if n == pos or n == pos + 1 else 'green'
                    for n in range(len(self.data))
                ]
                self.bars.drawData(self.colors)
                update(self.speed)
                ans += 1

        self.colors = ['white' for n in range(len(self.data))]
        self.bars.drawData(self.colors)
Ejemplo n.º 12
0
 def bubble_sort(self):
     """Bubble sort for python list
     """
     for _ in range(len(self.data) - 1):
         for j in range(len(self.data) - 1):
             if self.data[j] > self.data[j + 1]:
                 self.data[j], self.data[j + 1] = self.data[j +
                                                            1], self.data[j]
                 self.colors = [
                     'red' if n == j or n == j + 1 else 'green'
                     for n in range(len(self.data))
                 ]
                 self.bars.drawData(self.colors)
                 update(self.speed)
     self.colors = ['white' for n in range(len(self.data))]
     self.bars.drawData(self.colors)
Ejemplo n.º 13
0
    def start_simulation(self, simulation_speed=1, framerate=30):
        # Header initializes window
        simulation_speed = 1 / simulation_speed

        win_name = self.name + " - N-Body Problem"
        win = GraphWin(win_name, self.size, self.size, autoflush=False)
        win.setBackground("black")
        win.setCoords(-self.size / (2 * self.scale),
                      -self.size / (2 * self.scale),
                      self.size / (2 * self.scale),
                      self.size / (2 * self.scale))

        # Body
        start_time = time.time()
        current_time = time.time()
        draw_time = time.time()

        while win.checkMouse() is None:
            # FIXME this should be drawspeed
            if simulation_speed < time.time() - current_time:

                current_time = time.time()
                # draw update to window
                win.delete("all")
                # TODO ezen belul legyen
                self.update(simulation_speed)
                self.print(win)
            # If max time is exceeded break out of loop
            else:
                continue

            # Max time reached stop simulation
            if self.max_time < time.time() - start_time:
                break

            # If time passed is greater than refresh rate, refresh
            # TODO lehet ezt az updaten belul kulon is kene kezelni
            update(framerate)

        # Trailer closes window
        win.close()
        if not self.collisions:
            print("Simulation successful; System Stable")
        else:
            print("Simulation over; System Unstable\nCollisions: ",
                  self.collisions)
Ejemplo n.º 14
0
 def __init__(self, position, size, win, counter):
     self.position = position
     self.size = size
     self.win = win
     self.counter = counter
     self.brain = None
     self.genome = None
     bl = Point(position.x + size.x * SCALE, position.y + size.y * SCALE)
     self.__rectangle = Rectangle(position, bl)
     self.__rectangle.setFill('black')
     self.__rectangle.draw(self.win)
     self.__text = Text(self.position + Point(20, 20), '0')
     self.__text.setFill('grey')
     self.__text.draw(win)
     update()
     self.snake = Snake(win, self)
     self.food = Food(win, self)
Ejemplo n.º 15
0
    def run(self):
        """Runs the simulation until the user closes out."""
        drawables = []
        t0 = time.time()
        while self._window.isOpen():
            # Resolve time since last tick.
            t = time.time()
            dt = t - t0
            t0 = t

            # Run simulation for 1 tick.
            self._undraw(drawables)
            drawables = []
            self._body.update(dt)
            drawables.extend([self._draw_body()])
            self._draw(drawables)
            g.update(60)
Ejemplo n.º 16
0
def game_loop():
    global events, run, scene, lawrence, sc, ents, clock, lag, restart, ms
    while (run):
        ms = clock.tick(con.framerate)
        lag = lag + ms - con.ms_per_frame

        # Game Logic
        if lawrence.isAlive():
            gamespeed.update()

        events.update()
        lawrence.update()
        scene.update()

        for e in ents:
            e.update()

        # Update Score
        if gamespeed.frame % 15 == 0:
            sc.addScore(1)

        # Collision
        if lawrence.isAlive():
            for e in ents:
                if lawrence.rect.colliderect(e.rect):
                    if e.type > objects.EntityType.HURDLE:  # If it is a food.
                        sc.addScore(e.hit())
                    else:
                        lawrence.collide(e)
                        restart = True
                        if con.audio_support:
                            pygame.mixer.music.stop()

        if lag > con.ms_per_frame:
            graphics.update()
            lag -= con.ms_per_frame

        for e in events.event_queue:
            if e.type == pygame.QUIT:
                run = False
            elif e.type == pygame.KEYUP:
                if e.key == pygame.K_F4 and (e.mod & pygame.KMOD_ALT):
                    run = False
        if restart:
            break
Ejemplo n.º 17
0
 def insertion_sort(self):
     """Insertion sort for python list
     """
     for i in range(1, len(self.data)):
         key = self.data[i]
         j = i - 1
         while j >= 0 and key < self.data[j]:
             self.data[j + 1] = self.data[j]
             j -= 1
             self.colors = [
                 'red' if n == j or n == j + 1 else 'green'
                 for n in range(len(self.data))
             ]
             self.bars.drawData(self.colors)
             update(self.speed)
         self.data[j + 1] = key
         self.colors = ['white' for n in range(len(self.data))]
         self.bars.drawData(self.colors)
Ejemplo n.º 18
0
    def run(self):
        """Runs the simulation until the user closes out."""
        self._draw(self._static_drawables())
        dynamic_drawables = []
        t0 = time.time()
        while self._window.isOpen():
            # Resolve time since last tick.
            t = time.time()
            dt = (t - t0) * SCALE
            t0 = t

            # Run simulation for 1 tick.
            self._undraw(dynamic_drawables)
            dynamic_drawables = []
            self._rocket.update(dt)
            dynamic_drawables.extend(self._rocket.drawables())
            self._draw(dynamic_drawables)
            g.update(FPS)  # Enforce FPS.
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)
Ejemplo n.º 20
0
    def selection_sort(self):
        """Selection sort for python list
        """
        for i in range(len(self.data)):
            min_idx = i
            for j in range(i + 1, len(self.data)):
                if self.data[min_idx] > self.data[j]:
                    min_idx = j

            self.data[i], self.data[min_idx] = self.data[min_idx], self.data[i]
            self.colors = [
                'red' if n == i or n == i + 1 else 'green'
                for n in range(len(self.data))
            ]
            self.bars.drawData(self.colors)
            update(self.speed)

        self.colors = ['white' for n in range(len(self.data))]
        self.bars.drawData(self.colors)
def showMenu(window, control, apples, guiCreateFunction):
    '''Shows a basic menu which only has a back button (eg how to play, highscores)'''
    sprites = guiCreateFunction(window)
    backButtonSprites, \
    backButtonBounds   = button.create(BACK_BTN_Y, "Back", window)

    menu_top = common.createCenteredImage("menu_top")
    menu_top.draw(window)

    sprites += backButtonSprites
    while not window.closed:
        mouseClickPoint = window.checkMouse()
        updateApples(apples, window)
        if button.isButtonPressed(mouseClickPoint, backButtonBounds, window):
            break
        drawer.redrawSprite(menu_top, window)
        drawer.redrawList(sprites, window)
        gfx.update(common.UPDATE_SPEED)
    drawer.undrawList(sprites + [menu_top])
Ejemplo n.º 22
0
def update_step(win, step, update_interval, fps=None, text=None):
    """

    :param win: window to draw in
    :param step: how many times to run
    :param update_interval: how quick to update window being drawn. 1 for fast
    :param text: variable text to screen
    :return:
    """
    if update_interval and step % update_interval == 0:
        if text != None:
            format_str = 'step = {0}'
            text.setText(format_str.format(step))
        if fps is None:
            # win.update()
            graphics.update(
            )  # optional argument to throttle at x frames per second
        else:
            graphics.update(
                fps)  # optional argument to throttle at x frames per second
Ejemplo n.º 23
0
    def gnome_sort(self):
        """Gnome sort for python list
        """
        i = 1
        while i < len(self.data):
            if self.data[i - 1] <= self.data[i]:
                i += 1
            else:
                self.data[i - 1], self.data[i] = self.data[i], self.data[i - 1]
                self.colors = [
                    'red' if n == i or n == i + 1 else 'green'
                    for n in range(len(self.data))
                ]
                self.bars.drawData(self.colors)
                update(self.speed)
                i -= 1
                if i == 0:
                    i = 1

        self.colors = ['white' for n in range(len(self.data))]
        self.bars.drawData(self.colors)
Ejemplo n.º 24
0
    def set_game(self, game):
	i = 0
	while i < len(game.history) and i < len(self.history):
	    if game.history[i] != self.history[i].move:
		break
	    i += 1

	# Get rid of now unneeded objects
	if i < len(self.history):
	    for h in reversed(self.history[i:]):
		for o in h.objects:
		    o.undraw()
		self.known_moves.remove(h.move)
	    self.history = self.history[:i]

	# Add new objects
	while i < len(game.history):
	    self.create_move_objects(game, i)
	    i += 1

	gr.update()
def runGameOverState(window, control, score, elapsed):
    '''Runs after the player has run out of lives'''
    bg = common.createCenteredImage("menu_bg")
    bg.draw(window)
    overallScore = score * round(elapsed)
    messages = [
        addMessage(window, "GAME OVER", 30, "red", reset=True, bold=True),
        addMessage(window, "Score: " + str(score)),
        addMessage(window, "Time:  " + str(round(elapsed)) + " seconds"),
        addMessage(window, "Final Score:  " + str(overallScore))
    ]

    sprites,            \
    playAgainButton,    \
    submitScoreButton,  \
    exitToMenuButton    = makeGameOverButtons(len(messages), window)
    sprites += messages

    scoreSubmitted = False
    while control["state"] is states.STATE_GAME_OVER and not common.shouldExit(
            window, control):
        mouseClick = window.checkMouse()
        if button.isButtonPressed(mouseClick, playAgainButton, window):
            common.switchState(window, control, states.STATE_PLAYING)
        elif button.isButtonPressed(mouseClick, submitScoreButton,
                                    window) and not scoreSubmitted:
            drawer.undrawList(sprites)
            submitScoreState(window, control, overallScore)
            if window.closed:
                break
            drawer.drawList(sprites, window)
            scoreSubmitted = True
            sprites[0].setFill("dim gray")
            sprites[1].setFill("gray")
        elif button.isButtonPressed(mouseClick, exitToMenuButton, window):
            common.switchState(window, control, states.STATE_MENU)

        gfx.update(common.UPDATE_SPEED)

    drawer.undrawList(sprites + [bg])
Ejemplo n.º 26
0
    def pigeon_sort(self):
        """Pigeon sort for python list
        """
        min = self.data[0]
        max = self.data[0]

        for i in range(len(self.data)):
            if self.data[i] < min:
                min = self.data[i]
            elif self.data[i] > max:
                max = self.data[i]

        holes_range = max - min + 1
        holes = [0 for _ in range(holes_range)]
        holes_repeat = [0 for _ in range(holes_range)]

        for i in range(len(self.data)):
            index = self.data[i] - min
            if holes[index] != self.data[i]:
                holes[index] = self.data[i]
                holes_repeat[index] += 1
            else:
                holes_repeat[index] += 1

        index = 0
        for i in range(holes_range):
            while holes_repeat[i] > 0:
                self.data[index] = holes[i]
                self.colors = [
                    'red' if n == index or n == index + 1 else 'green'
                    for n in range(len(self.data))
                ]
                self.bars.drawData(self.colors)
                update(self.speed)
                index += 1
                holes_repeat[i] -= 1

        self.colors = ['white' for n in range(len(self.data))]
        self.bars.drawData(self.colors)
Ejemplo n.º 27
0
def main():
    win = graphics.GraphWin("Gravity", width, height, autoflush=False)

    sbody_image.draw(win)  # Draws Special Body
    sbody_image.setFill("blue")

    for pair in space:  # Initializes the space, draws all particles
        particle = pair[0]
        particle_circle = pair[1]
        particle_circle.draw(win)
        particle_circle.setFill("black")

    for frame in range(nframes):  # Instructions for frame refresh
        for pair in space:
            particle = pair[0]
            circle = pair[1]
            dx = particle.dx * timestep / scale
            dy = particle.dy * timestep / scale
            circle.move(dx, dy)
            particle.update_a(space, special_bodies)
            particle.update_v()
            particle.update_r(win)
        graphics.update(1 / framestep)
Ejemplo n.º 28
0
def main():
    dialog = InputDialog(45, 40, 2)
    choice = dialog.interact()
    if choice == "Fire!":
        angle, vel, height = dialog.getValues()

    # create animation window
    win = GraphWin("Projectile Animation", 640, 480, autoflush=False)
    win.setCoords(-10, -10, 210, 155)

    # draw baseline
    Line(Point(-10, 0), Point(210, 0)).draw(win)

    # draw labeled ticks every 50 meters

    for x in range(0, 210, 50):
        Text(Point(x, -5), str(x)).draw(win)
        Line(Point(x, 0), Point(x, 2)).draw(win)

        # Event loop, each time through fires a single shot
        angle, vel, hieght = 45.0, 40.0, 2.0
        while True:
            # interact with the user
            inputwin = InputDialog(angle, vel, height)
            choice = inputwin.interact()
            inputwin.close()

            if choice == "Quit":  # loop exit
                break
            # create a shot and track until it hits ground or leaves window
            angle, vel, height = inputwin.getValues()
            shot = ShotTracker(win, angle, vel, height)
            while 0 <= shot.getY() and -10 < shot.getX() <= 210:
                shot.update(1 / 50)
                update(50)

        win.close()
def displayHowToPlayMenu(window, control, apples):
    '''Displays the how to play menu, eg it's buttons'''
    sprites, ctrlButton, objButton, typeButton = createHowToPlayMenu(window)
    backButtonSprites, \
    backButtonBounds   = button.create(BACK_BTN_Y, "Back", window)

    menu_top = common.createCenteredImage("menu_top")
    menu_top.draw(window)

    def displayMenu(guiCreateFunction):
        drawer.undrawList(sprites + backButtonSprites)
        showMenu(window, control, apples, guiCreateFunction)
        if window.closed:
            return True
        drawer.drawList(sprites + backButtonSprites, window)
        return False

    while not window.closed:
        mouseClickPoint = window.checkMouse()
        updateApples(apples, window)
        if button.isButtonPressed(mouseClickPoint, backButtonBounds, window):
            break
        if button.isButtonPressed(mouseClickPoint, ctrlButton, window):
            if displayMenu(createHowToControls):
                break
        if button.isButtonPressed(mouseClickPoint, objButton, window):
            if displayMenu(createHowToObjectives):
                break
        if button.isButtonPressed(mouseClickPoint, typeButton, window):
            if displayMenu(createHowToAppleTypes):
                break

        drawer.redrawSprite(menu_top, window)
        drawer.redrawList(sprites, window)
        gfx.update(common.UPDATE_SPEED)
    drawer.undrawList(sprites + backButtonSprites + [menu_top])
Ejemplo n.º 30
0
def main():

    win = graphics.GraphWin('Paddle Game', 800, 800, autoflush=True)
    win.setBackground('gray')
    win.setCoords(0, 0, 10, 10)

    ball = Ball(0.2, 5, 'blue', 30)
    ball.setLocation(5, 5)
    ball.draw(win)

    paddle = Paddle(4, .3, 11, 'blue')
    paddle.draw(win)

    paddle.setLocation(1.5, 5)

    while True:

        graphics.update(30)

        ball.moveBehavior(graphics.Point(5, 5), 10, 10, 30, win, paddle)

        key = win.checkKey()

        if key == 'Up':

            paddle.glide(1, 30)

        elif key == 'Down':

            paddle.glide(-1, 30)

        if key == 'r':

            ball = Ball(0.2, 5, 'blue', 30)
            ball.setLocation(5, 5)
            ball.draw(win)
Ejemplo n.º 31
0
def move_card_across(cards_in_hand, rand_card, player):

    border = 160
    # Moves card across using the number of cards as an interger multipier,
    #   an if statment is used to direct the card left or right depending on
    #   which half of the screen the card needs to go.
    if player == "human":
        while rand_card.getAnchor().getX() > cards_in_hand * border:
            rand_card.move(-MOVEMENT_SPEED, 0)
            update()
    elif player == "ai":
        while rand_card.getAnchor().getX() < WIN.getWidth() - \
                cards_in_hand * border:
            rand_card.move(MOVEMENT_SPEED, 0)
            update()

    update()
Ejemplo n.º 32
0
def init():
    game.init()
    graphics.drawGame()
    graphics.update()
Ejemplo n.º 33
0
def update():
    global tile, currentIdx, currentMenu, currentCategory, prevIndex, symbolMode, nameMode, theme_name, menu_stack

    key = graphics.screen.getch()

    if key > 0:
        ''' Symbol Mode '''
        if symbolMode:
            input_string(key)
            if tile == '':
                tile = '  '
            category = currentMenu[currentIdx][0]
            theme.set_tiles_theme(category, tile[:2])
            tile = ''
            redraw_board()
            symbolMode = False
            return

        ''' Enter Name for new theme '''
        if nameMode:
            input_string(key)
            theme_name = tile
            tile = ''
            # Sanitise name
            theme_name = theme_name.replace(" ", "-")  # Replaces spaces
            theme_name = re.sub(r'[^a-zA-Z0-9-]', r'', theme_name)  # Remove special characters
            theme_name = theme_name[:20]  # Trim to 20 characters
            # Crate new theme and refresh
            redraw_board()
            menus.update_naming()
            # Go back to main menu
            del menu_stack[:]
            menu_stack = [[menus.main, '']]
            menu_stack.append([menus.editMain, theme_name])
            currentMenu = menus.editMain
            currentIdx = 0
            nameMode = False
            return

        ''' Check KEYS '''
        if key == keys['DOWN']:
            currentIdx = (currentIdx + 1) % len(currentMenu)
            # Preview colors
            if currentMenu == menus.colors:
                set_color()
            elif currentMenu == menus.naming:
                # pass the saved name from the theme
                theme_name = currentMenu[currentIdx][0]
                redraw_board()
            return
        elif key == keys['UP']:
            currentIdx = (currentIdx - 1) % len(currentMenu)
            # Preview colors
            if currentMenu == menus.colors:
                set_color()
            elif currentMenu == menus.naming:
                # Pass the saved name from the theme
                theme_name = currentMenu[currentIdx][0]
                redraw_board()
            return
        elif key == keys['LEFT']:
            navigate_back()
            return
        elif key == keys['ENTER'] or key == keys['RIGHT']:
            # Back
            if (currentIdx == len(currentMenu) - 1):
                navigate_back()
                return
            # Color option
            elif currentMenu[currentIdx][1] is None:
                set_color()
                navigate_back()
                return
            # Tile option
            elif currentMenu[currentIdx][1] == "symbols":
                symbolMode = True
                return
            # Custom Name Mode
            elif currentMenu[currentIdx][1] == "name":
                nameMode = True
                return
            # Delete
            elif currentMenu[currentIdx][1] == "delete":
                delete_theme()
                return
            # Screenshot
            elif currentMenu[currentIdx][1] == "screenshot":
                take_screenshot()
                menus.editMain[3] = ["Take Screenshot [TAKEN]", "screenshot"]
                return
            # Modify existing theme
            elif currentMenu[currentIdx][1] == "existing":
                # pass the saved name from the theme
                theme_name = currentMenu[currentIdx][0]
                theme.update_name()
                redraw_board()
                graphics.update()
                title = currentMenu[currentIdx][0]
                menu_stack.append([menus.editMain, title])
                currentMenu = menus.editMain
                currentIdx = 0
                return
            # Submenu
            else:
                # Prevent Delete of custom-theme
                if currentMenu == menus.editMain and currentIdx == 2 and \
                   theme_name == os.path.splitext(theme.CUSTOM_THEME)[0]:
                    return
                prevIndex = currentIdx
                title = currentMenu[currentIdx][0]
                menu_stack.append([currentMenu[currentIdx][1], title])
                if (currentMenu == menus.board or currentMenu == menus.elements):
                    currentCategory = title
                currentMenu = currentMenu[currentIdx][1]
                currentIdx = 0
                # Preview colors
                if currentMenu == menus.colors:
                    set_color()
                # Redraw with first theme on the list
                if currentMenu == menus.naming:
                    theme_name = currentMenu[0][0]
                    redraw_board()

        elif key == keys['Q']:
            __main__.exit()
            exit()
Ejemplo n.º 34
0
def update():
    game.update()
    graphics.update()
    controls.clear()
Ejemplo n.º 35
0
def update():
    game.update()
    graphics.update()