logo
down
shadow

Trouble with sudoku game in python 3.3.4


Trouble with sudoku game in python 3.3.4

By : Chao Gao
Date : November 21 2020, 12:01 PM
I wish did fix the issue. No offense intended, but your code was just too complex to understand easily. Below is an optimized version of what you are trying to do. It is not a complete solution, however, because a Sudoku game apparently cannot be created completely randomly as this program illustrates. I hope what you can take from this is not the solution as handed to you, but a means to understand how math, loops, and functions can aid in readability, optimization, and simplicity. Try to understand what I did here and not simply use it. Then, perhaps you can further find ways to improve it to actually do what you want to do. It does solve your '1' problem though. It just may not solve your 5 and up problem :-D. Good luck and I hope this helps!!
code :
#sudoku game
from random import randint

#generate board
def build_board():
    board=[]
    for i in range(9):
        block=[[" "," "," "],
               [" "," "," "],
               [" "," "," "]]
        board.append(block)
    return board


##
## Ensure no other block in the same row has the value
##
def row_available(block, row, board, num):
    # Determine which of the main 3 rows this 3x3 block is at
    boardRow = int(block / 3);
    good = True
    for b in range(boardRow * 3, (boardRow * 3) + 3):
        if b != block:
            if num in board[b][row]:
                good = False
                break
    return good


##
## Ensure no other block in the same col has the value
##
def col_available(block, row, col, board, num):
    # Determine which of the main 3 columns this 3x3 block is at
    boardCol = block % 3;
    good = True
    for b in (boardCol, boardCol + 3, boardCol + 6):
        if b != block:
            if num == board[b][row][col]:
                good = False
                break
    return good


def fill_board(board):
    # to fill all numbers 1 through 9
    for num in range(1,10):
        # for each of the 9 3x3 blocks
        for block in range(len(board)):
            triedRow = [-1]
            foundSpot = False
            for i in range(3):
                row = -1
                while row in triedRow:
                    row = randint(0,2)
                triedRow.append(row)
                if " " in board[block][row] and row_available(block, row, board, num):
                    triedCol = [-1]
                    for j in range(3):
                        col = -1
                        while col in triedCol:
                            col = randint(0,2)
                        triedCol.append(col)
                        if " " == board[block][row][col] and col_available(block, row, col, board, num):
                            board[block][row][col] = num
                            foundSpot = True
                        if foundSpot:
                            break
                if foundSpot:
                    break
            if not foundSpot:
                print("Never Found a Spot for " + str(num) + " in block " + str(block))
    return board


#display board
def display(board):
    num=[]
    for i in board: #block level
        for subI in i: #row
            for subsubI in subI: #item
                num.append(subsubI)
    print("---------------------------------------")
    print("| {} | {} | {} || {} | {} | {} || {} | {} | {} |".format(num[0],num[1],num[2],num[9],num[10],num[11],num[18],num[19],num[20]))
    print("---------------------------------------")
    print("| {} | {} | {} || {} | {} | {} || {} | {} | {} |".format(num[3],num[4],num[5],num[12],num[13],num[14],num[21],num[22],num[23]))
    print("---------------------------------------")
    print("| {} | {} | {} || {} | {} | {} || {} | {} | {} |".format(num[6],num[7],num[8],num[15],num[16],num[17],num[24],num[25],num[26]))
    print("---------------------------------------")
    print("---------------------------------------")
    print("| {} | {} | {} || {} | {} | {} || {} | {} | {} |".format(num[27],num[28],num[29],num[36],num[37],num[38],num[45],num[46],num[47]))
    print("---------------------------------------")
    print("| {} | {} | {} || {} | {} | {} || {} | {} | {} |".format(num[30],num[31],num[32],num[39],num[40],num[41],num[48],num[49],num[50]))
    print("---------------------------------------")
    print("| {} | {} | {} || {} | {} | {} || {} | {} | {} |".format(num[33],num[34],num[35],num[42],num[43],num[44],num[51],num[52],num[53]))
    print("---------------------------------------")
    print("---------------------------------------")
    print("| {} | {} | {} || {} | {} | {} || {} | {} | {} |".format(num[54],num[55],num[56],num[63],num[64],num[65],num[72],num[73],num[74]))
    print("---------------------------------------")
    print("| {} | {} | {} || {} | {} | {} || {} | {} | {} |".format(num[57],num[58],num[59],num[66],num[67],num[68],num[75],num[76],num[77]))
    print("---------------------------------------")
    print("| {} | {} | {} || {} | {} | {} || {} | {} | {} |".format(num[60],num[61],num[62],num[69],num[70],num[71],num[78],num[79],num[80]))
    print("---------------------------------------")  

