Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Gomoku game problem
#1
import pygame
pygame.init()

#game constants
WINDOW_SZ = 720
BOARD_SZ = 16
COLOR = [(255,255,255),(0,0,0)]
LINE_COLOR = (0,0,0)
BOARD_COLOR = (204, 154, 104)

#The chessboard data structure, with a default state of 0,
#where the player is 1 and the computer is -1
board = [[0 for _ in range(BOARD_SZ+1)]
                for _ in range(BOARD_SZ+1)
                ]
#the image of board
black = pygame.image.load("date/black.png")
white = pygame.image.load("date/white.png")

#“Map the player and computer onto the image,
#with the player defaulting to white and the computer to black
dic = {
        1:white,
        -1:black
        }
#set clock
clock = pygame.time.Clock()

#set font
fps_font = pygame.font.SysFont(None,15)
char_font = pygame.font.SysFont(None,25)
error_font = pygame.font.SysFont(None,25)

#condition judgement
player_turn = True
player_score = 0
computer_score = 0
game_over = False
winner = None
error_message = None
error_start_time = 0

def transform(picture,sqare_sz):
    """
    Scale the image to match the grid
    """
    new_image = pygame.transform.smoothscale(picture,(sqare_sz*0.85,sqare_sz*0.85))
    return new_image

