Basic Tally and Tracking - tally

Hi thank you to anyone looking, I'm new in a beginners class. I have a game where a dealer and a player each guess a number and a random number is generated. Whoever is closest wins the round. After 5 rounds print("Dealer wins: Player wins: ") and the number of rounds won will populate in that print statement. If dealer tallied 3-5 wins print("Sorry Try Again") if player tallied 3-5 wins print("Congrats you win") I have have it looped but not set to end after five rounds and then can't figure out the tally which counts the rounds and prints the results.
while True:
player = int(input("Guess a Number:"))
print(player)
dealer = int(input("Dealer Guess:"))
print(dealer)
import random
num1 = random.randint(0, 100)
print("Random Number:")
print(num1)
playerdist = abs(player - num1)
dealerdist = abs(dealer - num1)
if (playerdist > dealerdist):
print("Dealer Wins")
if (playerdist < dealerdist):
print("Player Wins")
if (playerdist == dealerdist):
print("Draw")

Maybe you can add a iterator to count the rounds, if the rounds reached 5, then exits.
for i in 5:
# rest of the codes

Related

Micro:bit - Accelerometer - (Micro python) make microbit count downward movements - only works with gestures

The following code works just fine:
# Add your Python code here. E.g.
from microbit import *
score = 0
display.show(str(score))
while True:
if accelerometer.was_gesture('face down'):
score += 1
if score < 10:
display.show(score)
else:
display.scroll(score)
continue
'''But when I try to replace was_gesture('face down') with get_Z i get an error:'''
# Add your Python code here. E.g.
from microbit import *
score = 0
display.show(str(score))
z = accelerometer.get_z()
while True:
if z < accelerometer.get_z(-500)
score += 1
if score < 10:
display.show(score)
else:
display.scroll(score)
continue
I get an error? But why? I just want to get the microbit to count every time I move the device below a certain point?
The accelerometer.get_z() statement needs to be inside the while loop so that it is updated. The loop also needs a sleep statement so that there is not a backlog of detections to display.
I tested the code below on a micro:bit using the mu editor. When the microbit is LED side up, the count increments. When it is face down, the count stops.
from microbit import *
uart.init(baudrate=115200)
score = 0
display.show(str(score))
while True:
z = accelerometer.get_z()
if z < -500:
score += 1
if score < 10:
display.show(score)
else:
display.scroll(score)
sleep(1000)
continue
You've missed a colon at the end of this line:
if z < accelerometer.get_z(-500)
Also, the get_z() method doesn't take any arguments:
https://microbit-micropython.readthedocs.io/en/latest/accelerometer.html#microbit.accelerometer.get_z

Adding a new name/item to a list and calling that variable globally?

