My code wont print - printing

I don't know why its not printing the number of heads and tails and everything I do it just does the same thing. Nothing!
Can someone please help this is part of an assessment that was due yesterday.
import random
heads = 0
tails = 0
rounds = 0
while rounds < 100:
coin = random.randint(1, 2)
if coin == 1:
heads += 1
rounds += 1
elif coin == 2:
tails += 1
rounds += 1
print("You Flipped Heads {} Times!".format(heads))
print("You Flipped Tails {} Times!".format(tails))

Probably broken indentation causes the while loop to loop :) infinitely.
import random
heads = 0
tails = 0
rounds = 0
while rounds < 100:
coin = random.randint(1, 2)
if coin == 1:
heads += 1
rounds += 1
elif coin == 2:
tails += 1
rounds += 1
print("You Flipped Heads {} Times!".format(heads))
print("You Flipped Tails {} Times!".format(tails))
And here's a working example.

Related

How to make an object move from top to bottom in Lua?

In a game I'm making, there's a square where the game is happening inside. I want the circles that spawn in to start at the top and travel down to the bottom. In the original program, they travel from left to right. How would I go about this? I don't know how to get it to start at the top and travel down instead of starting at the left and traveling to the right.
Here's the original code (I know it's a lot, sorry). I am trying to help a friend.
--Made by Joms or /u/jomy582
--Please credit me if using this in a battle.
spawntimer = 0
timerspawn = 0
storedtime = Time.time
bullets = {}
bulletsbig = {}
bulletswarn = {}
dir = 1
bigheight = {33, 98}
function Update()
spawntimer = spawntimer + (Time.dt*Time.mult)
timerspawn = timerspawn + (Time.dt*Time.mult)
--normal bullets
--change the number in the if statement to make them spawn more frequently/less frequently
--EX: spawntimer > 0.2 spawns them pretty fast
--EX2: spawntimer > 1 spawns them pretty slow
--Make sure to change the subtraction method in the if statement
if spawntimer > 0.16 then
spawntimer = spawntimer-0.16
local bullet = CreateProjectile("bullet", -Arena.width/2, math.random(-Arena.height/2, Arena.height/2))
bullet.SetVar("deadly", true)
table.insert(bullets, bullet)
end
--warning. spawns a warning every 5 seconds
--You could change it, but that may cause some bugs
if timerspawn > 2.2 then
timerspawn = timerspawn-2.2
dir = math.random(1,2)
local bulletwarn = CreateProjectile("warning", 0, Arena.height/2 - bigheight[dir])
bulletwarn.SetVar("warningtimer", 0)
bulletwarn.SetVar("soundtimer", 0)
bulletwarn.SetVar("animtimer", 0)
bulletwarn.SetVar("anim", 1)
table.insert(bulletswarn, bulletwarn)
end
--controlling normal bullets
--a simple method that moves the bullets 1 pixel each frame
--you can change it by editing the bullet.move
--EX: bullet.Move(5*Time.mult, 0) moves the bullets 5 pixels each frame
for i=1, #bullets do
local bullet = bullets[i]
if bullet.isactive then
bullet.Move(2*Time.mult, 0)
if bullet.y > -Arena.height/2 then
bullet.Remove()
end
end
end
--controlling warning timer
--a method that controls the warning timer
for i=1, #bulletswarn do
local bullet = bulletswarn[i]
if bullet.isactive then
local warningtimer = bullet.GetVar("warningtimer") + (Time.mult*Time.dt)
local soundtimer = bullet.GetVar("soundtimer") + (Time.mult*Time.dt)
local animtimer = bullet.GetVar("animtimer") + (Time.mult*Time.dt)
local bulletSprite = bullet.sprite
local anim = bullet.GetVar("anim")
--flashing colors
--change the animtimer > TIME where time is how often you want the warning to blink
--warnings last for 3 seconds. Can change that as well
--to get different colors, find the rgb value of the color you want and insert them below
if animtimer > 0.08 then
animtimer = animtimer-0.08
if anim == 1 then
local r = 0 --put Red value here
local g = 0 --put Green value here
local b = 169 --put Blue value here
bulletSprite.color = {r/255, g/255, b/255} -- changes the color to whatever you'd like. Uses RGB.
bullet.SetVar("anim", 2)
elseif anim == 2 then
local r = 0 --put Red value here
local g = 0 --put Green value here
local b = 255 --put Blue value here
bulletSprite.color = {r/255, g/255, b/255} -- changes the color to whatever you'd like. Uses RGB.
bullet.SetVar("anim", 1)
end
end
--plays a timer evert 10 frames for 3 seconds.
--change the soundname to change the sound
--change the soundtimer > 0.16 to change how often it plays
--can change how long it lasts as well by changing the less than statement
if soundtimer > 0.10 then
soundtimer = soundtimer-0.10
Audio.PlaySound("alarm")
end
--this controls when to spawn the bullets
--change the statement to change how long the warning timer is
if warningtimer > 2 then
warningtimer = warningtimer-2
Audio.PlaySound("shoot")
local bullet1 = CreateProjectile("leftbigbullet", Arena.width/2+30, Arena.height/2 - bigheight[dir]) --where to spawn them
bullet1.SetVar("speed", -4) --how fast
bullet1.SetVar("deadly", true)
local bullet2 = CreateProjectile("rightbigbullet", -Arena.width/2-30, Arena.height/2 - bigheight[dir]) --where to spawn them
bullet2.SetVar("speed", 4) --how fast
bullet2.SetVar("deadly", true)
table.insert(bulletsbig, bullet1)
table.insert(bulletsbig, bullet2)
bullet.Remove()
end
bullet.SetVar("warningtimer", warningtimer)
bullet.SetVar("animtimer", animtimer)
bullet.SetVar("soundtimer", soundtimer)
end
end
--controlling big bullets
--this method controls the big bullets
for i=1, #bulletsbig do
local bullet = bulletsbig[i]
if bullet.isactive then
local speed = bullet.GetVar("speed")
bullet.SendToBottom()
bullet.Move(speed*Time.mult, 0)
if bullet.absx > 700 or bullet.absx < -70 then
bullet.Remove()
end
end
end
end
function OnHit(bullet)
if(bullet.getVar("deadly")) then
Player.Hurt(3)
end
end