#test
board=build_board()
board=fill_board(board)
display=display(board)
Never Found a Spot for 5 in block 5
Never Found a Spot for 9 in block 4
---------------------------------------
| 7 | 9 | 1 || 4 | 6 | 8 || 5 | 3 | 2 |
---------------------------------------
| 6 | 8 | 3 || 2 | 5 | 9 || 4 | 1 | 7 |
---------------------------------------
| 2 | 5 | 4 || 3 | 7 | 1 || 8 | 6 | 9 |
---------------------------------------
---------------------------------------
| 3 | 2 | 9 || 7 | 8 |   || 6 | 4 | 1 |
---------------------------------------
| 1 | 7 | 6 || 5 | 3 | 4 || 9 | 8 | 2 |
---------------------------------------
| 8 | 4 | 5 || 6 | 1 | 2 ||   | 7 | 3 |
---------------------------------------
---------------------------------------
| 4 | 3 | 6 || 5 | 9 | 2 || 7 | 1 | 8 |
---------------------------------------
| 5 | 1 | 2 || 3 | 7 | 8 || 6 | 9 | 4 |
---------------------------------------
| 7 | 9 | 8 || 1 | 6 | 4 || 5 | 3 | 2 |
---------------------------------------


Share : facebook icon twitter icon
sudoku game constructor

sudoku game constructor


By : Michael
Date : March 29 2020, 07:55 AM
wish of those help I am having trouble initializing a parameterless constructor with a defined game. Somehow it keeps on returning null if I use a getter method to return the game. Can anyone tell me what would be the best method to initialize the game? , You are hiding the instance variable.
Change the following
code :
int[][] game = new int[GRID_SIZE][GRID_SIZE];
game = new int[GRID_SIZE][GRID_SIZE];
4 by 4 Sudoku game

4 by 4 Sudoku game


By : E. Smirnovsky
Date : March 29 2020, 07:55 AM
hope this fix your issue I have an assignment that is making a processing sketch that make 4 by 4 Sudoku game and make the player enter the missing numbers to the playing grid, the problem that I'm facing now is to make a loop or something that allow the player to enter ALL the missing numbers ? I'd Succeeded to allow the player to enter the first 4 numbers using switch statement and if statement but the program only go through the first if statement from each case, and I want to make it go through the rest ? here is the cod that I make. , I have gone through your code, and observed some issues:
code :
// GLOBAL VARS DECLARATION
int[][] resultsValue = {
  {1,2,3,4},
  {3,4,1,2},
  {2,3,4,1},
  {4,1,2,3}};
boolean[][] resultsSolved = new boolean[4][4];
int cellsX = 4;
int cellsY = 4;
float cellSize = 30; 
float xPos = 0;
float yPos = 0;

void setup ()
{
  background (255);
  size (130, 130);
  smooth();

  // GLOBAL VARS VALUE ASSIGNMENT            
  resultsSolved[0][2] = true;
  resultsSolved[1][1] = true;
  resultsSolved[2][2] = true;
  resultsSolved[3][3] = true;
}

void draw ()
{
  background(255);

  drawBoard(cellsX, cellsY, cellSize, xPos, yPos, 2);

  pushStyle();
  fill (0);
  textSize(28);

  for (int i = 0; i < 4; i++) {
    for (int j = 0; j < 4; j++) {
      if (resultsSolved[i][j] == true) {
         text(resultsValue[i][j], 5 + xPos + j * cellSize, -5 + yPos + (i + 1) * cellSize);
      }
    }
  }

  popStyle();

  if (mousePressed)
  {
    mouseClicked ();
  }

}

