Question

Here is my code for minesweeper in python and it has something wrong. Could you please help me to fix it?->93 ms-Minesweeper() ipython-input-10-5363c27af02c> ininit (self) self.main.title(mine sweeper) self.define widgets () sel

import tkinter as tk
import random

class Minesweeper:
def __init__(self):
self.main = tk.Tk()
self.main.title("mine sweeper")
self.define_widgets()
self.mines = random.sample( [(i,j) for i in range(25) for j in range(50) ],self.CustomizeNumberOfMines())
print(self.mines)
self.main.mainloop()
self.CustomizeNumberOfMines()

def define_widgets(self):
""" Define a canvas object, populate it with squares and
possible texts """
self.canvas = tk.Canvas(self.main, width = 1002, height=502,
bg="#f0f0f0")
self.canvas.grid(row=0, column=0)
self.boxes = [ [ ] for _ in range(25) ]
self.texts = [ [ ] for _ in range(50) ]
for i in range(25):
for j in range(50):
box = self.canvas.create_rectangle(3+j*20, 3+i*20, 20+j*20,
20+i*20)
self.boxes[i].append(box)
text = self.canvas.create_text(
11+j*20, 11+i*20, text="?",
width = 8)
self.texts[i].append(text)
# self.canvas.itemconfig(self.boxes[3][7], fill = "blue")
# self.canvas.delete(self.texts[3][5])
# self.canvas.itemconfig(self.texts[2][2], text="9", fill = "red")
self.canvas.bind('<Button-1>', self.handler)

def handler(self, event):
row = (event.y-2)//20
column = (event.x-2)//20
if (row, column) in self.mines:
self.canvas.create_text(100, 100, text="Boom",
font= ("Helvetica", 40))
self.canvas.delete(self.boxes[row][column])
self.canvas.itemconfig(self.texts[row][column], text=
str(self.nr_mines(row, column)), fill = "red")
  

def neighboring(ii, jj):
""" returns a list of all neighboring cells"""
maxrow, maxcol = 25, 50
return [ (i,j) for i in range(ii-1, ii+2) for j in range(jj-1, jj+2) if
i>=0 and i<maxrow and j>=0 and j<maxcol and not (i==ii and j==jj) ]

def nr_mines(self, row, column):
count = 0
for field in Minesweeper.neighboring(row, column):
if field in self.mines:
count+=1
if (row, column) in self.mines:
count+=1
return count
  
def CustomizeNumberOfMines(self):
while True:
numberOfMinesString = input("Enter number of mines: ")
try:
self.numberOfMines = int(numberOfMinesString)
if self.numberOfMines < 1:
print("Too few mines!")
else:
break
except:
self.InvalidResponseMessage()
  
def AskIfPlayAgain(self):
while True:
playAgain = (input("Do you want to play again? y/n ")).lower()
if playAgain == "y":
break
elif playAgain == "n":
self.ShutDown()
else:
self.InvalidResponseMessage()
  
def ShutDown(self):
print("Good bye!")
exit()
  
def rClick(self, event):
self.button.config(bg="#FFCC00", text="?")
  
  

ms = Minesweeper()

0 0
Add a comment Improve this question Transcribed image text
Answer #1

As you have not provided the intended code so there was difficulty to run whole program.

But I am able to remove your error. The problem is in

self.mines = random.sample( [(i,j) for i in range(25) for j in range(50) ],self.CustomizeNumberOfMines())

Now here you are calling a function but not returning any value to it takes null value and throws the error you are getting.

I updated the code for the function. Check below :

def CustomizeNumberOfMines(self):
while True:
numberOfMinesString = input("Enter number of mines: ")
try:
self.numberOfMines = int(numberOfMinesString)
if self.numberOfMines < 1:
print("Too few mines!")
else:
return int(numberOfMinesString)
except:
self.InvalidResponseMessage()
#here return default value

Please uprate.

Output :

mine sweeper

