Bug in block moving game Google Colab

I don’t know how to fix this. It works fine but randomly stops at some point.

!pip install pygame

# Initialize the pygame!

# Imported code
#-------------------------------------------------------------
import pygame
import cv2
from google.colab.patches import cv2_imshow
from IPython.display import clear_output as clear
from google.colab import output
import time 
import os, sys
#-------------------------------------------------------------
# Apparently this is necessary for the code to 
# run to fool it into thinking it has a windowing system.
os.environ["SDL_VIDEODRIVER"] = "dummy"

# Initialize the game!
pygame.init()

# Create a gamespace. 
screen = pygame.display.set_mode((400, 300))

# Set variables.
is_blue = True # (Came with code, unknown use)
color = (255, 100, 0)

# Set up the square's origin coordinates.
x = 165
y = 125

#----------------------------------------------------------------
# Define a function to gather keypresses.
def keypress():
  pressed = False
  # While the verbal key input is not a valid direction, it keeps asking for one.
  
  while not pressed:
    keypress = str(input("Please enter a direction:"))
    
    if keypress == "Right" or keypress == "right":
      pressed = True
    elif keypress == "Left" or keypress == "left":
      pressed = True
    elif keypress == "Up" or keypress == "up":
      pressed = True
    elif keypress == "Down" or keypress == "down":
      pressed = True
  
    else:
      print("\nI'm sorry, that's not a valid direction.")
      time.sleep(2)
      clear()

  # When it finally gets a valid direction, it 
  # clears any remaining text and returns the pressed key.
  clear()
  return keypress

#-------------------------------------------------------------
# If: 
  # - The key is (right, left, up, down), and
  # - The code is asking for (x or y),

# Then,
  # Add or subtract 50 to the cooresponding coordinate.

# Otherwise,
  # Do nothing.

# Return the movement.

def moveSquare(coordinate, Key):
  movement = 0

  if ((Key == "Right" or Key == "right") and (coordinate == x)):
    
    movement = 50

  elif ((Key == "Left" or Key == "left") and (coordinate == x)):  
    
    movement = -50

  elif ((Key == "Up" or Key == "up") and (coordinate == y)):
    
    movement = -50

  elif ((Key == "Down" or Key == "down") and (coordinate == y)):
    
    movement = 50
  
  else:
    ""
  
  return movement
#-------------------------------------------------------------
# This draws the four squares to interact with.
def drawSquares():
  pygame.draw.rect(screen, color, pygame.Rect(0, 0, 50, 50))
  pygame.draw.rect(screen, color, pygame.Rect(0, 250, 50, 50))
  pygame.draw.rect(screen, color, pygame.Rect(350, 0, 50, 50))
  pygame.draw.rect(screen, color, pygame.Rect(350, 250, 50, 50))

#-------------------------------------------------------------

# Setup the 'game' to keep it running
while not done:
        done = False
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        done = True

        # Set the background color to black and erase the previous square

        backgroundColor = (0,0,0)
        pygame.draw.rect(screen, backgroundColor, pygame.Rect(x, y, 30, 30))

        # Set x and y to what they were before, plus the positive or 
        # negative direction resulting from the direction

        x = x + moveSquare(x,Key)
        y = y + moveSquare(y,Key)

        # Draw/redraw the rectangle
        pygame.draw.rect(screen, color, pygame.Rect(x, y, 30, 30))

        # Draw/redraw the four corner rectangles
        drawSquares()
        
        # Update the full display
        pygame.display.flip()

        #convert image so it can be displayed in OpenCV 
        view = pygame.surfarray.array3d(screen) # (Came with code, unknown use)

        #  convert from (width, height, channel) to (height, width, channel) 
        view = view.transpose([1, 0, 2]) # (Came with code, unknown use)

        #  convert from rgb to bgr 
        img_bgr = cv2.cvtColor(view, cv2.COLOR_RGB2BGR) # (Came with code, unknown use)

        #Display image and clear text
        cv2_imshow(img_bgr) # (Came with code, unknown use)
        Key = keypress()
        output.clear()

#-------------------------------------------------------------

Do you happen to have a public link to your colab so we can check it out? I pasted your code, and it doesn’t run, seems you attempt to use some variables before they are declared, such as done and Key.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.