def draw_line(sz,sqare_sz,color,surface):
    """draw the grid"""
    for i in range(1,sz):
        char =  char_font.render('{}'.format(i),True,color)
        pygame.draw.line(surface,color,(i*sqare_sz,sqare_sz),(i*sqare_sz,(sz - 1)*sqare_sz),3)
        pygame.draw.line(surface,color,(sqare_sz,i*sqare_sz),((sz - 1)*sqare_sz,i*sqare_sz),3)
        surface.blit(char,(i*sqare_sz-(char.get_width() // 2),sqare_sz-20))
        surface.blit(char,(sqare_sz-20,i*sqare_sz-(char.get_height()) // 2))
    return surface

def low(value,col,row,sqare_sz,surface):
    """Put the pieces on the board"""
    new_picture = transform(dic[value],sqare_sz)
    rect = new_picture.get_rect(center = (col*sqare_sz,row*sqare_sz))
    surface.blit(new_picture,rect)
    return surface

def draw_picture(sz,sqare_sz,board,surface):
    """
    draw the board
    """
    for row in range(1,sz):
        for col in range(1,sz):
            value = board[row][col]
            if value == 1 or value == -1:
                low(value,col,row,sqare_sz,surface)

def distance(p1,p2,radius):
    """Judge the distance"""
    import math
    dx = abs(p1[0]-p2[0])**2
    dy = abs(p1[1]-p2[1])**2
    if math.sqrt(dx + dy) <= radius:
        return True
    return False


def scope_of_circle(sz,sqare_sz,picture,cur_pos):
    """ Circular Region of Interest"""
    for row in range(1,sz):
        for col in range(1,sz):
            circle_center = (col*sqare_sz,row*sqare_sz)
            radius = sqare_sz // 2
            if distance(circle_center,cur_pos,radius):
                return (row,col)

def move_of_computer(sz,board):
    """the movement of computer in each turn"""
    import random
    empty = []
    for row in range(1,sz):
        for col in range(1,sz):
            if board[row][col] == 0:
                empty.append((row,col))
    result = random.choice(empty)
    return result

def get_point():
    """ Determine the player’s/computer's scoring conditions"""
    pass

def main():
    """
    main floo in game
    """
    global game_over,player_turn,winner,player_score,computer_score,error_message,error_start_time

    #Initialize window
    CHANCE = 0
    sqare_sz = WINDOW_SZ // BOARD_SZ
    adjusted_sz = sqare_sz * BOARD_SZ
    window = pygame.display.set_mode((adjusted_sz,adjusted_sz))
    pygame.display.set_caption('Gomoku game')
    running = True
    while running:
        clock.tick(60)
        fps_text = fps_font.render('Current: {:.2f} FPS'.format(clock.get_fps()),
                                   True,(0,0,0) )
        rate_text = fps_font.render('RunTime: {:.2f} s'.format(pygame.time.get_ticks()//1000),
                                   True,(0,0,0) )
        window.fill(BOARD_COLOR)
        window.blit(fps_text,(10,10))
        window.blit(rate_text,(120,10))
        draw_line(BOARD_SZ,sqare_sz,LINE_COLOR,window)
        draw_picture(BOARD_SZ,sqare_sz,board,window)
        #Error message for incorrect move
        if error_message:
            now = pygame.time.get_ticks()
            if now - error_start_time  < 3000:
                error = error_font.render(error_message, True, (255,0,0))
                rect = error.get_rect(center=(adjusted_sz // 2, adjusted_sz // 2))
                window.fill((125,125,125),(160,310,400,100))
                window.blit(error, rect)
                pygame.display.flip()

            else:
                error_message = None   #Automatically clears after three seconds
        for event in pygame.event.get():
            #if event.type != pygame.NOEVENT:
                #print(event)
            if event.type == pygame.QUIT:
                running = False
                break
            if not game_over and event.type==pygame.MOUSEBUTTONDOWN and player_turn:
                #player's turn
                (x,y) = pygame.mouse.get_pos()
                result = scope_of_circle(BOARD_SZ,sqare_sz,black,(x,y))
                if result:
                        (row,col) = result
                        if board[row][col] == 0:
                            board[row][col] = 1
                            #the player’s score exceeds the computer’s score by 20 points,
                            #game is immediately returned
                            if player_score - computer_score > 20:
                                winner = 'PLAYER!'
                                game_over = True
                            #elif get_points():
                                #pass
                            CHANCE = 0
                        else:
                            CHANCE += 1
                            if CHANCE % 3 != 0:
                                error_message =  'here is already a piece here, please try again.'
                                error_start_time = pygame.time.get_ticks()
                                continue
                            CHANCE = 0
                            error_message = 'You have wasted three opportunities.Turn the computer'
                            error_start_time = pygame.time.get_ticks()

                        player_turn = False

            if not game_over and not player_turn:
                #trun of computer
                (x,y) = move_of_computer(BOARD_SZ,board)
                board[x][y] = -1
                player_turn = True
                pass
            if game_over:
                pass
        pygame.display.update()
    pygame.quit()
    pass

if __name__ == '__main__':
    main()
Hello, above is the Gomoku game code I wrote. I've encountered a problem that's difficult for me to solve, which is how to determine whether the player or the computer scores. According to the game rules, when five pieces are in the same column, the same row, or the same diagonal, the player (or computer) scores. However, my data structure is a two-dimensional matrix, and the probability of scoring seems to be related to the position of the pieces. I don't know how to implement it in a programming language, and I'm completely at a loss.
If you are willing to help me, I would be extremely grateful.

Attached Files

.zip   gomokuame.zip (Size: 33.15 KB / Downloads: 11)
Reply
#2
Describing the problem clearly and succinctly is the first step to writing code.
Reply
#3
Smile 
I apologize for the confusion in my description. Currently, I am facing an issue where I am developing a Gomoku (Five in a Row) game, and I am using a two-dimensional array to manage the board data.

board = [  [0 for _ in range(17)]
                 for _ in range(17)]    
This is a 16x16 grid, and the default state of each intersection is 0, indicating that there is no piece at that position.
Player's turn:
When the player clicks on one of the intersections, two situations will be detected:
First situation: If there is a piece at the current position (not equal to zero), an error will be reported. When the error reaches three times, the control will be transferred to the computer.
Second situation: If there is no piece at the current position, the state will be changed to 1, and then the following situations will be checked one by one:
Situation A - Check win/loss: If the player's score is higher than the computer's score, the game is won directly.
Situation B - Determine the position of the pieces. If there are pieces in the same column, same row, or same diagonal, the
player gets five points, the pieces are removed, and the player continues to play;
If the above conditions are not met, it is the computer's turn.

Computer's turn:
The computer will change the state of the board to -1, and the win/loss logic is the same.

Example: For example, at the beginning of the game, the player goes first and clicks on the position of the fifth row and sixth column. The data of the fifth row and sixth column of the board will become 1, and then it will check if there are five pieces in the fifth row, sixth column, or diagonal. If so, the player gets +5 points, these pieces are removed, and the player continues the turn. If not, the control is transferred, and it is the computer's turn.
My game logic is basically like this, and the problem I encountered is how to determine if there are five pieces in
1.The same row
2.The same column
3.The diagonal
Just like in the example above. After I click on the fifth row and sixth column, how can I make it detect the above conditions?
I apologize if you find my description a bit confusing. That is entirely my fault. English is not my native language, and I used a translation software to translate it.
Thank you for your patience in reading this.
Reply
#4
Your code makes a 17x17 grid.

I was not asking for a description of the game. I want a description of how you detect that a move resulted in a win. Pretend you were describing the rules to someone who didn’t understand what “5 pieces in the diagonal” meant. Define diagonal in terms of rows and columns. Most of programming is understanding the problem and solution. Once you have that, the coding is easy.
Reply
#5
(Yesterday, 12:56 PM)deanhystad Wrote: Your code makes a 17x17 grid.

I was not asking for a description of the game. I want a description of how you detect that a move resulted in a win. Pretend you were describing the rules to someone who didn’t understand what “5 pieces in the diagonal” meant. Define diagonal in terms of rows and columns. Most of programming is understanding the problem and solution. Once you have that, the coding is easy.
Thank you very much. I think I have some ideas now,but I really feel that programming is not as simple for me as you described Cry Confused
Reply
#6
That is because you start programming before you really understand the solution. My primary programming tools are notebook and pencil. They are better design tools than keyboard and monitor. You have to do design sometime. If you don't put in the time before you start typing, you're stuck doing design with tools not really fit for the job and using a language you're not comfortable with.
Reply
#7
(Yesterday, 03:50 PM)deanhystad Wrote: That is because you start programming before you really understand the solution. My primary programming tools are notebook and pencil. They are better design tools than keyboard and monitor. You have to do design sometime. If you don't put in the time before you start typing, you're stuck doing design with tools not really fit for the job and using a language you're not comfortable with.
Do you have any recommended books and learning videos?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Stacking Problem in a game. HelloTobi22 2 1,839 Aug-05-2022, 09:48 AM
Last Post: HelloTobi22
  Problem with my pong game code Than999 8 6,022 May-15-2022, 06:40 AM
Last Post: deanhystad
  Problem restricting user input in my rock paper scissors game ashergreen 6 6,544 Mar-25-2021, 03:54 AM
Last Post: deanhystad
  Guessing game problem IcodeUser8 7 5,661 Jul-19-2020, 07:37 PM
Last Post: IcodeUser8
  Python Hangman Game - Multiple Letters Problem t0rn 4 6,407 Jun-05-2020, 11:27 AM
Last Post: t0rn
  game of the goose - dice problem koop 4 4,629 Apr-11-2020, 02:48 PM
Last Post: ibreeden
  Dice Throwing Game in Python (I have a problem) yuseinali 1 3,704 Jun-22-2017, 10:22 PM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020