Here I am trying to devolope a game.
Anyone please explain why boolean value of the variable win is not updating if Board value changes
Here is the code..
Board = {'1':'1','2':'6','3':'7',
'4':'2','5':'5','6':'8',
'7':'3','8':'4','9':'9'}
Win = Board['1'] == Board['2']== Board['3']=='X' or Board['4'] == Board['5'] == Board['6'] or Board['7'] == Board['8'] == Board['9'] or Board['1'] == Board['5'] == Board['9'] or Board['3'] == Board['5'] == Board['7'] or Board['1'] == Board['4'] == Board['7'] or Board['2'] == Board['5'] == Board['8'] or Board['3'] == Board['6'] == Board['9']
turn = 'X'
print(Win)
for i in range(9):
a = str(input('Enter choice {}: '.format(turn)))
Board[a] = turn
turn = 'Y' if turn == 'X' else 'X'
if Win: #Here I am expecting Win to be True but it is actually False
print('Win')
Please help me out with this.
You have one static boolean value that is unmodified as you "play the game"
Instead, define a function that inspects the state of the board
def isWin(board):
return board['1'] == board['2']== board['3']=='X' or ...
Then use that within the game loop
Board[a] = turn
turn = 'Y' if turn == 'X' else 'X'
if isWin(Board):
...
break # stop the game
Related
I had a script somewhat similar like in this video:
extends KinematicBody2D
var movement=Vector2();
var up= Vector2(0, -1);
var speed=200;
var isAttacking=false;
func _process(delta):
if Input.is_action_pressed("ui_right") && isAttacking == false:
movement.x = speed;
$AnimatedSprite.play("walk");
elif Input.is_action_pressed("ui_left") && isAttacking == false:
movement.x= -speed;
$AnimatedSprite.play("Walk");
else:
movement.x = 0;
if isAttacking == false:
$AnimatedSprite.play("Idle");
if Input.is_action_just_pressed("Attack"):
$AnimatedSprite.play("Slash");
isAttacking=true;
movement = move_and_slide(movement, up * delta);
func _on_AnimatedSprite_animation_finished():
if $AnimatedSprite.animation == "Slash":
isAttacking= false;
but the problem was when I was rapidly pressing attack & movement on my keyboard
sometimes the isAttacking did not get set back to false after the animation was completed and hence froze my character animation
Maybe it was a bug in invoking the connected signal function when pressed rapidly? but anyhow it gave me a nightmare
so I came up with this workaround for rapid key pressing attack and movements (check the solutions) so no one else has to go through what I did :)
Instead of checking for attack in _process() I used _unhandled_key_input() and this seemed to get rid of the problem
Hope this helps! :D
...
func _process(delta):
if Input.is_action_pressed("ui_right") && isAttacking == false:
movement.x = speed;
$AnimatedSprite.play("walk");
elif Input.is_action_pressed("ui_left") && isAttacking == false:
movement.x= -speed;
$AnimatedSprite.play("Walk");
else:
movement.x = 0;
if isAttacking == false:
$AnimatedSprite.play("Idle");
if Input.is_action_just_pressed("Attack"):
$AnimatedSprite.play("Slash");
isAttacking=true;
movement = move_and_slide(movement, up * delta);
func attack_animation_finished(var _extra):
isAttacking=false
func _unhandled_key_input(event):
if(event.echo):
return
if(!event.pressed):
return
if(event.scancode==KEY_X and !isAttacking): # x key to attack (you can use whatever you like)
isAttacking=true
if!($AnimatedSprite.is_connected("animation_finished",self,"attack_animation_finished")):
$AnimatedSprite.connect("animation_finished", self, "attack_animation_finished", [], CONNECT_ONESHOT) # warning-ignore:return_value_discarded
$AnimatedSprite.play("Slash");
Note: I haven't ran this particular code segment but I have used this logic/approach in a working larger script which would be too long to share here
I wanna know how to ask user input for a string. For example:
when user input is asked "lruud" is entered
Enter letters: lruud
and I want it the return should be:
Left
right
up
up
down
left = l, right = r, etc.
So basically it should return the result in the order the letters are entered.
The code below is what I have tried where al() is move left, ar() is move right etc
def move(s: String) {
if(s == "l"){
al()
}else if(s == "r"){
ar()
}else if(s == "u"){
au()
}else if(s == "d"){
ad()
}
}
You can read in a string from standard input using
val s = scala.io.StdIn.readLine()
Scala implicitly considers String to be a Scala collection, in particular an IndexedSeq which means you can call standard collections methods on it such as map to transform it. For example
def move(s: Char): String = {
if (s == 'l') "left"
else if (s == 'r') "right"
else if (s == 'u') "up"
else if (s == 'd') "down"
else throw new RuntimeException("Bad input")
}
"lruud".map(move)
// res4: IndexedSeq[String] = ArraySeq(left, right, up, up, down)
Mapping over a String reads each Char in the string and passes it to the move method for transformation.
Here's one way to go about this.
val action :Map[Char,String] =
Map('d'->"down",'l'->"left",'r'->"right",'u'->"up")
.withDefault(c => s"$c?")
val moves :Seq[String] =
io.StdIn.readLine("Enter letters: ").map(c =>action(c.toLower))
println("\ndirections:\n" + moves.mkString(" ","\n ",""))
testing:
Enter letters: lLdRbu
directions:
left
left
down
right
b?
up
I'm trying to make a calculator in Haxe, it is almost done but have a bug. The bug is happening every time that some part of the equation result in 0.
This is how I concatenate the numbers and put i the array number, the cn is the variable used to receive the digit and transform in a number, the ci is a specific counter to make the while work well and the c is the basic counter that is increased to a background while used to read the array (input) items:
var cn = '';
var ci = c;
if (input[c] == '-') {
number.push('+');
cn = '-';
ci ++;
}
while (input[ci] == '0' || input[ci] == '1' || input[ci] == '2' || input[ci] == '3' || input[ci] == '4' || input[ci] == '5' || input[ci] == '6' || input[ci] == '7' || input[ci] == '8' || input[ci] == '9' || input[ci] == '.') {
if(ci == input.length) {
break;
}
cn += input[ci];
ci++;
}
number.push(cn);
c += cn.length;
This is the part of the code used to calculate the addition and subtraction
for (i in 0 ... number.length) { trace(number); if (number[c] == '+') { number[c-1] = ''+(Std.parseFloat(number[c-1])+Std.parseFloat(number[c+1])); number.remove(number[c+1]); number.remove(number[c]); }
else {
c++;
}
}
Example:
12+13-25+1: When my code read this input, it transform in a array ([1,2,+,1,3,-,2,5,+,1]), then the code concatenate the numbers ([12,+,13,-,25,+,1]) and for lastly it seeks for the operators(+,-,* and /) to make the operation (ex: 12+13), substituting "12" for the result of the operation (25) and removing the "+" and the "13". This part works well and then the code does 25-25=0.
The problem starts here because the equation then becomes 0+1 and when the code process that what repend is that the 0 vanish and the 1 is removed and the output is "+" when the expected is "1".
remove in this case uses indexOf and is not ideal, suggest using splice instead.
number.splice(c,1);
number.splice(c,1);
https://try.haxe.org/#D3E38
I have this block of code inside of a class. No matter what data I pass into the class, this will always return "Loss".
def win_loss_unadj(self):
if self.side == "Long" and (self.getMAE > self.getStop) and (self.getMFE >= self.unadj_T2):
return "T2_Win"
elif self.side == "Long" and (self.getMAE > self.getStop) and (self.getMFE >= self.unadj_T1):
return "Win"
elif self.side == "Short" and (self.getMAE < self.getStop) and (self.getMFE <= self.unadj_T2):
return "T2_Win"
elif self.side == "Short" and (self.getMAE < self.getStop) and (self.getMFE <= self.unadj_T1):
return "Win"
else:
return "Loss"
When I use the same logic outside of the class (using print() instead of return), I get the correct results with the same data.
for i in range(len(tradeList)):
if Trade.side(tradeList[i]) == "Long" and (Trade.getMAE(tradeList[i]) > Trade.getStop(tradeList[i])) and (Trade.getMFE(tradeList[i]) >= Trade.unadj_T2(tradeList[i])):
print("T2_Win")
elif Trade.side(tradeList[i]) == "Long" and (Trade.getMAE(tradeList[i]) > Trade.getStop(tradeList[i])) and (Trade.getMFE(tradeList[i]) >= Trade.unadj_T1(tradeList[i])):
print("Win")
elif Trade.side(tradeList[i]) == "Short" and (Trade.getMAE(tradeList[i]) < Trade.getStop(tradeList[i])) and (Trade.getMFE(tradeList[i]) <= Trade.unadj_T2(tradeList[i])):
print("T2_Win")
elif Trade.side(tradeList[i]) == "Short" and (Trade.getMAE(tradeList[i]) < Trade.getStop(tradeList[i])) and (Trade.getMFE(tradeList[i]) <= Trade.unadj_T1(tradeList[i])):
print("Win")
else:
print("Loss")
Now, I might be grossly misunderstanding the return command or class methods in general. I am not experienced with python at all and for the life of me I can't figure out what's wrong here.
I checked if there was something wrong with the objects themselves, but there isn't. All the data is correct, so the issue MUST be in the first section of code I posted.
I am currently learning Python and I am trying to get this game to work. Basically I assigned a word to be guessed and then sliced the word and assigned it to several other variables. Basically, each variable assigned as "letterx" is a letter which makes up part of the string variable word. The problem is getting the while statement with nested if statements to work. For some reason I can't get the guess input to equal letterx. All I get when I run the code is "No." and then the amount of turns left. However, I can't get the elif statement to work. Pretty much everything else works. I'm used to programming in Java and I am fairly new to Python so any tips or help would be greatly appreciated. Thank you for your time and help! Here's the code:
#Guess The Word
word = "action"
letter1 = ""
letter2 = ""
letter3 = ""
letter4 = ""
letter5 = ""
letter6 = ""
position1 = 0
position2 = 1
position3 = 2
position4 = 3
position5 = 4
position6 = 5
letter1 += word[position1]
letter2 += word[position2]
letter3 += word[position3]
letter4 += word[position4]
letter5 += word[position5]
letter6 += word[position6]
print("Welcome to Guess the Word!\n")
count = 6
while(count != 0):
guess = input("Take a guess: \n")
if(guess != letter1 or guess != letter2 or guess != letter3 or guess !=
letter4 or guess != letter5 or guess != letter6):
count -= 1
print("No.\n")
print("Turns left: \n", count)
elif(guess == letter1 or guess == letter2 or guess == letter3
or guess == letter4 or guess == letter5 or guess == letter6):
count -= 1
print("Yes.\n")
if(count == 0):
print("Your turns are up, what do you think the word is?")
guess = input("The word is...: \n")
if(guess == word):
print("You win! That's the word")
elif(guess != word):
print("Sorry, you lose.")
Here's the program running in the Python shell:
Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Welcome to Guess the Word!
Take a guess:
a
No.
Turns left:
5
Take a guess:
c
No.
Turns left:
4
Take a guess:
t
No.
Turns left:
3
Take a guess:
i
No.
Turns left:
2
Take a guess:
o
No.
Turns left:
1
Take a guess:
n
No.
Turns left:
0
Your turns are up, what do you think the word is?
The word is...:
action
You win! That's the word
Let's say guess equals letter1. Then even though
guess == letter1, the first condition is still True since guess != letter2. And similarly, no matter what guess is, there is some letter (amongst letter1, letter2, etc.) which it is not equal.
So the first if condition is always True.
Instead, you could use
while(count != 0):
guess = input("Take a guess: \n")
if not guess in word:
count -= 1
print("No.\nTurns left: \n", count)
else:
count -= 1
print("Yes.\n")
By the way, it should be entirely possible to code the game without defining letter1, letter2, etc. All this code should be deleted:
letter1 = ""
letter2 = ""
letter3 = ""
letter4 = ""
letter5 = ""
letter6 = ""
position1 = 0
position2 = 1
position3 = 2
position4 = 3
position5 = 4
position6 = 5
letter1 += word[position1]
letter2 += word[position2]
letter3 += word[position3]
letter4 += word[position4]
letter5 += word[position5]
letter6 += word[position6]
Just use word[0] in place of letter1, and word[1] in place of letter2, etc.
And note you may not even need word[0], word[1]. For example,
with Python you can use
guess in word
instead of
guess in (word[0], word[1], word[2], word[3], word[4], word[5])
It's not only a lot less typing, it is more general, since guess in word does the right thing with words of any length.