I'm trying to stop 3 animations in my function when it reaches a certain point and then have a message display "Animations Stopped".
How would I do this? I know about display.NewText() but how would I go about stopping the animations and getting the message to pop up at the same time?
Here is the function I'm trying to stop.
WIDTH = display.contentWidth
HEIGHT = display.contentHeight
--displays background
local s = display.newImageRect("space.png" ,1136, 640)
s.x = 900/2
s.y = 500/2
--display main ship
local r = display.newImageRect("ship.png", 70, 70)
r.x = 20
r.y = 450
local minions = {}
function createMinions()
local x = 40
local y = 120
for n = 1, 20 do -- displays 20 minions
local minion = display.newImageRect("minion.png", 50, 50)
minion.x = x
minion.y = y
minions[n] = minion
x = x + 60 -- next enemy will be to the right
if x >= WIDTH then -- start a new row if necessary
y = y + 60 -- seperation between minions
x = 40
end
end
end
--display mothership
m = display.newImageRect("mothership.png", 150, 150)
m.x = 160
m.y = 10
function nextFrame()
-- begins movements of main ship to right
r.x = r.x + 5
if r.x > 350 then
r.x = -100
end
-- begins movement of minions to the left
for i = 1, 20 do
local minion = minions[i]
minion.x = minion.x - 8
if minion.x < -100 then
minion.x = 400
end
end
--begins movement of mothership towards small ship
m.y = m.y + 10
if m.y > 460 then
m.y = -100
end
--stops all animations
if m.y > 450 then
--r.x = r.x + 0
--m.y = m.y + 0
--minion.x = minion.x + 0
local s = true
--displays game over text
s = display.newText("Game Over", WIDTH/2, 400, native, 30)
end
end
createMinions()
Runtime:addEventListener( "enterFrame", nextFrame )
--hides status bar
display.setStatusBar( display.HiddenStatusBar )
Just to make it very short -
This is the code specific to your problem.
if(m.y < 450) then YOURCODE else DISPLAYTEXTCODE end
For future I suggest people to look at:
Corona Docs: API > Libraries > Transition > To - To move display objects.
and
Corona Docs: APi > Types > EventListener > addEventListener - To trigger code based on events.
Related
I am reading "Numerical Methods for Engineers" by Chapra and Canale. In it, they've provided pseudocode for the implementation of Euler's method (for solving ordinary differential equations). Here is the pseucode:
Pseucode for implementing Euler's method
I tried implementing this code in GNU Octave, but depending on the input values, I am getting one of two errors:
The program doesn't give any output at all. I have to press 'Ctrl + C' in order to break execution.
The program gives this message:
error: 'ynew' undefined near line 5 column 21
error: called from
Integrator at line 5 column 9
main at line 18 column 7
I would be very grateful if you could get this program to work for me. I am actually an amateur in GNU Octave. Thank you.
Edit 1: Here is my code. For main.m:
%prompt user
y = input('Initial value of y:');
xi = input('Initial value of x:');
xf = input('Final value of x:');
dx = input('Step size:');
xout = input('Output interval:');
x = xi;
m = 0;
xpm = x;
ypm = y;
while(1)
xend = x + xout;
if xend > xf
xend = xf;
h = dx;
Integrator(x,y,h,xend);
m = m + 1;
xpm = x;
ypm = y;
if x >= xf
break;
endif
endif
end
For Integrator.m:
function Integrator(x,y,h,xend)
while(1)
if xend - x < h
h = xend - x;
Euler(x,y,h,ynew);
y = ynew;
if x >= xend
break;
endif
endif
end
endfunction
For Euler.m:
function Euler(x,y,h,ynew)
Derivs(x,y,dydx);
ynew = y + dydx * h;
x = x + h;
endfunction
For Derivs.m:
function Derivs(x,y,dydx)
dydx = -2 * x^3 + 12 * x^2 - 20 * x + 8.5;
endfunction
Edit 2: I shoud mention that the differential equation which Chapra and Canale have given as an example is:
y'(x) = -2 * x^3 + 12 * x^2 - 20 * x + 8.5
That is why the 'Derivs.m' script shows dydx to be this particular polynomial.
Here is my final code. It has four different M-files:
main.m
%prompt the user
y = input('Initial value of y:');
x = input('Initial value of x:');
xf = input('Final value of x:');
dx = input('Step size:');
xout = dx;
%boring calculations
m = 1;
xp = [x];
yp = [y];
while x < xf
[x,y] = Integrator(x,y,dx,min(xf, x+xout));
m = m+1;
xp(m) = x;
yp(m) = y;
end
%plot the final result
plot(xp,yp);
title('Solution using Euler Method');
ylabel('Dependent variable (y)');
xlabel('Independent variable (x)');
grid on;
Integrator.m
%This function takes in 4 inputs (x,y,h,xend) and returns 2 outputs [x,y]
function [x,y] = Integrator(x,y,h,xend)
while x < xend
h = min(h, xend-x);
[x,y] = Euler(x,y,h);
end
endfunction
Euler.m
%This function takes in 3 inputs (x,y,h) and returns 2 outputs [x,ynew]
function [x,ynew] = Euler(x,y,h)
dydx = Derivs(x,y);
ynew = y + dydx * h;
x = x + h;
endfunction
Derivs.m
%This function takes in 2 inputs (x,y) and returns 1 output [dydx]
function [dydx] = Derivs(x,y)
dydx = -2 * x^3 + 12 * x^2 - 20 * x + 8.5;
endfunction
Your functions should look like
function [x, y] = Integrator(x,y,h,xend)
while x < xend
h = min(h, xend-x)
[x,y] = Euler(x,y,h);
end%while
end%function
as an example. Depending on what you want to do with the result, your main loop might need to collect all the results from the single steps. One variant for that is
m = 1;
xp = [x];
yp = [y];
while x < xf
[x,y] = Integrator(x,y,dx,min(xf, x+xout));
m = m+1;
xp(m) = x;
yp(m) = y;
end%while
from graphics import *
def draw():
returnStuff = {'again' : 0, '1st' : 1 }
draw.again = False
win = GraphWin("Quadrilateral Maker", 600, 600)
win.setBackground("yellow")
text = Text(Point(150, 15), 'Click 4 points to create a Quadrilateral')
text.draw(win)
#gets the 4 points
p1 = win.getMouse()
p1.draw(win)
p2 = win.getMouse()
p2.draw(win)
p3 = win.getMouse()
p3.draw(win)
p4 = win.getMouse()
p4.draw(win)
vertices = [p1, p2, p3, p4]
#draws the shape
quad = Polygon(vertices)
quad.setFill('red')
quad.setOutline('black')
quad.setWidth(3)
quad.draw(win)
text.setText('Click in the appropriate box.')
#Quit box
quitBox = Rectangle(Point(30, 500), Point(100,550))
quitBox.setFill('green')
quitBox.draw(win)
quitorNah = Text(Point(60, 490), 'Quit')
quitorNah.draw(win)
#again box
quitBox = Rectangle(Point(480, 500), Point(550,550))
quitBox.setFill('green')
quitBox.draw(win)
quitorNah = Text(Point(510, 490), 'Draw Again')
quitorNah.draw(win)
click = win.getMouse()
x = click.getX()
y = click.getY()
while True:
if 30 < x < 100 and 500 < y < 550:
returnStuff['again'] = 0
win.close()
break
elif 480 < x < 550 and 500 < y < 550:
returnStuff['again'] = 1
win.close()
break
return returnStuff
count = 1
returnValue = draw()
if returnValue['1st'] == 1:
count = 0
while count == 1 or returnValue['again'] == 1:
return_value = draw()
So I have this simple interactive program using Zelle graphics, it asks the user to click on 4 points in a window and from that it creates a shape. Then, the user is shown 2 boxes, one to quit and one to draw again. My draw again isn't working, and it has something to do with the return value. I am returning a dictionary, as I need access to 2 of the variables within the function. In the 'returnStuff' dictionary, I have a part called 'again', which is initially set to 0. If the user clicks in the run again box, it changes this value to 1, and then outside the function I have an if statement that should call the function again if that again value is 1. It does this properly the FIRST time, but the 2nd time around my program just stops all together, and I don't understand why.
Can anybody explain why this is happening?
I think you need a while...
while count==1 or returnValue['again'] == 1:
returnValue = draw()
Okay so I kind of am almost there but need a little push:
My dustbins spawn but there are a few to begin with like I want and then after about 30 seconds of the numbers of dustbins increasing there are 1000's all clumped together.. What can i do to alter my function so that its only ever a few at a time:
function spawnDustbin()
dustbin = {}
for i = 1,800 do
dustbin[i] = display.newImage("dustbin.png")
dustbin[i].xScale = 0.55
dustbin[i].yScale = 0.55
dustbin[i].y = 555
dustbin[i].x = (math.random(1000,1500) * i)
dustbin[i].speed = 4
physics.addBody( dustbin[i], "static", { friction=1.0, density=1.0, bounce=0, radius=30,} )
dustbin[i].enterFrame = moveDustbin
Runtime:addEventListener("enterFrame", dustbin[i])
end
end
and the movedustbin function simply moves the dustbin in the negative x direction:
function moveDustbin(self,event)
if self.x < -2560 then
self.x = 2560
else
self.x = self.x - val
end
end
First 20ish seconds:
http://i.stack.imgur.com/7iEeP.png
After 20 seconds:
http://i.stack.imgur.com/aae0D.png
Thank you very much
James
That "spawnDustbin" function above is spawning 800 dustbins every frame. That will really crush your performance, and I am pretty certain you don't want to create that many objects every frame.
You might want to do something like this:
local dustbin = {}
local i = 0
local function spawnDustbin()
i = i+1
dustbin[i] = display.newImage("dustbin.png")
dustbin[i].xScale = 0.55
dustbin[i].yScale = 0.55
dustbin[i].y = 555
dustbin[i].x = (math.random(1000,1500) * i)
dustbin[i].speed = 4
physics.addBody( dustbin[i], "static", { friction=1.0, density=1.0, bounce=0, radius=30,} )
dustbin[i].enterFrame = moveDustbin
Runtime:addEventListener("enterFrame", dustbin[i])
end
timer.performWithDelay(500, spawnDustbin, 10)
YMMV but that will spawn 10 dustbins in 5 seconds.
I created this function to figure out if betting either side of proposition bet on how many 3 pointers there will be in a particular basketball game is profitable. I project how many total three pointers will be made pjTotal3s and the standard deviation pjGame3STD earlier in the code. The threes_over is the the number given to me by the betting site for which I try to find if the total number of threes will be over or under that number. In this case it is 14.5.
threes_over = 14.5
def overunder(n):
over_count = 0
under_count = 0
push_count = 0
overodds = 0
underodds = 0
for i in range(n):
if round(np.random.normal(pjTotal3s,pjGame3STD)) > threes_over:
over_count = over_count + 1
if round(np.random.normal(pjTotal3s,pjGame3STD)) < threes_over:
under_count = under_count +1
if round(np.random.normal(pjTotal3s,pjGame3STD)) == threes_over:
push_count = push_count + 1
return over_count, under_count, push_count
Then I simulate it a 100,000 overunder(100000) times and it gives me how many times the number of three pointers will be over, under or equal to the number given. This works fine but I still have to more work to do to find if it is a profitable bet.
Assuming that this the output (57550, 42646, 0) I have to manually input it like so and do more to find out if either side of the bet is worthwhile.
over_count = 57550
under_count = 42646
over = 1/(over_count / (over_count + under_count))
under = 1/ (under_count / (over_count + under_count))
over_odds_given = 1.77
under_odds_given = 2.05
overedge = 1/over * over_odds_given - 1
underedge = 1/under * under_odds_given - 1
print overedge, underedge
How do I combine the second set of calculations into the same function as the first. I would like to avoid having to manually input the results of the first function in order to save time and avoid inputting a wrong number.
If you really want the second bit of code in the same function as the first, you could just paste all but the part where you set the over_count and under_count into the function...
def overunder(n):
over_count = 0
under_count = 0
push_count = 0
overodds = 0
underodds = 0
for i in range(n):
if round(np.random.normal(pjTotal3s,pjGame3STD)) > threes_over:
over_count = over_count + 1
if round(np.random.normal(pjTotal3s,pjGame3STD)) < threes_over:
under_count = under_count +1
if round(np.random.normal(pjTotal3s,pjGame3STD)) == threes_over:
push_count = push_count + 1
over = 1/(over_count / float(over_count + under_count))
under = 1/ (under_count / float(over_count + under_count))
over_odds_given = 1.77
under_odds_given = 2.05
overedge = 1/over * over_odds_given - 1
underedge = 1/under * under_odds_given - 1
print overedge, underedge
return over_count, under_count, push_count
Or, probably better, you could put the second bit of code (overedge, underedge) into a separate function and pass it the results from overunder:
def edges(over_count, under_count, push_count):
over = 1/(over_count / float(over_count + under_count))
under = 1/ (under_count / float(over_count + under_count))
over_odds_given = 1.77
under_odds_given = 2.05
overedge = 1/over * over_odds_given - 1
underedge = 1/under * under_odds_given - 1
print overedge, underedge
And then call it with the results from overunder:
c = overunder(100000)
edges(c[0],c[1],c[2])
I'm currently in the process of creating a Snake game and I want to create a food generator that generates an apple every 10 seconds based on my in-game timer. The timer counts down from 60 to 0(when the game ends) and I want an new apple to generate every 10 seconds, keeping the old one even if it hasn't been eaten. I don't know how to approach this and could use some help. Here is my full program.
Edit: this is a beginner Computer Science school project so the more basic the better.
import random
import pygame
pygame.init()
#---------------------------------------#
#
# window properties #
width = 640 #
height = 480
game_window=pygame.display.set_mode((width,height))
black = ( 0, 0, 0) #
#---------------------------------------#
# snake's properties
outline=0
body_size = 9
head_size = 10
apple_size = 8
speed_x = 8
speed_y = 8
dir_x = 0
dir_y = -speed_y
segx = [int(width/2.)]*3
segy = [height, height + speed_y, height + 2*speed_y]
segments = len(segx)
apple_counter = 0
grid_step = 8
regular_font = pygame.font.SysFont("Andina",18)
blue = [11, 90, 220]
clock = pygame.time.Clock()
time = 60
fps = 25
time = time + 1.0/fps
text = regular_font.render("Time from start: "+str(int(time)), 1, blue)
text2 = regular_font.render("Score: "+str(int(apple_counter)), 1, blue)
apple_x = random.randrange(0, 640, grid_step)
apple_y = random.randrange(0, 480, grid_step)
apple_colour = (255,0,0)
def redraw_game_window():
game_window.fill(black)
for i in range(segments):
segment_colour = (random.randint(1,50),random.randint(100,150),random.randint(1,50))
head_colour = (random.randint(180,220),random.randint(180,220),random.randint(1,15))
apple_colour = (255,0,0)
pygame.draw.circle(game_window, segment_colour, (segx[i], segy[i]), body_size, outline)
pygame.draw.circle(game_window, head_colour, (segx[0], segy[0]), head_size, outline)
game_window.blit(text, (530, 20))
game_window.blit(text2, (30, 20))
pygame.draw.circle(game_window, apple_colour, (apple_x, apple_y), apple_size, outline)
pygame.display.update()
exit_flag = False
print "Use the arrows and the space bar."
print "Hit ESC to end the program."
########################################################## TIMER/CONTROLS
while exit_flag == False:
redraw_game_window()
clock.tick(fps)
time = time - 1.00/fps
text = regular_font.render("Time: "+str(int(time)), 1, blue)
text2 = regular_font.render("Score: "+str(int(apple_counter)), 1, blue)
if time < 0.1:
print "Game Over"
exit_flag = True
pygame.event.get()
keys = pygame.key.get_pressed()
if time ==
if keys[pygame.K_ESCAPE]:
exit_flag = True
if keys[pygame.K_LEFT] and dir_x != speed_x:
dir_x = -speed_x
dir_y = 0
if keys[pygame.K_RIGHT] and dir_x != -speed_x:
dir_x = speed_x
dir_y = 0
if keys[pygame.K_UP] and dir_y != speed_x:
dir_x = 0
dir_y = -speed_y
if keys[pygame.K_DOWN] and dir_y != -speed_x:
dir_x = 0
dir_y = speed_y
############################################################ SNAKE MOVEMENT
for i in range(segments-1,0,-1):
segx[i]=segx[i-1]
segy[i]=segy[i-1]
segx[0] = segx[0] + dir_x
segy[0] = segy[0] + dir_y
############################################################ COLLISION
for i in range(segments-1, 3, -1):
if segments > 3:
if segx[0] == segx[i] and segy[0] == segy[i]:
print "You have collided into yourself, Game Over."
exit_flag = True
############################################################# BORDERS
if segx[0] > 640 or segx[0] < 0:
print "Game Over, you left the borders."
break
if segy[0] > 480 or segy[0] < 0:
print "Game Over, you left the borders."
break
############################################################# APPLE DETECT
for i in range (0 , 13):
if segx[0] == apple_x + i and segy[0] == apple_y + i:
segments = segments + 1
segx.append(segx[-1])
segy.append(segy[-1])
apple_counter = apple_counter + 1
if segx[0] == apple_x - i and segy[0] == apple_y - i:
segments = segments + 1
segx.append(segx[-1])
segy.append(segy[-1])
apple_counter = apple_counter + 1
#############################################################
pygame.quit()
You either
A) use pygame.time.set_timer to call a function every 10 seconds to spawn food, and every 60 seconds to end the round.
or
B) compare get_ticks()
def new_round():
last_apple = pygame.time.get_ticks() + 10*1000
while true:
now = pygame.time.get_ticks()
if now - last_apple >= 1000:
spawn_apple()
last_apple = now
if now - round_start >= 60*1000:
round_end()