How to minimize recursion - python

I'm trying to make minesweeper with tkinter in a really simple way but on the first click that break a lot of cells with no mines around it is kinda confusing. I tried checking all the cells around it by calling a function over and over again, there aren't that many cells to check but I keep getting a recursion error. How do I fix this?
def break_logic(now):
global checked
if BTNvals.get(now)==0: #check if the button has 0 mines around it
checked.append(now)
CanGo = check(now)[1] #check surroundings
for _checked in CanGo:
if _checked in checked:
CanGo.remove(_checked)
elif BTNvals.get(_checked)!=0:
button_ids[_checked-1].destroy()
CanGo.remove(_checked)
for _cans in CanGo:
button_ids[_cans-1].destroy()
break_logic(_cans) #recursion
0 means no mines around it.
It breaks a bit but not all it's supposed to.

Related

Phrase that pauses update loop then continues

Is there a way I could simplify this code?
My code is much longer and would take a lot more explaining to fully understand my question, so I condensed my issue into a smaller example:
i = 0
def test():
global i
i += 1
print("animated")
while True:
if i < 3:
test()
else:
print("updated")
In my situation, I would like to run a function in an infinite loop that is the only line that is ran until a number of frames pass by. My solution was to create a counter, i, that counts each frame in the test() function and it is checked every frame until it is past 3. In my actual code for my pygame game, this functionality was supposed to be a for a menu transition system. I wanted to have it so that when you enter the menu, an animation plays first before you are given functionality. I needed the animation to count up in its frames every time the menu was updated from the infinite loop. I had tried the i counter solution in my actual game code but it became to bloated and hard to read with the amount of code already written. I was wondering if there was a simpler solution that was much easier to read and comprehend on my part.

How do I get this input to work inside of an inherited class in Python?

So, to preface this I’m self learning python and I’m trying to build a Tic-Tac-Toe game using the command line as an interface. The issue that I have is that I can’t get the input inside one of the inherited class for the player to work (so the game itself doesn’t work aside from the 3x3 board showing up on the command line)
The section of code that I’m having issues with goes as such:
class HumanPlayer(Player):
def __init__(self, letter):
super().__init__(letter)
def get_move(self, game):
valid_square = False
val = None
while not valid_square:
square = input(self.letter + ' s turn. Input move (0-9):')
# we are going to check that this is a correct value by trying to cast
# it into an integer, and if it's not, then we will say its invalid
# if that spot is not available on the board, then we also say it's invalid
try:
val = int(square)
if val not in game.available_moves:
raise ValueError
valid_square = True # if these are successful, then oh yeah!
except ValueError:
print ('Invalid Square. Try Again. ')
return val
I’ve tried to make sure that my spacing is correct within this class, but now I’m not sure what else to do. Any help, suggestions, or the like would be appreciated since I’m learning to program in general
Thanks!
Although there is nothing wrong with an object-oriented approach, and it can be the (or at least a) right approach for many problems, it looks like your program has "classes because of classes". It's probably easier if you don't bother with the object-orientation too much at this stage and focus on the main gameplay loop.
Try to imagine how the game should progress: you start the game, you make a move, another player makes a move, this continues until the game decides either play has won and then perhaps you can start a new game. And the other player might be an "AI" (tic tac toe doesn't require much intelligence) or another live player.
Your code covers what needs to happen for a single player to enter a valid square and it appears you have another class somewhere that's a Game, an instance of which has an attribute available_moves that contains all the currently valid moves. Or perhaps that Game class is the next thing you plan to write.
The main game loop would be to ask players for a move in alternating fashion, update the game board, decide if someone has won yet, and keep doing that. And you'll need to get the whole thing started, some core routine that sets up the game and the players and gets the ball rolling.
If you have a more specific problem getting all that to work, you should post a question about that - but without a more specific problem, it's hard to provide a better answer.
Where is the code for th

Swapping and removing numbers within a randomized Python guessing game

Within a python program, I need to simulate a basic game. Within this game, I need to randomize a hiding spot using a number between 1-3 as part of a simulated game:
def coin_places():
return random.randrange(1,4)
I then take this random number and put it into the game, seeing if the simulated guess is correct:
hide_spot = coin_places()
print(hide_spot)
guess = random.randrange(1,4)
print(guess)
def game():
if guess == hide_spot:
return True
elif guess != hide_spot:
return False
else:
return game(guess)
However, where I'm stumped is, I've been tasked with creating a caveat where one wrong hiding spot is removed, and the program must swap the remaining two guess numbers.
For example, the ramdom output is guess = 2 and hide_spot = 2, so the number 3 or 1 needs to be removed, and guess will be swapped with what is left, let's say from 2 to 1. Each the caveat and original values are outputted as percent chances (just as background, I'm able to write that part)
I can't seem to be able to find any examples of this kind of problem elsewhere, and any help would be greatly appreciated!
To be a bit more clear essentially I need to:
Create a simulated number of games, from user input
Create the number of spots and designate one as the hiding spot.
Create the parameters of the normal game, simulating user guess
Add another technique, which will produce its own results, where one wrong hiding spot is removed, and the program must swap the remaining two guess numbers.
Output the chances of success of each technique as percentages
Thanks a bunch for any help or consideration!

Finding Next Obstacle in List

I am trying to create a game that moves to the end of a square. Inside the game I created obstacles by making a list of true and false (false=obstacles). What I have (but did not post) is something that detects an obstacle ONLY IF the user lands on the obstacle. However, I want to find a way to detect an obstacle BEFORE the user makes its next move and make it stay in place if the next spot will be an obstacle. In other words I want to find the next index of list before proceeding. Here's some pseudo code for a better picture:
if next_left != [[False]]: # if there is no obstacle
officially_move_left
else: # if there is an obstacle
user_do_nothing
What I have (in pseudo):
def moving_pos(user):
copy_user.pos = user.pos
if copy_user.pos +1 == [True]
user.pos += 1
copy_user.pos += 1
else:
return user.pos
if (user_position == obstacle):
next_square_is_obstacle = true
user_move_backwards
ie, move the player, detect the object, move the player back again. It's very difficult to help without seeing the actual implementation
Edit: Okay, in your new edit I don't see any reason why the program should have such constraints. However, let me suggest something new-
obstacle_index = [obs1, obs2, obs3...]
if user_position+1 in obstacle_index:
do_nothing;
else
user_move_forward;
Can you post the actual minimal working code, or at least a more detailed pseudocode of the implementation?

Adding a countdown timer in python

I'll admit, i am a newbie with python, but here is my issue.
the version is 2.6.5 (i know i'ts an old version but there's reasons to this) and livewires is used
Bascially this game has a bunch of colored balloons in which you need to click them to make them disappear. Adjacent balloons of the same color disappear along with the clicked balloon. Once the balloons are cleared it moves on to the next level.
I need to create a timer on the top right of my screen. This timer needs to countdown in seconds (from 30 might be a good start.) However no matter what i try, either the timer does not display or the numbers are overlap eachother. I would like to know how to do this, as it has been driving me up the wall as of late.
...Of course it also needs to end the game if it reaches zero and add more time if the level is complete...
But for now i just want to focus on displaying the timer and having it count down to zero on screen.
class Timer(games.Sprite):
""" countdown timer """
def __init__(self):
timer_message = games.Text(
value = 30,
size = 50,
color = red,
x = 600,
y = 30
)
def start(self):
while self.timer_message.value != 0:
time.sleep(1)
self.timer_message.value -= 1
game.screen.add(timer_message)
Alright. I fixed the "compressing balloons table" (accidentally deleted the self_update lol) problem, but now it is saying that "global name timer_message is not defined"... despite the fact that it says timer_message = games.Text
I would paste the whole code, but i can't get the indentation right (this is my first time using this website.)
So, I understand it's been some time and if you don't need an answer anymore that's alright.
For now it's hard to answer your question in general because I don't understand the structure of the rest of your code or how you're displaying graphics. However, I can tell you while you're getting the
global name timer_message is not defined
error. It's because when you define timer_message within the __init__ function you are defining it within the local scope of the function but not for the class. In order to make it accessible to the class you need to assign to self.timer_message.
This is a consequence of how python imitates object oriented programming, but making this change should address your immediate error.

Categories

Resources