Auto clear blank spaces in minesweeper - python-3.x

I'm trying to code minesweeper in pygame, I am having a problem with auto-clearing the blank spaces due to a recursion error, RecursionError: maximum recursion depth exceeded in comparison, it says it is being repeated 993 more times (this amount doesn't change no matter how many randomly generated positions I create). I've tried doing my own solution and got this problem then I used a solution I found on the internet and still got the same error I'm not sure what to do
import pygame
import random
pygame.init()
size = 800
rows = 8
window = pygame.display.set_mode((size, size))
pygame.display.set_caption("MineSweeper")
mines_needed = 10
num_colour = {
0: (255,255,255), 1:(3,37,126), 2: (0,137,0), 3: (255,0,0), 4: (0,0,255), 5: (128,0,0), 6: (0,128,128), 7: (0,0,0), 8: (128,128,128)
}
font = pygame.font.SysFont('arial', 30)
def board():
global board_array
board_array = []
window.fill((255, 255, 255))
distance = size//rows #100
x = 0
y = 0
for i in range(rows):
pygame.draw.line(window, (0, 0, 0), (x, 0), (x, size))
pygame.draw.line(window, (0, 0, 0), (0, y), (size, y))
x += distance
y += distance
elements = []
for j in range(rows):
elements.append(0)
board_array.append(elements)
def create_mines():
mines_created = 0
while mines_created < mines_needed:
randomr = random.randint(-1,7)
randomc = random.randint(-1,7)
if board_array[randomr][randomc] == -1:
pass
else:
board_array[randomr][randomc] = -1
mines_created += 1
def draw():
number = 0
for x in range(8):
for y in range(8):
if x == 0 and y == 0:
number = 0
if board_array[x + 1][y] == -1:
number += 1
if board_array[x + 1][y + 1] == -1:
number += 1
if board_array[x][y + 1] == -1:
number += 1
if board_array[x][y] != -1:
board_array[x][y] = number
if x == 7 and y == 0:
number = 0
if board_array[x - 1][y] == -1:
number += 1
if board_array[x - 1][y + 1] == -1:
number += 1
if board_array[x][y + 1] == -1:
number += 1
if board_array[x][y] != -1:
board_array[x][y] = number
if x == 0 and y == 7:
number = 0
if board_array[x + 1][y] == -1:
number += 1
if board_array[x + 1][y - 1] == -1:
number += 1
if board_array[x][y - 1] == -1:
number += 1
if board_array[x][y] != -1:
board_array[x][y] = number
if x == 7 and y == 7:
number = 0
if board_array[x - 1][y] == -1:
number += 1
if board_array[x - 1][y - 1] == -1:
number += 1
if board_array[x][y - 1] == -1:
number += 1
if board_array[x][y] != -1:
board_array[x][y] = number
if x == 0 and (y != 0 and y != 7):
number = 0
if board_array[x][y - 1] == -1:
number += 1
if board_array[x + 1][y - 1] == -1:
number += 1
if board_array[x + 1][y] == -1:
number += 1
if board_array[x + 1][y + 1] == -1:
number += 1
if board_array[x][y + 1] == -1:
number += 1
if board_array[x][y] != -1:
board_array[x][y] = number
if x == 7 and (y != 0 and y != 7):
number = 0
if board_array[x][y - 1] == -1:
number += 1
if board_array[x - 1][y - 1] == -1:
number += 1
if board_array[x - 1][y] == -1:
number += 1
if board_array[x - 1][y + 1] == -1:
number += 1
if board_array[x][y + 1] == -1:
number += 1
if board_array[x][y] != -1:
board_array[x][y] = number
if y == 0 and (x != 0 and x != 7):
number = 0
if board_array[x + 1][y] == -1:
number += 1
if board_array[x - 1][y] == -1:
number += 1
if board_array[x][y + 1] == -1:
number += 1
if board_array[x + 1][y + 1] == -1:
number += 1
if board_array[x - 1][y + 1] == -1:
number += 1
if board_array[x][y] != -1:
board_array[x][y] = number
if y == 7 and (x != 0 and x != 7):
number = 0
if board_array[x + 1][y] == -1:
number += 1
if board_array[x - 1][y] == -1:
number += 1
if board_array[x][y - 1] == -1:
number += 1
if board_array[x + 1][y - 1] == -1:
number += 1
if board_array[x - 1][y - 1] == -1:
number += 1
if board_array[x][y] != -1:
board_array[x][y] = number
if (x != 7 and x != 0) and (y != 7 and y != 0):
number = 0
if board_array[x][y + 1] == -1:
number += 1
if board_array[x][y - 1] == -1:
number += 1
if board_array[x + 1][y] == -1:
number += 1
if board_array[x - 1][y] == -1:
number += 1
if board_array[x - 1][y - 1] == -1:
number += 1
if board_array[x + 1][y - 1] == -1:
number += 1
if board_array[x - 1][y + 1] == -1:
number += 1
if board_array[x + 1][y + 1] == -1:
number += 1
if board_array[x][y] != -1:
board_array[x][y] = number
def click(x,y):
dug = set()
dug.add((x,y))
centre_x = (x * 100) + 50
centre_y = (y * 100) + 50
if board_array[x][y] != -1:
number_text = font.render(str(board_array[x][y]), True, num_colour[board_array[x][y]])
window.blit(number_text, (centre_x - 10, centre_y - 10))
elif board_array[x][y] != 0:
pygame.draw.circle(window, (0, 0, 0), (centre_x, centre_y), 10)
if board_array[x][y] == 0:
pygame.draw.rect(window, (128,128,128), (x*100+2, y*100+2, 97, 97))
for i in range(max(0,x-1), min(6,x+1)+1):
for j in range(max(0, y-1), min(6, y+1)+1):
if (x,y) in dug:
pass
click(x,y)
def draw_flag():
pass
board()
create_mines()
draw()
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
x,y = pygame.mouse.get_pos()
x /= 100
y /= 100
click(int(x),int(y))
if event.type == pygame.QUIT:
run = False
print(board_array)
pygame.display.update()
I know my code could be better optimised but I tried to do this with minimal help from the internet and plan on going back to it once I've completed the game