/*------------------------------------------------------------------------------------------*/

void drawBoard(int rows, int cols, float cellSize, float xPos, float yPos, int cellBlocks) {
  pushStyle();
  noFill();
  stroke(0);
  strokeWeight(1);

  // DRAW RECTANGLES
  for (int i = 0; i < cols; i++) {
    for (int j = 0; j < rows; j++) {
      rect(xPos + i * cellSize, yPos + j * cellSize, cellSize, cellSize);
    }
  }

  strokeWeight(3);

  // DRAW LINES
  for (int i = 0; i < cols / cellBlocks; i++) {
      line(xPos + i * cellSize * cellBlocks, yPos, xPos + i * cellSize  * cellBlocks, yPos + rows * cellSize); 
  }
  for (int i = 0; i < rows / cellBlocks; i++) {
      line(xPos, yPos + i * cellSize * cellBlocks, xPos + cols * cellSize, yPos + i * cellSize * cellBlocks); 
  }

  popStyle();
} 

void mouseClicked ()
{
  int cellX = (int) ((mouseX - xPos) / cellSize); 
  if (cellX > cellsX - 1) cellX = cellsX - 1;
  else if (cellX < 0) cellX = 0;

  int cellY = (int) ((mouseY - yPos) / cellSize); 
  if (cellY > cellsY - 1) cellY = cellsY - 1;
  else if (cellY < 0) cellY = 0;

  int lastKeyInt = int(key - '0');

  if (resultsValue[cellY][cellX] == lastKeyInt) {
    resultsSolved[cellY][cellX] = true;
  }
}
Having trouble starting the game in python. The game never starts and the error below shows up

Having trouble starting the game in python. The game never starts and the error below shows up


By : andromara
Date : March 29 2020, 07:55 AM
help you fix your problem In python I'm trying to create a simple game where the player chooses what cave to go to next, while trying to avoid the wumpus. While setting up the initial cave structure it somehow stops and never starts the game, with the following error: , First:
code :
visited_caves = []
link_caves()
this_cave = choose_cave(visited_caves)
cave_number = choice(cave_list)
def link_caves():
    """ make sure all of the caves are connected with two way tunnels"""
    if not (visited_caves and unvisited_caves):
        return
    this_cave = choose_cave(visited_caves)
    next_cave = choose_cave(unvisited_caves)
    create_tunnel(this_cave, next_cave)
    visit_cave(next_cave)
Trouble with game over screen for Python game with Pygame

Trouble with game over screen for Python game with Pygame


By : Siva Subramani
Date : March 29 2020, 07:55 AM
help you fix your problem You've 2 functions main() and game_over(), each has its own event loop and does its own drawing.
Create 2 state variables. The first state (run), indicates if the game has to be continued or be terminated.
code :
run = True
gameover = False
while run:
    if not gameover:
        run, gameover = main()
    else:
        run, gameover = game_over()
        if not gameover:
            snake_pos = [100, 100]
            snake_body = [[100, 100], [90, 100], [80, 100]]
            snake_speed = 10
            apple_pos = [random.randrange(1,60)*10, random.randrange(1,60)*10]
            apple_spawn = True
            direction = RIGHT
            update = direction
            scoreval = 0
def game_over():

    screen.fill(LIGHTBLUE)
    draw_text("GAME OVER", 48, WHITE, screen_width/2, screen_height/4)
    draw_text("Score: " + str(score), 22, WHITE,  screen_width / 2, screen_height / 3)
    draw_text("Press SPACE to play again or ESC to exit", 22, WHITE, screen_width/2, screen_height / 4)
    pygame.display.update()
    fps_controller.tick(25)

    rungame = True 
    continuegame = False 
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            rungame  = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                continuegame = True
            if event.key == pygame.K_ESCAPE:
                rungame = False
    return rungame, not continuegame