Add a comment
Know the answer?
Add Answer to:
Here is my code for minesweeper in python and it has something wrong. Could you please help me to fix it? import tkinter as tk import random class Minesweeper: def __init__(self): self.main = tk.Tk()...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please use my code to implement the above instructions. My Grid class: import java.util.ArrayList; import java.util.Collections;...

    Please use my code to implement the above instructions. My Grid class: import java.util.ArrayList; import java.util.Collections; class Grid { private boolean bombGrid[][]; private int countGrid[][]; private int numRows; private int numColumns; private int numBombs; public Grid() { this(10, 10, 25); }    public Grid(int rows, int columns) { this(rows, columns, 25); }    public Grid(int rows, int columns, int numBombs) { this.numRows = rows; this.numColumns = columns; this.numBombs = numBombs; createBombGrid(); createCountGrid(); }    public int getNumRows() { return numRows;...

  • 9p This is for Python I need help. Pet #pet.py mName mAge class Pet: + __init__(name,...

    9p This is for Python I need help. Pet #pet.py mName mAge class Pet: + __init__(name, age) + getName + getAge0 def init (self, name, age): self.mName = name self.mAge = age Dog Cat def getName(self): return self.mName mSize mColor + __init__(name, age,size) + getSize() + momCommento + getDog Years() +_init__(name, age,color) + getColor + pretty Factor + getCatYears def getAge(self): return self.mAge #dog.py import pet #cat.py import pet class Dog (pet. Pet): class Cat (pet. Pet): def init (self,...

  • PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please...

    PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please so I can understand LinkedList ADT: class myLinkedList:     def __init__(self):         self.__head = None         self.__tail = None         self.__size = 0     def insert(self, i, data):         if self.isEmpty():             self.__head = listNode(data)             self.__tail = self.__head         elif i <= 0:             self.__head = listNode(data, self.__head)         elif i >= self.__size:             self.__tail.setNext(listNode(data))             self.__tail = self.__tail.getNext()         else:             current = self.__getIthNode(i - 1)             current.setNext(listNode(data,...

  • PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment...

    PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment the lines please so I can understand. There are short and med files lengths for each the list of names/ids and then search id file. These are the input files: https://codeshare.io/aVQd46 https://codeshare.io/5M3XnR https://codeshare.io/2W684E https://codeshare.io/5RJwZ4 LinkedList ADT to store student records(code is below). Using LinkedList ADT instead of the Python List. You will need to use the Student ADT(code is below) Imports the Student class...

  • hello good night, could you help me to see what is wrong with my code, two...

    hello good night, could you help me to see what is wrong with my code, two errors appear at the bottom in red: In [47]: file_contents-open("color-blanco.png") def calculate_frequencies (file_contents): # Here is a list of punctuations and uninteresting words you can use to process your text punctuations = ""!()-[]{};:"",-./?@#$%^&*_~ uninteresting_words = ["the","in" ,"a", "to", "if", "is", "it", "of", "and", "or", "an", "as", "i", "me", "my", "we", "o # LEARNER CODE START HERE result={} a-file_contents.split() for word in a: if word...

  • In this part, you will complete the code to solve a maze.

    - Complete the code to solve a maze- Discuss related data structures topicsProgramming-----------In this part, you will complete the code to solve a maze.Begin with the "solveMaze.py" starter file.This file contains comment instructions that tell you where to add your code.Each maze resides in a text file (with a .txt extension).The following symbols are used in the mazes:BARRIER = '-' # barrierFINISH = 'F' # finish (goal)OPEN = 'O' # open stepSTART = 'S' # start stepVISITED = '#' #...

  • If anyone can please convert from Java to python. Thank you!! import javax.swing.*; import javax.swing.event.*; import...

    If anyone can please convert from Java to python. Thank you!! import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class CalenderProgram{ static JLabel lblMonth, lblYear; static JButton btnPrev, btnNext; static JTable tblCalendar; static JComboBox cmbYear; static JFrame frmMain; static Container pane; static DefaultTableModel mtblCalendar; //Table model static JScrollPane stblCalendar; //The scrollpane static JPanel pnlCalendar; static int realYear, realMonth, realDay, currentYear, currentMonth;    public static void main (String args[]){ //Look and feel try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());} catch (ClassNotFoundException...

  • I need help fixing this code and adding a loop please. Here is the original problem: #include <iostream> using namespace std; //function to print seating chart void printSeatingChart(int **cha...

    I need help fixing this code and adding a loop please. Here is the original problem: #include <iostream> using namespace std; //function to print seating chart void printSeatingChart(int **chart) {    int i, j;    cout << "\nROW\t";    for (i = 1; i <= 10; i++)    {        cout << i << "\t";    }    cout << "\n-----------------------------------------------------------------------------------\n";    for (i = 8; i >= 0; i--)    {        cout << "\n" << i + 1 << "\t";        for (j = 0; j < 10; j++)       ...

  • My Python file will not work below and I am not sure why, please help me...

    My Python file will not work below and I am not sure why, please help me debug! ********************************* Instructions for program: You’ll use these functions to put together a program that does the following: Gives the user sentences to type, until they type DONE and then the test is over. Counts the number of seconds from when the user begins to when the test is over. Counts and reports: The total number of words the user typed, and how many...

  • Below is my code please help me edit it so in the beginning it ask for Press any key to start Tas...

    below is my code please help me edit it so in the beginning it ask for Press any key to start Task n, where n is the task number (1, 2, or 3,4). I already wrote the code for the 4 task. Also please write it so when 1 code is finish running it return to the prompt where it ask to run another task #task 1 list1 = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','.',',','?'] morse = ['.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..','-----','.----','..---','...--','....-','.....','-....','--...','---..','----.','.-.-.-','--..--','..--..'] inp = input("Enter original text : ")...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT