Pygame dice roller

Question:

I’d like to have the dice roll, and then player 1 move forward as many spaces as the dice rolls on. Currently, this is the starting code with the grid and the squares along with the numbers.

import pygame
import random 

w_in_squares = 7
h_in_squares = 6
square_dim   = 50

blue  = (47,134,150)
white = (255, 255, 255)
black = (0,0,0)
red   = (255,0,0)

def Draw_Checker_Board( window, number_font ):
    

    #7x6 checkbaord
    number = 1
    current_colour = white

    for i in range(0, h_in_squares):
        tl_corner_y = i * square_dim     # top-left corner Y coordinate
        for j in range(0, w_in_squares):
            if current_colour == white:
                current_colour = black
            else:
                current_colour = white
            tl_corner_x = j * square_dim  # top-left corner X coordinate

            rectangle = ( tl_corner_x, tl_corner_y, square_dim, square_dim)   # rectangle defining checker
            pygame.draw.rect( window, current_colour, rectangle )             # paint the rectangle
            number_bitmap = number_font.render( str(number), True, blue )     # create the number
            number += 1
        
            margin = 10
            window.blit( number_bitmap, ( tl_corner_x + margin, tl_corner_y + margin ) )  

Asked By: azhua123

||

Answers:

It’s not really clear what you need here, the code does not do what’s described. So I’ve re-arranged it, moved some code into a function, and "made it work" somewhat.

So, to address the changes:

  • All constants to be named in capitals. This is a very common convention in programming.
    • I pushed them all to the same place in the code, too.
  • Changed the grid from being 6×7 to 7×6, otherwise you get columns of colour. If you did want coloured columns, just change that back.
  • Moved the drawing of the chequered board pattern into a function
  • Reworked the main loop to paint the Board, update the window, limit the frame-rate, etc..

The biggest change is obviously moving the drawing of the board into a function. This is desirable because it "compartmentalises" everything about drawing a numbered, chequered board into a single place, which can later be called with a single statement.

If the code does not define functions / procedures like this, it would end-up unwieldy, (with probably repeated) lumps of code all over the place. Either that, or "goto" instructions to branch the program’s execution.

Where I think you should go from here:

  • Store your player information (colour, position) in a data structure, say a Python List
    • For example: player1 = [ RED, 1 ]
  • Write another function drawPlayer() that given a window and player, "knows" how to draw that player’s circle in the correct square by taking elements from the Player data structure (list).
    • Obviously this new drawPlayer() function would be called during the main loop, similar to how the Board drawing function is.

Once this part is working OK, then look at how you want to implement the dice-rolling. Please feel free to ask another question at this time.

screen shot

import pygame
import random

W_IN_SQUARES = 7
H_IN_SQUARES = 6
SQUARE_DIM   = 50

BLUE  = (47,134,150)
WHITE = (255, 255, 255)
BLACK = (0,0,0)
RED   = (255,0,0)

def drawCheckerBoard( window, number_font ):
    """ Draw a checker-board alternating-coloured square pattern
        to the given window surface.  Put a number into each square """

    #7x6 checkbaord
    number = 1
    current_colour = WHITE

    for i in range(0, H_IN_SQUARES):
        tl_corner_y = i * SQUARE_DIM      # top-left corner Y coordinate
        for j in range(0, W_IN_SQUARES):
            if current_colour == WHITE:
                current_colour = BLACK
            else:
                current_colour = WHITE
            tl_corner_x = j * SQUARE_DIM  # top-left corner X coordinate

            rectangle = ( tl_corner_x, tl_corner_y, SQUARE_DIM, SQUARE_DIM)   # rectangle defining checker
            pygame.draw.rect( window, current_colour, rectangle )             # paint the rectangle
            number_bitmap = number_font.render( str(number), True, BLUE )     # create the number
            number += 1
            # Space it off the corner a bit
            margin = 10
            window.blit( number_bitmap, ( tl_corner_x + margin, tl_corner_y + margin ) )  # paint the number


"""
#diceroller from 1-6 using random.rantint
diceroll = random.randint(1,6)
rollboard = DiceRollerFont.render(str(diceroll),1,WHITE)
for ex in range(0, W_IN_SQUARES):
    for why in range(0, H_IN_SQUARES):
        drawing_window.blit(rollboard,(310,300))


player1 = pygame.draw.circle(drawing_window,BLUE,(25,25),10)
player1 = pygame.draw.circle(drawing_window,RED,(40,25),10)

"""

pygame.init()
pygame.font.init()

drawing_window = pygame.display.set_mode((350, 350))
drawing_window.fill(BLUE)

# I don't have 'cambriamath'
font = pygame.font.SysFont( None, 18, bold =pygame.font.Font.bold)
dice_roller_font = pygame.font.SysFont('arial', 40)

clock = pygame.time.Clock()   # used to govern the max MAX_FPS
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # paint the window
    drawCheckerBoard( drawing_window, font )

    # "flush" the changes to the window
    pygame.display.update()

    clock.tick( 60 )   # control the frame-rate to save electricity

pygame.quit()
Answered By: Kingsley
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.