def main():
    global update, direction, snake_pos, snake_speed, apple_spawn, apple_pos
    pygame.time.delay(60)

    rungame = True
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            rungame = False

    # [...]

    collision = False
    if snake_pos[0] < 0 or snake_pos[0] > screen_width-20:
        collision = True
    if snake_pos[1] < 0 or snake_pos[1] > screen_height-20:
        collision = True

    for block in snake_body[1:]:
        if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
            collision = True

    score(scoreval)
    pygame.display.update()
    fps_controller.tick(25)

    return rungame, collision
android sudoku game, button press crashes the game

android sudoku game, button press crashes the game


By : vuioap1042
Date : March 29 2020, 07:55 AM
To fix the issue you can do I'm creating a sudoku game, but when i press the button it crashes the game. Here's my code: , Hidden in your LogCat is the answer to your question:
Related Posts Related Posts :
  • Filtering from data
  • Where is the problem about selenium with python?
  • ansible custom filter fails when importing python library
  • How to assign the label of one column to the new one based on group maximum in pandas
  • What is the best approach for isolating a single area of similar colour?
  • Creating multiple clients for topics
  • Why is my 'for loop', despite iterating over all keys, only acting on the last one?
  • Can someone tell me what's wrong, when I run it the browsers says "This site can’t be reached"
  • Error in setting up mitmproxy on alpine 3.9
  • From traditional loop to list comprehension
  • Django celery unregistered task | relative imports
  • How to add elements in a multi dimensional array
  • Async await with sqs receive messages not working properly
  • What is definition of 'NAME' in Python grammar
  • Easy method to move rows from df to another with coditions?
  • Changing the size of only a single plot in matplotlib, without altering figure parameters
  • Fastest way to use Vision API on 10,000+ images with python
  • How to install nvidia apex on Google Colab
  • Random numbers Continuous in python
  • Fetching data after a certain time interval(10 sec) from a continuously increasing database like mysql using flask
  • Using VLOOKUP with merge in Python
  • Calculate geographical distance between 5 cities with all the possible combinations of each city
  • How to filter a pandas dataframe using multiple partial strings?
  • Pygame- make bullet shoot toward cursor direction
  • Create SEQUENCE based dictionary from list
  • How to fix broken link from Django MEDIA_ROOT?
  • How can I display the current time left in a timer in a label?
  • Compute number of occurance of each value and Sum another column in Pandas
  • How to separate the prefix in words that are 'di'?
  • Handling network errors from an external API across an application
  • Want a pandas Series of Trips Completed to count(Request) ratio for each hour as index for the given dataframe
  • Access dict keys and list elements by same index to loop over and assign values
  • Find rows from the same dataframe based on condition
  • Read only specific part first two lines from text file in python
  • Python How to convert string to dataframe?
  • How to fix this my error code program? I use Python 3.6
  • Is there a way of getting this string down to 3 words?
  • Large difference between overall F Score for a custom Spacy NER model and Individual Entity F Score
  • Drop rows where timestamps are older than subsequent row
  • Implement a bottle spin
  • Unable to convert widows epoch time to normal date time
  • Values from a XML file
  • PyAudio readframes not ending when wav file completes
  • Could not load the module
  • How to change datetime.datetime(2012, 1, 1, 0, 0) to 1/1/2012 in Python?
  • How to create ASN.1 Sequence without NamedType?
  • How to locate specific sequences of words in a sentence efficiently
  • How can I generate a multi-step process in Django without changing pages (w/out a new request)?
  • Why does this list comprehension only "sometimes" work?
  • send html report with row collapsed
  • How to define a type hint to a argument (the argument's value is a class, all expected value is a subclass of a certain
  • How do I send a styled pandas DataFrame by e-mail without losing the format?
  • How to view/average a groupby dataframe when the data is a string?
  • Django 2.2 staticfiles do not work in development
  • Flag to enable/disable numba JIT compilation?
  • Trying to split byte in a byte array into two nibbles
  • Error in Query - missing FROM-clause entry for table - SQL
  • Reading double c structures of Dll with Ctypes in Python
  • Autofill missing row in database based on missing time range
  • Get the max of a nested dictionary
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org