I'm not sure exactly what you are trying to do, but you are passing the original arguments to the recursive call in click, thus running endlessly.
if (x,y) in dug:
pass
click(x,y)
Replace (x,y) with (i,j).
pass does nothing - you probably wanted continue to jump over the recursive click - instead, use:
if (i,j) not in dug:
click(i,j)
It looks like this will still fail as you don't use the dug set in the recursive calls, so you need to pass it to and get it back from the recursive click to skip points you've finished handling.

Related

I'm running a odd/even game in Python and I get stuck once I need to define a winner

#Here I define the user and cpu function
cpu_num = random.randint(1,6)
user_selection = ["Odd", "Even"]
def cpu_choice():
choice = random.randint(1,6)
print("The computer's choice is",choice)
return choice
def user_choice():
while(True):
choice = input("Odd or Even? ")
if choice in user_selection:
print("Your choice is",choice)
return choice
else:
print("You did not write your answer correctly, please try again.")
#In this function I define the result of each round based on previous formulas and two new variables (num_rounds and user_lives) and everything works well
def round_result():
num_rounds = 0
user_lives = 10
while num_rounds < 8 and user_lives > 0:
user_pick = user_choice()
cpu_pick = cpu_choice()
if (cpu_pick % 2 == 0) and (user_pick == "Even"):
print (f'You have {user_lives + cpu_pick} lives left')
num_rounds += 1
user_lives = user_lives + cpu_pick
if (cpu_pick % 2 == 0) and (user_pick == "Odd"):
print (f'You have {user_lives - cpu_pick} lives left')
num_rounds += 1
user_lives = user_lives - cpu_pick
if (cpu_pick % 2 != 0) and (user_pick == "Even"):
print (f'You have {user_lives - cpu_pick} lives left')
num_rounds += 1
user_lives = user_lives - cpu_pick
if (cpu_pick % 2 != 0) and (user_pick == "Odd"):
print (f'You have {user_lives + cpu_pick} lives left')
num_rounds += 1
user_lives = user_lives + cpu_pick
#Everything works well until here, I don't know what am I doing wrong in the winner function
def winner():
user_won = user_lives > 0 and num_rounds == 8
cpu_won = user_lives < 0
game = round_result()
while game:
if user_won is True:
print ('You won')
if cpu_won is True:
print ('Cpu won')