Minimum Change Maker Returning Optimal Solution and No Solution

I need Help adding a if clause to my Change Maker, so that if say I have denominations of coins that can't equal the input coin value. For Example I have Coins worth 2,4,6 and I have a Value of 1. I Want it to return Change Not Possible I tried adding a clause to it below but when I test it I get 1.#INF
I also am curious how I can find the optimal coin solution, So on top of saying the minimum number of coins it returns the optimal coin setup if there is one.
function ChangeMaking(D,n)
--[[
//Applies dynamic programming to find the minimum number of coins
//of denominations d1< d2 < . . . < dm where d1 = 1 that add up to a
//given amount n
//Input: Positive integer n and array D[1..m] of increasing positive
// integers indicating the coin denominations where D[1]= 1
//Output: The minimum number of coins that add up to n
]]
F = {} -- F is List Array of Coins
m = tablelength(D)
F[0] = 0
for i =1,n do
temp = math.huge
j = 1
while j <= m and i >= D[j] do
temp = math.min(F[ i - D[j] ], temp)
j = j + 1
end
F[i] = temp + 1
end
--I wanted to Catch the failed Solution here but I return 1.#INF instead
--if F[n] <= 0 and F[n] == 1.#INF then print("No Change Possible") return end
return F[n]
end
function main()
--[[
//Prints a Greeting, Asks for Denominations separated by spaces.
// Iterates through the input and assigns values to table
// Table is then input into ChangeMaker, and a while loop takes an n value for user input.
// User Enters 0 to end the Loop
]]
io.write("Hello Welcome the to Change Maker - LUA Edition\nEnter a series of change denominations, separated by spaces: ")
input = io.read()
deno = {}
for num in input:gmatch("%d+") do table.insert(deno,tonumber(num)) end
local i = 1
while i ~= 0 do
io.write("Please Enter Total for Change Maker, When Finished Enter 0 to Exit: ")
input2 = io.read("*n")
if input2 ~= 0 then io.write("\nMinimum # of Coins: " .. ChangeMaking(deno,input2).."\n") end
if input2 == 0 then i=0 print("0 Entered, Exiting Change Maker") end
end
end
function tablelength(T)
--[[
//Function for grabbing the total length of a table.
]]
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
main()

