I have the following code, which is a code for a connect 4 game, the problem is that the functions seem to break in the user input part of the code. I don't know if I accidentally edited something to break it but I'm almost certain that it isn't as typing the adding this to the code:
addcounter(1,1)
addcounter(1,1)
addcounter(1,1)
addcounter(1,1)
addcounter(2,1)
addcounter(2,1)
addcounter(2,1)
addcounter(3,1)
addcounter(3,1)
addcounter(4,1)
checkdiagonal(4,1,1)
The output of this does return true as expected.
The code is as follows:
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 22 17:24:35 2019
#author: Norbert
"""
import numpy as np
h = 8
w = 9
x = 0
y = 0
playspace = np.zeros((h,w))
playspace[:, [0,-1]] = 8
def addcounter(column,team):
placed = False
while not placed:
for i in range(h-1,0,-1):
if playspace[i,column] > 0:
continue
else:
if team == 1:
playspace[i,column] = 1
if team == 2:
playspace[i,column] = 2
if team != 1 and team != 2:
print("error, invalid team")
placed = True
break
def height(column):
for i in range(h-1,0,-1):
if playspace[i,column] > 0:
continue
else:
return i
def checkhorizontal(y,x,team):
a1 = 0
a2 = 0
a3 = 0
a4 = 0
for i in range(4):
try:
if playspace[h-y,x+i] == team:
a1 += 1
if playspace[h-y,x+i-1] == team:
a2 += 1
if playspace[h-y,x+i-2] ==team:
a3 += 1
if playspace[h-y,x+i-3] ==team:
a4 += 1
except:
pass
if (a1 == 4) or (a2 == 4) or (a3 == 4) or (a4 == 4):
return True
def checkvertical(y,x,team):
a1 = 0
a2 = 0
a3 = 0
a4 = 0
checking = playspace[:,x]
for i in range(4):
try:
if checking[h-(y+i)] == team:
a1 += 1
if checking[h-(y+i-1)] == team:
a2 += 1
if checking[h-(y+i-2)] ==team:
a3 += 1
if checking[h-(y+i-3)] == team:
a4 += 1
except:
pass
if (a1 == 4) or (a2 == 4) or (a3 == 4) or (a4 == 4):
return True
def checkdiagonal(y,x,team):
diag1 = 0
diag2 = 0
if playspace[h-y,x] == team:
diag1 += 1
diag2 += 1
for i in range(1,4):
broken1 = False
try:
if playspace[h-y+i,x+i] == team and not broken1:
diag1 += 1
if playspace[h-y+i,x+i] != team:
broken1 = True
except:
pass
for i in range(1,4):
broken2 = False
try:
if playspace[h-y-i,x-i] == team and not broken2:
diag1 += 1
if playspace[h-y-i,x-i] != team:
broken2 = True
except:
pass
for i in range(1,4):
broken3 = False
try:
if playspace[h-y+i,x-i] == team and not broken3:
diag2 += 1
if playspace[h-y+i,x-i] != team:
broken3 = True
except:
pass
for i in range(1,4):
broken4 = False
try:
if playspace[h-y-i,x+i] == team and not broken4:
diag2 += 1
if playspace[h-y-i,x+i] != team:
broken4 = False
except:
pass
if (diag1 >= 4) or (diag2 >= 4):
return True
finished = False
turn = 0
team_turn = 1
print(playspace)
while not finished:
valid = False
print("turn: {}".format(turn))
print("It is player {}'s turn".format(team_turn))
while not valid:
player_input = int(input("Where would you like to drop a counter?"))
if playspace[0,player_input] != 0:
print("That isn't a valid column")
else:
valid = True
if team_turn == 1:
addcounter(player_input,team_turn)
if checkhorizontal(height(player_input),player_input,team_turn) == True or checkvertical(height(player_input),player_input,team_turn) == True or checkdiagonal(height(player_input),player_input,team_turn) == True:
print("Player {} wins".format(team_turn))
finished = True
if team_turn == 2:
addcounter(player_input,team_turn)
if checkhorizontal(height(player_input),player_input,team_turn) == True or checkvertical(height(player_input),player_input,team_turn) == True or checkdiagonal(height(player_input),player_input,team_turn) == True:
print("Player {} wins".format(team_turn))
finished = True
turn += 1
turn_changed = False
while not turn_changed:
if team_turn == 1:
team_turn = 2
turn_changed = True
break
if team_turn == 2:
team_turn = 1
turn_changed = True
break
print(playspace)
any help in trying to solve the bugs in the code would be grately appreciated. The connect 4 game uses simple 2-d arrays to display and store the game board. I have plans to use this array to create a pygame later on.
EDIT:
To clarify, the checks don't run to execute a victory message and end the game. despite the if statements being True. Only the vertical win seems to end the game.
I managed to correct the horizontal part, the code correction is as follows:
if (checkhorizontal(height(player_input)+1,player_input,team_turn) == True) or (checkvertical(height(player_input),player_input,team_turn) == True) or (checkdiagonal(height(player_input),player_input,team_turn) == True):
and in the horizontalcheck function:
def checkhorizontal(y,x,team):
a1 = 0
a2 = 0
a3 = 0
a4 = 0
checking = playspace[y,:]
print(checking)
for i in range(4):
try:
if checking[x+i] == team:
a1 += 1
if checking[x+i-1] == team:
a2 += 1
if checking[x+i-2] ==team:
a3 += 1
if checking[x+i-3] ==team:
a4 += 1
except:
pass
print(a1,a2,a3,a4)
if (a1 == 4) or (a2 == 4) or (a3 == 4) or (a4 == 4):
return True
Ignore the prints, they're for debugging. But I basically removed one dimension and flipped the h-y value to become the y value.
Related
So I was going to make an arithmetic operator:
import random
solution = 0
summation = False
multiplication_table = False
subtraction = False
the_exercise = False
def arithmetic_operation(arithmetic_type):
stopper = []
exercise = input(
f"This is the {arithmetic_type} generator. Subjects: summation, multiplication table, subtraction.\nWhich of the subjects is "
"the student to practice? Please choose one of these 3 specifically")
if exercise == 'summation':
summation = True
elif exercise == 'multiplication table':
multiplication_table = True
elif exercise == 'subtraction':
subtraction = True
while summation == True:
ten_exercises = 0
if ten_exercises == 2:
summation == False
a = random.randint(0, 50)
b = random.randint(0, 50)
solution = a + b
print(f"What is {a} + {b}?")
the_exercise = True
return solution
while multiplication_table == True:
ten_exercises = 0
if ten_exercises == 2:
summation == False
a = random.randint(0, 10)
b = random.randint(0, 10)
solution = a * b
print(f"What is {a} * {b}?")
the_exercise = True
return solution
while subtraction == True:
ten_exercises = 0
if ten_exercises == 2:
summation == False
a = random.randint(21, 100)
b = random.randint(0, 20)
solution = a - b
print(f"What is {a} - {b}?")
the_exercise = True
return solution
arithmetic_operation("artithmetic exercise")
def main():
while the_exercise == True:
ans = input()
if int(ans) == solution:
print("Correct!")
stopper.append("STOP!")
if stopper.count("STOP!") == 10:
print("That's the end. Until next time!")
summation == False
else:
break
else:
print("Wrong! Try again")
ten_exercises += 1
if __name__ == '__main__':
main()
The problem is that my two functions aren't cooperating. According to the exercise, 'arithmetic_operation' is supposed to have a parameter.
What is it that I fail to understand? I have tried multiple solutions and replacing blocks of code to the main, but it doesn't work...
I am looking for a converting from TV to python. Just a little code. This is the code in tradingview :
last_signal = 0
long_final = longCond and (nz(last_signal[1]) == 0 or nz(last_signal[1]) == -1)
short_final = shortCond and (nz(last_signal[1]) == 0 or nz(last_signal[1]) == 1)
last_signal := long_final ? 1 : short_final ? -1 : last_signal[1]
for variable :
-> longCond and shortCond, i have the right value (I compared between plot)
But for others, i have some differences (i think, because of last_signal)
this is my code in python :
for x in range(0,len(mavi),1):
last_signal[i] = 0
if x == 0:
longCond_tmp = 0
shortCond_tmp = 0
last_signal_tmp = 0
short_final_tmp = 0
long_final_tmp = 0
else:
if ((longCond_tmp and ((last_signal[i-1])) == 0) or ((last_signal[i-1]) == -1)):
long_final_tmp = 1
else:
long_final_tmp = 0
if ((shortCond_tmp and ((last_signal[i-1])) == 0) or ((last_signal[i-1]) == 1)):
short_final_tmp = 1
else:
short_final_tmp = 0
if long_final_tmp != 0:
last_signal_tmp = 1
else:
if short_final_tmp != 0:
last_signal_tmp = -1
else:
last_signal_tmp = last_signal[i-1]
last_signal[i] += last_signal_tmp
Are there errors in my script in python ?
Ok i found.
Just the number of "(" in
if ((longCond_tmp and ((last_signal[i-1])) == 0) or ((last_signal[i-1]) == -1)):
long_final_tmp = 1
else:
long_final_tmp = 0
if ((shortCond_tmp and ((last_signal[i-1])) == 0) or ((last_signal[i-1]) == 1)):
short_final_tmp = 1
else:
short_final_tmp = 0
during the execution of the code the program skips all ELIF conditions, going directly to ELSE, even if the ELIF condition is TRUE
a = 0
b = 0
c = 0
r = 0
soma = 1
sub = 2
div = 3
mult = 4
print('enter the number corresponding to the operation you want to do:\n')
print('Sum [1]')
print('Subtraction[2]')
print('Divisao [3]')
print('Multiplication [4]')
r = int(1)
while (r == 1):
operacao = 0
operacao = input('\n>')
if operacao == soma:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a + b
print ('\n A Soma de {} mais {} equivale a: {}'.format(a,b,c))
elif operacao == sub:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a - b
print ('\n A subtracao de {} menos {} equivale a: {}'.format(a,b,c))
elif operacao == div:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a / b
print ('\n A divisao de {} de {} equivale a: {}'.format(a,b,c))
elif operacao == mult:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a * b
print ('\n The multiplication of {} by {} is equivalent to: {}'.format(a,b,c))
else: #going direct to here...
print('\n Unrecognized operation')
EXPECTED that the ELIF conditions would work when true,but not working.
input returns a string, so you'll need to do operacao = int(input('\n>')), otherwise str == int will always be False:
x = input("\n>") # I've input 5
x
# '5'
# returns False because x is a string
x == 5
# False
# converts x to int, so returns True
int(x) == 5
# True
# returns True because we are comparing to a string
x == '5'
# True
So for your code:
# convert the return of input to int for comparing against other ints
operacao = int(input('\n>')) # I'll put 3
if operacao == 1:
print('got one')
elif operacao == 3:
print('got three')
# got three
My code is not running although everything is properly indented and I have been using Python for a while now, so I am no longer in the world of programming. I couldn't find the solution.
def revisedRussianRoulette(doors):
counter = 0
for i in range(0, len(doors), 2):
i = int(i)
if doors[i] == 1 & counter == 0:
counter += 1
elif doors[i] == 1 & counter == 1:
doors[i] = 0
doors[i-2] = 0
doors[i+2] = 0
elif doors[i] == 0 & counter == 1:
doors[i-2] = 0
return doors
n = int(input().strip())
doors = list(map(int, input().strip().split(' ')))
result = revisedRussianRoulette(doors)
print (" ".join(map(str, result)))
The thing I want to do with this code does not matter. I just want to ask if the syntax is correct because I am getting the following error.
C:\Users\lenovo\Desktop\Practice Files>2nd_answer_week_of_code_36.py
File "C:\Users\lenovo\Desktop\PracticeFiles\2nd_answer_week_of_code_36.py", line 13
return doors
^
IndentationError: unindent does not match any outer indentation level
Please, could anyone tell me the solution fast?
EDIT:
The solution provided by Vikas was accurate, although there were no differences between his and my code.
Do indenation like this :
def revisedRussianRoulette(doors):
counter = 0
for i in range(0, len(doors), 2):
i = int(i)
if doors[i] == 1 & counter == 0:
counter += 1
elif doors[i] == 1 & counter == 1:
doors[i] = 0
doors[i-2] = 0
doors[i+2] = 0
elif doors[i] == 0 & counter == 1:
doors[i-2] = 0
return doors
def revisedRussianRoulette(doors):
counter = 0
for i in range(0, len(doors), 2):
i = int(i)
condition_one = doors[i] == 1 & counter == 0
condition_two = doors[i] == 1 & counter == 1
condition_three = doors[i] == 0 & counter == 1
if condition_one:
counter += 1
elif condition_two:
doors[i] = 0
doors[i-2] = 0
doors[i+2] = 0
elif condition_three:
doors[i-2] = 0
return doors
n = int(input().strip())
doors = list(map(int, input().strip().split()))
result = revisedRussianRoulette(doors)
print (" ".join(map(str, result)))
I am struggling to understand the following error in the code block below:
if o == None or t == None:
try:
elif o == 1 and t == 1:
c1 = c1 + 1
elif o == -1 and t == -1:
c2 = c2 + 1
elif o == -1 and t == 1:
i1 = i1 + 1
elif o == 1 and t == -1:
i2 = i2 + 1
return (c1, i1, c2, i2)
Error :
elif o == 1 and t == 1:
^
Syntax error : invalid syntax
Can anyone point out what am I doing wrong? I followed correct indentation in the program.
You appear to have a naked try in your code which is very much stuffing up the layout of your program.
You can certainly try within a code block of an if statement, but you need to provide the entire thing, something like:
if somethingOrOther():
try:
xyzzy = 42
except:
pass
elif ...
This is the structure of your code correctly indented, so maybe now it's obvious what the problem is?
if o == None or t == None:
try:
elif o == 1 and t == 1:
c1 = c1 + 1
elif o == -1 and t == -1:
c2 = c2 + 1 elif o == -1 and t == 1:
i1 = i1 + 1
elif o == 1 and t == -1:
i2 = i2 + 1
return (c1, i1, c2, i2)
Once you fix your indentation
if o == None or t == None:
try:
elif o == 1 and t == 1:
c1 = c1 + 1
elif o == -1 and t == -1:
......
your code will still not work. Note how the elif is at a different indentation from the if.
You cannot splice a try into the middle of an if statement. All the elif statements must be at the same nesting/indentation level. Therefore if you open a try block inside an if or elif, you must complete it before completing that if or elif.
You'll need it like this:
try:
if o is None or t is None:
pass
elif o == 1 and t == 1:
c1 = c1 + 1
elif o == -1 and t == -1:
......
Another point to make is not to compare against None using the equality operator. You should use is when comparing against the singleton None:
if o is None or t is None:
Your code is correct just the format is wrong.
Nothing to serious but format is highly effective in python, the wrong amount of whitespaces and it could ruin your entire code. Organization and punctuation with semicolons are also key.
Here is the right format.
if o == None or t == None:
try:
elif o == 1 and t == 1:
c1 = c1 + 1
elif o == -1 and t == -1:
c2 = c2 + 1
elif o == -1 and t == 1:
i1 = i1 + 1
elif o == 1 and t == -1:
i2 = i2 + 1
except:
...
return (c1, i1, c2, i2)
Great question! This will be used throughout all the time stack overflow is around. Keep it up!