Trying to make Gnome sort recursive

I was given the following block of code
def sort(a):
"""Sort list a into ascending order by value.
Adapted from https://en.wikipedia.org/wiki/Gnome_sort#Code.
"""
pos = 0
while pos < len(a):
if pos == 0 or a[pos] >= a[pos-1]:
pos += 1
else:
a[pos], a[pos-1] = a[pos-1], a[pos]
pos -= 1
and need to make implment it the same in python, but recursively instead of iteratively. so far I have
def sort(a,pos=0):
if(pos<len(a)):
return
else:
if(pos==0 or a[pos]>= a[pos-1]):
sort(a,pos+1)
else:
a[pos],a[pos-1]= a[pos-1],a[pos]
pos=pos-1
can anyone help me out
You should not return when pos is less than len(a), and you should make a recursive call with pos - 1 after the swap:
def sort(a, pos=0):
if pos < len(a):
if pos == 0 or a[pos] >= a[pos - 1]:
sort(a, pos + 1)
else:
a[pos], a[pos - 1] = a[pos - 1], a[pos]
sort(a, pos - 1)

IndexError: list index out of range when trying to make grid for minesweeper in python

I'm trying to make minesweeper grid in python. So basically, first there are only zeros and 10 bombs (X's) in the grid and if some index in this grid has bomb in it, the program should add 1 to all surrounding indexes, excluding indexes that also have bomb in it.
Here is my code:
import random
board1 = [[0] * 9 for n in range(9)]
for pos in random.sample(range(72), 10):
a = pos // 9
b = pos % 9
board1[a][b] = "X"
if a != 0 and b != 0 and board1[a-1][b-1] != "X":
board1[a - 1][b - 1] += 1
if a != 0 and board1[a-1][b] != "X":
board1[a - 1][b] += 1
if a != 0 and b != 9 and board1[a-1][b+1] != "X":
board1[a - 1][b + 1] += 1
if b != 0 and board1[a][b-1] != "X":
board1[a][b - 1] += 1
if b != 9 and board1[a][b+1] != "X":
board1[a][b + 1] += 1
if a != 9 and b != 0 and board1[a+1][b-1] != "X":
board1[a+1][b - 1] += 1
if a != 9 and board1[a+1][b] != "X":
board1[a + 1][b] += 1
if a != 9 and b != 9 and board1[a+1][b+1] != "X":
board1[a + 1][b + 1] += 1
frmt = "{:>3}"*len(board1)
for row in board1:
print(frmt.format(*row))
The code seems to work, but sometimes I get this error:
if a != 0 and b != 9 and board1[a-1][b+1] != "X":
IndexError: list index out of range
The error usually says if a != 0 and b != 9 and board1[a-1][b+1] != "X":, but sometimes it might give error from some other line, like: if b != 9 and board1[a][b+1] != "X":.
I've been pulling my hair out for days with this, can someone help?
import random
board1 = [[0] * 9 for n in range(9)]
for pos in random.sample(range(72), 10):
a = pos // 9
b = pos % 9
board1[a][b] = "X"
if a != 0 and b != 0 and board1[a-1][b-1] != "X":
board1[a - 1][b - 1] += 1
if a != 0 and board1[a-1][b] != "X":
board1[a - 1][b] += 1
if a != 0 and b != 8 and board1[a-1][b+1] != "X":
board1[a - 1][b + 1] += 1
if b != 0 and board1[a][b-1] != "X":
board1[a][b - 1] += 1
if b != 8 and board1[a][b+1] != "X":
board1[a][b + 1] += 1
if a != 8 and b != 0 and board1[a+1][b-1] != "X":
board1[a+1][b - 1] += 1
if a != 8 and board1[a+1][b] != "X":
board1[a + 1][b] += 1
if a != 8 and b != 8 and board1[a+1][b+1] != "X":
board1[a + 1][b + 1] += 1
frmt = "{:>3}"*len(board1)
for row in board1:
print(frmt.format(*row))
I have updated your code hopefully this will work for you.
I think this happens when your bomb is at one extremity of the board when b=9 then the index b+1 (10) does not exist.
This does not happen when b or a are equals to 0 because you can access elements in a list with a negative index (the last one for -1) but I don't think you want this.