Diagonal movement causing tilemap painting flaws

I was able to make a good assembly of what is happening and killing me for weeks, and I really wanted to know if it was my mistake or just the keys pressed too fast, or the rendering delayed? to deal with the problem, because I'm not finding the culprit for doing so.
This happens when for example I go from diagonal down-rigth to left, and right, then I go back down, I make moves like that, fast, it does not always happen, but enough to disrupt the game.
Movement Script:
extends KinematicBody2D
var velocity = 150
var direction = Vector2()
func _ready():
set_fixed_process(true)
func _fixed_process(delta):
#-----------MOVIMENT-------------------------------
direction = Vector2()
#LEFT
if Input.is_action_pressed("left"):
direction += Vector2(-1, 0)
#RIGHT
elif Input.is_action_pressed("right"):
direction += Vector2(1, 0)
#UṔ
if Input.is_action_pressed("up"):
direction += Vector2(0, -1)
#DOWN
elif Input.is_action_pressed("down"):
direction += Vector2(0, 1)
if direction.x != 0 || direction.y != 0:
direction = direction.normalized()*velocity
move(direction*delta)
Paint Script:
extends Control
var map_size = 64
var preScriptUtils = preload("res://scripts/utils_fuctions.gd")
var utils_functions
onready var player = $"../Player"
onready var tile_map = $"../TileMap"
var posTileMap = Vector2()
var posWorld = Vector2()
var prevRect = Rect2()
var newRect = Rect2()
var distance_gen = 2048
var positionMap_rect = 0
var size_rectMap = 0
func _ready():
utils_functions = preScriptUtils.utils_functions.new()
set_fixed_process(true)
posWorld = Vector2(0, 0)
positionMap_rect = ((distance_gen/32)/2)
size_rectMap = distance_gen/32
surround_map(posWorld)
func _fixed_process(delta):
var posPlayer = player.get_position()
posTileMap = tile_map.world_to_map(posPlayer) - Vector2(positionMap_rect, positionMap_rect)
newRect = Rect2(tile_map.map_to_world(posTileMap), Vector2(distance_gen, distance_gen))
if prevRect.position != newRect.position:
load_newMap()
func gen_data(var _posWorld=Vector2(0, 0), var _posTileMap=Vector2(0, 0), var size=Vector2(0, 0)):
var x = 0
var y = 0
var pos_modx = 0
var pos_mody = 0
while x < size.x:
y = 0
pos_modx = utils_functions.mod(_posWorld.x + x, map_size)
#NOISE
var result_noise
while y < size.y:
pos_mody = utils_functions.mod(_posWorld.y + y, map_size)
if (pos_modx >= 0 && pos_mody >= 0) && (pos_modx < map_size && pos_mody < map_size):
tile_map.set_cell(_posTileMap.x + x, _posTileMap.y + y, biomes(result_noise))
y += 1
x += 1
func load_newMap():
var rectIntersection = newRect.clip(prevRect)
var _x = 0
var _y = 0
#LEFT
if player.direction.x < 0:
if int((newRect.size.x - rectIntersection.size.x)/32) == 1:
_x = int(newRect.position.x/32)
_y = int(rectIntersection.position.y/32)
posWorld.x -= 1
gen_data(Vector2(posWorld.x, posWorld.y), Vector2(_x, _y), Vector2(1, size_rectMap))
#RIGHT
elif player.direction.x > 0:
if int((newRect.size.x - rectIntersection.size.x)/32) == 1:
_x = int(rectIntersection.end.x/32)
_y = int(rectIntersection.position.y/32)
posWorld.x += 1
Vector2(_x, _y)
gen_data(Vector2(posWorld.x - 1, posWorld.y), Vector2(_x, _y), Vector2(1, size_rectMap))
#UP
if player.direction.y < 0:
if int((newRect.size.y - rectIntersection.size.y)/32) == 1:
_x = int(newRect.position.x/32)
_y = int(newRect.position.y/32)
posWorld.y -= 1
gen_data(Vector2(posWorld.x, posWorld.y), Vector2(_x, _y), Vector2(size_rectMap, 1))
#DOWN
elif player.direction.y > 0:
if int((newRect.size.y - rectIntersection.size.y)/32) == 1:
_x = int(rectIntersection.position.x/32)
_y = int(rectIntersection.end.y/32)
posWorld.y += 1
gen_data(Vector2(posWorld.x, posWorld.y - 1), Vector2(_x, _y), Vector2(size_rectMap, 1))
prevRect = newRect
func surround_map(var _posWorld=Vector2(0, 0)):
posTileMap = - Vector2(positionMap_rect, positionMap_rect)
prevRect = Rect2(tile_map.map_to_world(posTileMap), Vector2(distance_gen, distance_gen))
gen_data(_posWorld, Vector2(-32, -32), Vector2(64, 64))
Do not be fussed with the codes, it's very simple what I'm trying to do, I want to move the player while I generate my world, it works perfectly in the 4 directions, but when it involves the diagonals, it does not go as expected. I'm painting like this, I have two rects that I compare to each frame, I take the retagunlo of the interception and calculate where I should paint or erase.
Video of what is happening:
http://www.dailymotion.com/video/x6286px
But there are these flaws not only by pressing too fast, it also happens in slow motion, while being diagonally down-right and then left or left-right and then back to right, moving on the diagonals seems to be the problem, I've tried a lot of shapes, I have almost a notebook all scribble trying to figure this out, I tried with diagonal checks too and I get the same result, today I lost another day, and it does not leave the place, I'm weeks like this, when I think I fixed it, not really.
I'm using godot.
Up 1:
With #Ryan1729 response I realized that I was really thinking the wrong way, but I try to fix my logic by doing something like below and the error continues, I'm confused:
if direction.x != 0 || direction.y != 0:
var vetor_normalized = direction.normalized()
if abs(vetor_normalized.x) < 1 && abs(vetor_normalized.y) < 1:
var vx = Vector2(direction.x, 0)
var vy = Vector2(0, direction.y)
vx = vx.normalized()*velocity
move(vx*delta)
vy = vy.normalized()*velocity
move(vy*delta)
else:
direction = direction.normalized()*velocity
move(direction*delta)
Up2:
Now I have done so, it seems that solved the flaws, but others appeared, which I still do not understand, this issue of 0 confuses me too much.
var oldPosWorld = Vector2(0, 0)
var rect_tileMap = Vector2(-32, -32)
func load_newMap():
var posPlayer = Vector2(int(player.get_position().x/32), int(player.get_position().y/32))
#LEFT
if posPlayer.x < oldPosWorld.x:
pos_tileMap.x -= 1
posWorld.x -= 1
gen_data(Vector2(posWorld.x, posWorld.y), Vector2(pos_tileMap.x, pos_tileMap.y), Vector2(1, size_rectMap))
#RIGHT
elif posPlayer.x > oldPosWorld.x:
pos_tileMap.x += 1
posWorld.x += 1
gen_data(Vector2(posWorld.x - 1, posWorld.y), Vector2(pos_tileMap.x + 63, pos_tileMap.y), Vector2(1, size_rectMap))
#UP
if posPlayer.y < oldPosWorld.y:
pos_tileMap.y -= 1
posWorld.y -= 1
gen_data(Vector2(posWorld.x, posWorld.y), Vector2(pos_tileMap.x, pos_tileMap.y), Vector2(size_rectMap, 1))
#DOWN
elif posPlayer.y > oldPosWorld.y:
pos_tileMap.y += 1
posWorld.y += 1
gen_data(Vector2(posWorld.x, posWorld.y - 1), Vector2(pos_tileMap.x, pos_tileMap.y + 63), Vector2(size_rectMap, 1))
oldPosWorld = posPlayer
The movements of the right and bottom are right, the problem is those of the left and above that is left over this empty space(ie dealing with the negatives
).
If I put x - 1 on the left to solve the problem, this happens to me:
I solved this by changing:
var posPlayer = Vector2(int(player.get_position().x/32), int(player.get_position().y/32))
by checks like this:
if ((player.get_position().x)/32)
but now I get this by going to the sides and then up:
Up 3:
I'm not going to put my mind to it, so as not to get frustrated if I'm mistaken, but by the tests I did the failure stopped. The code would look like this by assigning int (player.get_position (). X / 32) separately to oldPosWorld.x, this respectively for y as well, since before I was assigning the position to the player only once the postPlayer variable, this caused errors , when you entered the up-down if, as it was still with the previous position of x, doing so updates everything in its right time.
is still so to the left and up:
I do not quite understand why, and frankly not so soon will I know, I'm too tired to look at it. But I'd like to understand not to err. Apart from this it seems to be happening now as expected.
#LEFT
if int(player.get_position().x/32) < oldPosWorld.x:
rect_tileMap.x -= 1
posWorld.x -= 1
gen_data(Vector2(posWorld.x, posWorld.y), Vector2(rect_tileMap.x, rect_tileMap.y), Vector2(1, size_rectMap))
oldPosWorld.x = int(player.get_position().x/32)
I think that the problem is that you want discrete movement (moving up and right moves 1 up and 1 right) but you're normalizing the vector to length 1 in the first code snippet. In the non-diagonal cases this does nothing because the vectors are length 1 already. But in the diagonal cases the vector is length sqrt(2) before normalization, (you can use the Pythagorean theorem to show this.) So your vector is getting shrunk down to something like Vector2(sqrt(2)/2, sqrt(2)/2)), (sqrt(2)/2 is about 0.707,) which causes the painting offset.
Edit: My best guess now is that the problem is that you are calling gen_data twice when the player moves diagonally. I think you want to figure out the x and y offsets then redraw the map.
Summarizing the error was in the update(which in the case would be oldPosWorld), because they were two blocks of ifs, I would enter one after another, and without updating the position, paints the wrong way because it is in a late position:
Video working:
http://www.dailymotion.com/video/x62e6l9