I'm pretty much brand new to coding and decided to start with Python. I have been working on a simple "Number Guessing Game" and have evolved it a bit more each iteration.
I decided that I want to make it a little bit more robust that just finishing after the number is guessed.
I want the user/player to enter their name, have that name stored, and then used throughout... until the end, when they're asked if they want to play again and if it's the 'same user?" and if they say, "No.", I want it to append a new name to the list and then go through the game again.
This is what I've got so far... please be gentle... I know there's some errors :(
import sys
import os
import random
global player
while True:
def GuessingGame():
player = []
player.append(input("Please Enter Your Name:\n")),
# player_name = input("Please enter your name: \n")
print(f"Hello, {player[0]}! Let's get started!\n")
number = 500
count = 1
guess = int(input("Guess a number between 1 and 1000: \n"))
while guess != number:
count += 1
if guess > (number + 10):
print("TOO HIGH, a little lower...")
elif guess < (number - 10):
print("TOO LOW... guess higher!")
elif guess > (number + 5):
print("You're getting warmer, but still TOO HIGH, a little lower...")
elif guess < (number - 5):
print("You're getting warmer, but still TOO LOW... higher!")
elif guess < number:
print("You're REALLY warm, but still a bit TOO LOW")
elif guess > number:
print("You're REALLY, but still a bit TOO HIGH")
guess = int(input("Try again...\n"))
if guess == number:
print(f"You got it!!! It took you {count} tries to guess {number}\n")
response1 = str(input("Would you like to try again? Y or N\n"))
if response1 == ("y" or "Y"):
sameplayer = str(input("Is this still {player[0]}? Y1 or N1\n"))
if sameplayer == ("y1" or "Y1"):
GuessingGame()
else:
newplayer = player.extend(str(input("Please Enter New Player's Name:\n")))
print(f"Hello, {player[1]}!, Let's Get Started!")
return
GuessingGame()
Again, this is the first time I'm sharing anything I've done... so please don't just wreck me :)
Here i copy the same code you wrote, but with a little bit of modifications that i felt were needed to be made.
from random import randint
player = None
def GuessingGame():
global player
if player is None:
player = input("Please Enter Your Name:\n")
print(f"Hello, {player}! Let's get started!\n")
number = randint(1, 1000)
guess = int(input("Guess a number between 1 and 1000: \n"))
count = 1
while guess != number:
if guess > (number + 10):
print("TOO HIGH, a little lower...")
elif guess < (number - 10):
print("TOO LOW... guess higher!")
elif guess > (number + 5):
print("You're getting warmer, but still TOO HIGH, a little lower...")
elif guess < (number - 5):
print("You're getting warmer, but still TOO LOW... higher!")
elif guess < number:
print("You're REALLY warm, but still a bit TOO LOW")
elif guess > number:
print("You're REALLY, but still a bit TOO HIGH")
if guess == number:
break
else:
count += 1
guess = int(input("Try again...\n"))
print(f"You got it!!! It took you {count} tries to guess {number}\n")
response1 = str(input("Would you like to try again? Y or N\n"))
if response1.lower() == 'y':
sameplayer = str(input(f"Is this still {player}? Y or N\n"))
if sameplayer.lower() == 'n':
player = None
return
else:
return
while True:
GuessingGame()
Let me know if you got any questions.

Relative Strength Index in Swift

I am trying to code an RSI (which has been a good way for me to learn API data fetching and algorithms already).
The API I am fetching data from comes from a reputable exchange so I know the values my algorithm is analyzing are correct, that's a good start.
The issue I'm having is that the result of my calculations are completely off from what I can read on that particular exchange and which also provides an RSI indicator (I assume they analyze their own data, so the same data as I have).
I used the exact same API to translate the Ichimoku indicator into code and this time everything is correct! I believe my RSI calculations might be wrong somehow but I've checked and re-checked many times.
I also have a "literal" version of the code where every step is calculated like an excel sheet. It's pretty stupid in code but it validates the logic of the calculation and the results are the same as the following code.
Here is my code to calculate the RSI :
let period = 14
// Upward Movements and Downward Movements
var upwardMovements : [Double] = []
var downwardMovements : [Double] = []
for idx in 0..<15 {
let diff = items[idx + 1].close - items[idx].close
upwardMovements.append(max(diff, 0))
downwardMovements.append(max(-diff, 0))
}
// Average Upward Movements and Average Downward Movements
let averageUpwardMovement1 = upwardMovements[0..<period].reduce(0, +) / Double(period)
let averageDownwardMovement1 = downwardMovements[0..<period].reduce(0, +) / Double(period)
let averageUpwardMovement2 = (averageUpwardMovement1 * Double(period - 1) + upwardMovements[period]) / Double(period)
let averageDownwardMovement2 = (averageDownwardMovement1 * Double(period - 1) + downwardMovements[period]) / Double(period)
// Relative Strength
let relativeStrength1 = averageUpwardMovement1 / averageDownwardMovement1
let relativeStrength2 = averageUpwardMovement2 / averageDownwardMovement2
// Relative Strength Index
let rSI1 = 100 - (100 / (relativeStrength1 + 1))
let rSI2 = 100 - (100 / (relativeStrength2 + 1))
// Relative Strength Index Average
let relativeStrengthAverage = (rSI1 + rSI2) / 2
BitcoinRelativeStrengthIndex.bitcoinRSI = relativeStrengthAverage
Readings at 3:23pm this afternoon give 73.93 for my algorithm and 18.74 on the exchange. As the markets are crashing right now and I have access to different RSIs on different exchanges, they all display an RSI below 20 so my calculations are off.
Do you guys have any idea?
I am answering this 2 years later, but hopefully it helps someone.
RSI gets more precise the more data points you feed into it. For a default RSI period of 14, you should have at least 200 previous data points. The more, the better!
Let's suppose you have an array of close candle prices for a given market. The following function will return RSI values for each candle. You should always ignore the first data points, since they are not precise enough or the number of candles is not the 14 (or whatever your periods number is).
func computeRSI(on prices: [Double], periods: Int = 14, minimumPoints: Int = 200) -> [Double] {
precondition(periods > 1 && minimumPoints > periods && prices.count >= minimumPoints)
return Array(unsafeUninitializedCapacity: prices.count) { (buffer, count) in
buffer.initialize(repeating: 50)
var (previousPrice, gain, loss) = (prices[0], 0.0, 0.0)
for p in stride(from: 1, through: periods, by: 1) {
let price = prices[p]
let value = price - previousPrice
if value > 0 {
gain += value
} else {
loss -= value
}
previousPrice = price
}
let (numPeriods, numPeriodsMinusOne) = (Double(periods), Double(periods &- 1))
var avg = (gain: gain / numPeriods, loss: loss /numPeriods)
buffer[periods] = (avg.loss > .zero) ? 100 - 100 / (1 + avg.gain/avg.loss) : 100
for p in stride(from: periods &+ 1, to: prices.count, by: 1) {
let price = prices[p]
avg.gain *= numPeriodsMinusOne
avg.loss *= numPeriodsMinusOne
let value = price - previousPrice
if value > 0 {
avg.gain += value
} else {
avg.loss -= value
}
avg.gain /= numPeriods
avg.loss /= numPeriods
if avgLoss > .zero {
buffer[p] = 100 - 100 / (1 + avg.gain/avg.loss)
} else {
buffer[p] = 100
}
previousPrice = price
}
count = prices.count
}
}
Please note that the code is very imperative to reduce the amount of operations/loops and get the maximum compiler optimizations. You might be able to squeeze more performance using the Accelerate framework, though. We are also handling the edge case where you might get all gains or losses in a periods range.
If you want to have a running RSI calculation. Just store the last RSI value and perform the RSI equation for the new price.

Scala dice program

I've just started Scala at University and we're currently just doing the basics but I'm moved ahead and want to try making some basic programs to get ahead. I'm currently trying to make a basic dice role guessing program.
I want to add in a feature to replay the game, the counter is to tell the user how many attempts to guess. I know I can add it in somewhere with counter += 1 just not sure where in the program to put it.
Currently compiling does nothing until I input something and I'm unsure why, then when I input something I don't get any results from the if statements it just terminates the program.
import scala.io.StdIn.readInt
import scala.util.Random
object GuessTheNumber {
def main(args: Array[String]): Unit = {
var play = true
var counter = 0 //Allows counting input
var responseGuess = readInt()
val numRange = Random.nextInt(12)
println("Enter your guess of the result of 2, 6 sided dice.")
while(play) {
if (responseGuess == numRange)
println ("You got it right!")
else if (numRange < responseGuess)
("Your guess was too large by" + (responseGuess - numRange) + " the corrrect answer was " + numRange)
else if (numRange > responseGuess)
( "Your guess was too small by" + (numRange - responseGuess) + " the correct answer was " + numRange)
else if (responseGuess < 1)
("Your guess is too small enter 2-12")
else if (responseGuess > 12)
("You entered an invalid number, 2 dice can only equate to a maximum of 12")
}
}
}
A couple things:
You should ask for a guess (the println) before you go get it from the input
All of your else if blocks were missing println statements
You aren't using your counter
Your numRange is incorrect, right now it would return 0 to 11 inclusive
I made those changes, and moved the readInt() inside the while loop to give people multiple chances to guess, once they guess the answer then the loop exited.
var play = true
val numRange = 2 + Random.nextInt(11)
while(play) {
println("Enter your guess of the result of 2, 6 sided dice.")
var responseGuess = readInt()
if (responseGuess == numRange) {
println ("You got it right!")
play = false
}
else if (numRange < responseGuess)
println("Your guess was too large")
else if (numRange > responseGuess)
println( "Your guess was too small")
else if (responseGuess < 2)
println("Your guess is too small enter 2-12")
else if (responseGuess > 12)
println("You entered an invalid number, 2 dice can only equate to a maximum of 12")
}
You can build off of this to get the functionality you need.
You had a few basic errors, but, a really good first attempt. I have included most of the comments in context for clarity. Here is a quick summary of some of the things that needed minor corrections
You forgot to include println in every else clause
You didn't reset the value of play variable causing your program to be stuck in an infinite loop. The while loop kept executing without asking user for any input giving the illusion that nothing was printing
The counter needs to be updated after every attempt within the loop
import scala.io.StdIn.readInt
import scala.io.StdIn.readChar
import scala.util.Random
object GuessTheNumber {
def main(args: Array[String]): Unit = {
var play = true
var counter = 1 //Allows counting input
// Start a loop. As long as the user says he wants to continue, we keep entering the loop
while (play) {
// The game is slightly more clear in my humble opinion if you ask him/her this question after every attempt.
// Otherwise you just have a blinking cursor on screen, without prompting user for input
println("Enter your guess of the result of 2, 6 sided dice.")
// Read his current response
val responseGuess = readInt()
// If you don't have `1 +`, then, 0 could be a potential result
val numRange = 2 + Random.nextInt(11)
if (responseGuess == numRange)
println(s"You got it right! in $counter attempts")
// You were missing println in each of the following cases. Hence the lack of response from your program, since,
// it didn't know you wanted it to print that response
else if (numRange < responseGuess)
println("Your guess was too large by " + (responseGuess - numRange) + " the correct answer was " + numRange)
else if (numRange > responseGuess)
println( "Your guess was too small by " + (numRange - responseGuess) + " the correct answer was " + numRange)
else if (responseGuess < 1)
println("Your guess is too small enter 2-12")
else if (responseGuess > 12)
println("You entered an invalid number, 2 dice can only equate to a maximum of 12")
println("Do you want to continue? (Y/N)")
// Now you are reading a character instead of an integer. Basically a Y or an N
play = readChar() match { // Not sure if you have gotten this far in your course. This syntax is referred to as pattern matching.
// Its basically the same as using if / else
case 'Y' | 'y' => true // If he enters Y or y, we assume he wants to continue.
case _ => // For any other input we abort
println(s"You tried $counter times") // When he does decide to quit, lets tell him how many times he tried
false
}
// After every attempt increment counter within your loop
counter += 1
}
}
}
Hope this helps.

Why does SKLabelNode increment too much on Contact? (Swift)

I am trying to have my Label to increment +1 every time a sprite makes contact with a Contact node, but it increments by large numbers like +23. I think what is happening is that its taking into account every millisecond that the sprite is touching the node, but i don't know how to fix it.
Here is my Label node code within DidMoveToView:
score = 0
scoreLabelNode = SKLabelNode(fontNamed:"[z] Arista Light")
scoreLabelNode.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/4)
scoreLabelNode.zPosition = 100
scoreLabelNode.fontSize = 500
scoreLabelNode.alpha = 0.03
scoreLabelNode.text = String(score)
self.addChild(scoreLabelNode)
here is my contact node:
var contactNode = SKNode()
contactNode.position = CGPoint(x: self.frame.size.width + asteroidTexture.size().height / 15 + rocket.size.width, y: 0.0)
contactNode.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake( asteroid.size.width/16, self.frame.size.height*2 ))
contactNode.physicsBody?.dynamic = false
contactNode.physicsBody?.categoryBitMask = scoreCategory
contactNode.physicsBody?.contactTestBitMask = rocketCategory
contactNode.runAction(asteroidsMoveAndRemove)
moving.addChild(contactNode)
and here is my code where when my rocket sprite makes contact with the contactNode it increments:
func didBeginContact(contact: SKPhysicsContact) {
if moving.speed > 0 {
if ( contact.bodyA.categoryBitMask & scoreCategory ) == scoreCategory || ( contact.bodyB.categoryBitMask & scoreCategory ) == scoreCategory {
// Rocket has contact with score entity
score++
scoreLabelNode.text = String(score)
println("HIT")
}
else{
gameOver()
}
}
'moving' is when my asteroid sprites are moving, the contact nodes move with it
It's probably not every millisecond, but instead every frame, and that's why you likely end up with numbers like +23 (The collision is taking place for a 1/3 of a second and if it's running at 60 FPS that is about 20 or so frames).
One thing you could do is subclass SKNode into an actual ContactNode class that has a property hasBeenStruck that is initially set to false or something to that extent.
Then when you check contact, you first check to see if hasBeenStruck is false. If it is, register the hit and update the score and then set that ContactNode's hasBeenStruck property to true. This way, on the next 20 or so checks to see if contact has happened, it won't keep updating the label because the if condition has failed.
However, if your game allows a user to hit the same ContactNode twice and get score both times, this isn't a complete solution. If that is the case, you could use a timer or "invincibility" period for the given ContactNode.