Testing divisibility of a list and appending if prime

I'm writing a short snippet for a class that is supposed to run through a given list of numbers and append any primes. Right now it is returning all numbers in the range though.
I've found examples online for how to do this, but wanted to try it myself but I've seem to hit a wall... Here is my code:
from random import randrange
from time import sleep
def prime():
user_num = eval(input("Input a number: "))
list_prime = []
for i in range(2,user_num):
if (i % 2) == 1 and\
(i % 3) == 1 and\
(i % 4) == 1 and\
(i % 5) == 1 and\
(i % 6) == 1 and\
(i % 7) == 1 and\
(i % 8) == 1 and\
(i % 9) == 1 or\
i == 2:
list_prime.append(i)
if list_prime == '':
print('No prime numbers.')
if list_prime != '':
print('\nPrime numbers from 1 to ' + str(user_num) + ': ' + str(list_prime))
sleep(1)
print('\nClosing console in 60 seconds...')
sleep(60)
prime()
As he said, you werent correctly checking for prime numbers.
from random import randrange
from time import sleep
list_prime = []
user_num = 0
def prime():
user_num = eval(input("Input a number: "))
for i in range(2,user_num):
j = 2
isprime = 1
while (j <= i/2):
if (i % j == 0):
isprime = 0
break
j+=1
if (isprime == 1):
list_prime.append(i)
prime()
if list_prime == '':
print('No prime numbers.')
if list_prime != '':
print('\nPrime numbers from 1 to ' + str(user_num) + ': ' + str(list_prime))
sleep(1)
print('\nClosing console in 60 seconds...')
sleep(60)
Checking if the result of a modulo operation is 1 is not the correct approach. For example, 6 % 5 is 1, but 6 definitely isn't a prime number. Instead, for each suspect N you should check that no number X exists such that N % X == 0.
A wildly sub-optimal implementation could look like this:
list_prime = []
for i in range(2, user_num):
if all(n % x for x in list_prime):
list_prime.append(i)

List index out of range when moving

This is my code for the game of fifteen, excluding the 'won' function:
import sys
d = int(sys.argv[1])
dimension = (d * d) - 1
board = [[0 for x in range(d)] for y in range(d)]
def main():
global d
if len(sys.argv) != 2 or 0 > d or d > 9:
print("usage: python fifteen.py size")
exit()
def init():
global d
global dimension
global board
for row in range(d):
for col in range(d):
board[row][col] = dimension
dimension -= 1
if d % 2 == 0:
board[d-1][d-3] = 1
board[d-1][d-2] = 2
def draw():
global d
global dimension
global board
for row in range(d):
for col in range(d):
if board[row][col] == 0:
print("__", end="")
else:
print("{:0=2d} ".format(board[row][col]), end="")
print("")
def move():
global d
global dimension
global board
while True:
tile = int(input("Tile to move: "))
if tile > 0:
break
for row in range(d):
for col in range(d):
if board[row][col] == tile:
colleft = col - 1
colright = col + 1
rowup = row - 1
rowdown = row + 1
if board[row][colleft] == 0 and colleft >= 0:
board[row][colleft] = tile
board[row][col] = 0
return True
elif board[row][colright] == 0 and colright < d:
board[row][colright] = tile
board[row][col] = 0
return True
elif board[rowup][col] == 0 and rowup >= 0:
board[rowup][col] = tile
board[row][col] = 0
return True
elif board[rowdown][col] == 0 and rowdown < d:
board[rowdown][col] = tile
board[row][col] = 0
return True
return False
return True
main()
init()
draw()
move()
draw()
When I want to move 2 or 3 for instance, I keep getting "IndexError: list index out of range":
Erorr message:
python3 fifteen.py 3
Traceback (most recent call last):
File "fifteen.py", line 83, in <module>
move()
File "fifteen.py", line 72, in move
elif board[rowdown][col] == 0 and rowdown < d:
IndexError: list index out of range
What do I have to do to make this work properly?
because rowdown and colright could be bigger than the max index of your board.
for example, d = 3.
when row = 2, rowdown = 3 which is out of index of board.

Resources