How to count the number of repetitions for every single number?

So I have a for loop that loops 100 times and each time it generates a random number from 1 to 100. For some statistics, I need to count how many times each number repeats. I have no idea how to make it other than manually.
One = 0
Two = 0
Three = 0
Four = 0
Five = 0
for i=1, 100 do
number = GetRandomNumber(1, 5, 1.5)
if number == 1 then
One = One + 1
elseif number == 2 then
Two = Two + 1
elseif number == 3 then
Three = Three + 1
elseif number == 4 then
Four = Four + 1
elseif number == 5 then
Five = Five + 1
end
end
This is how I currently count, but I don't want to manually type for every number. How can I make this simpler?
I do it as such:
number_counter, number = {}, 0
for i = 1, 100 do
number = GetRandomNumber(1, 5, 1.5)
if number_counter[number] then
number_counter[number] = number_counter[number] + 1
else
number_counter[number] = 1
end
end
This is, of course, assuming there are no half points (not sure what the 1.5 is for). Then you can just call number_counter[#] to see what its value is.

Corona: How to detect the direction of an object with physics

I would like to know how to detect the direction of an object with physics, I mean when is falling down. can it be by a eventListener? any idea how to do it?
I need it for know can I change the spriteSheet.
Thanks.
To find the exact angle based on an objects velocity you'd call:
local angle = atan2(xVelocity, yVelocity)
This returns the angle in radians, which you can then convert to degrees. This allows for more precise control over the object. Daniel Shiffman wrote a great book involving many aspects of physics simulation over at http://natureofcode.com/book/.
Try this :
local xVelocity, yVelocity
local upDown, leftRight -- upDown = 1 for up, leftRight = 1 for left
....
-- Get speed of physics object here ( Assume normal orientation ---
xVelocity, yVelocity = physicsObject:getLinearVelocity()
if xVelocity > 0 then
print( "Object goes right" )
leftRight = 0
end
if xVelocity < 0 then
print( "Object goes left" )
leftRight = 1
end
if yVelocity > 0 then
print( "Object goes down" )
upDown = 0
end
if yVelocity < 0 then
print( "Object goes up" )
upDown = 1
end
-----------------------------------

Resources