Python clicking game, updating score - python

import pygame
from pygame.locals import *
import random
import time
pygame.init()
randomNumber = random.randint(1,600)
randomNumber2 = random.randint(1,600)
x = 0
text = ""
squareCount = 0
beenHere = 0
# colours = (red, green, blue)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
LBLUE = (0, 123, 255)
colour = RED
# Make a window appear
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Square Chase | Score: 0")
screen.fill(LBLUE)
pygame.display.flip()
pygame.time.set_timer(USEREVENT + 1, 1500)
done = False
clock = pygame.time.Clock()
while done == False:
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
done = True
if event.type == USEREVENT + 1:
screen.fill(LBLUE)
randomNumber = random.randint(1,625)
randomNumber2 = random.randint(1,420)
mySquare = pygame.draw.rect(screen,colour,(randomNumber,randomNumber2,50,50),5)
squareCount = squareCount + 1
if squareCount == 50:
done == true
pygame.display.flip()
if event.type == pygame.MOUSEBUTTONDOWN:
y, z = pygame.mouse.get_pos()
is_inside = mySquare.collidepoint(y, z)
if is_inside and colour == GREEN:
x = x+1
text = str(x)
pygame.display.set_caption("Square Chase | Score " + text)
colour = RED
elif is_inside:
x = x+1
text = str(x)
pygame.display.set_caption("Square Chase | Score " + text)
colour = GREEN
clock.tick(20)
pygame.quit()
I am aiming to create a game in which the user has to click on a square for their score to increase. They get 50 chances to do this. If they click in the square within the 1.5 seconds the colour of the square changes.
The above code works apart from each time a new square is drawn the user could click on it say 5 times and their score will go up by 5. Any suggestions as to how to get the score to increase by just one? Thanks in advance.

Wish I could just use a comment but I have lack of reputation.
I didn't look through all your code, but your description makes it sound like a simple flag would be able to help you.
Once you recognize it has been clicked, increment the score AND set a boolean.
So in essence you will want something along the lines of
if clicked == false
score = score+1
clicked = true
You will want to clear the flag back to false once another block has appeared.

Wouldn't it be better, if a new square would show up after a successful keypress? That way the game would be more dynamic.
It's easy to change this. Instead of using user events that are called every 1.5 sec, sum the value returned by clock.tick() and when their sum will be greater than 1500 ms, create a new rectangle. This is a better approach, because you can call the method that creates a new square and reset the timer right after a successful keypress.
Some code to get you started:
def new_rect(screen,colour):
screen.fill(LBLUE)
randomNumber = random.randint(1,625)
randomNumber2 = random.randint(1,420)
mySquare = pygame.draw.rect(screen,colour,(randomNumber,randomNumber2,50,50),5)
return mySquare
done = False
clock = pygame.time.Clock()
timer_var = 0
while done == False:
if(timer_var > 1500):
timer_var = 0
mySquare = new_rect(screen,color)
squareCount = squareCount + 1
if squareCount == 50:
done == true
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
y, z = pygame.mouse.get_pos()
is_inside = mySquare.collidepoint(y, z)
if is_inside:
x = x+1
text = str(x)
pygame.display.set_caption("Square Chase | Score " + text)
timer_var = 0
new_rect(screen,colour)
squareCount = squareCount + 1
if squareCount == 50:
done == true
if colour == GREEN:
colour = RED
else:
colour = GREEN
timer_var += clock.tick(20)
pygame.quit()

Related

ZX81 BASIC to Pygame Conversion of "Dropout" Game

I based the code below on this article: http://kevman3d.blogspot.com/2015/07/basic-games-in-python-1982-would-be.html
and on the ZX BASIC in this image:
10 LET P=0
20 LET T=P
30 FOR Z=1 T0 10
35 CLS
37 PRINT AT 12,0;T
40 LET R=INT (RND*17)
50 FOR Y=0 TO 10
60 PRINT AT Y,R;"O"
70 LET N=P(INKEY$="4")-(INKEY$="1")
80 IF N<0 OR N>15 THEN LET N=P
100 PRINT AT 11,P;" ";AT 11,N;"┗┛";AT Y,R;" "
110 LET P=N
120 NEXT Y
130 LET T=T+(P=R OR P+1=R)
150 NEXT Z
160 PRINT AT 12,0;"YOU SCORED ";T;"/10"
170 PAUSE 4E4
180 RUN
I also shared it on Code Review Stack Exchange, and got a very helpful response refactoring it into high quality Python code complete with type hints.
However, for my purposes I'm wanting to keep the level of knowledge required to make this work a little less advanced, including avoiding the use of OOP. I basically want to maintain the "spirit of ZX BASIC" but make the code "not awful." The use of functions is fine, as we were allowed GOSUB back in the day.
I'm pretty dubious about the approach of using nested FOR loops inside the main game loop to make the game work, but at the same time I'm curious to see how well the BASIC paradigm maps onto the more event driven approach of Pygame, so I'd welcome any comments on the pros and cons of this approach.
More specifically,
Is there somewhere I can put the exit code if event.type == pygame.QUIT where it will work during game rounds, without having to repeat the code elsewhere?
How would this game be implemented if I were to avoid the use of FOR loops / nested FOR loops?
Are there any points of best practice for pygame/Python which I have violated?
What improvements can you suggest, bearing in mind my purpose is to write good Pygame code while maintaining the "spirit" of the ZX81 games?
Any input much appreciated. I'm also curious to see a full listing implementing some of the ideas arising from my initial attempt if anyone is willing to provide one.
import pygame
import random
import sys
# Define colors and other global constants
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
TEXT_SIZE = 16
SCREEN_SIZE = (16 * TEXT_SIZE, 13 * TEXT_SIZE)
NUM_ROUNDS = 5
def print_at_pos(row_num, col_num, item):
"""Blits text to row, col position."""
screen.blit(item, (col_num * TEXT_SIZE, row_num * TEXT_SIZE))
# Set up stuff
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption("Dropout")
game_font = pygame.font.SysFont('consolas', TEXT_SIZE)
# Create clock to manage how fast the screen updates
clock = pygame.time.Clock()
# initialize some game variables
player_pos, new_player_pos, coin_row, score = 0, 0, 0, 0
# -------- Main Program Loop -----------
while True:
score = 0
# Each value of i represents 1 round
for i in range(NUM_ROUNDS):
coin_col = random.randint(0, 15)
# Each value of j represents one step in the coin's fall
for j in range(11):
pygame.event.get()
pressed = pygame.key.get_pressed()
if pressed[pygame.K_RIGHT]:
new_player_pos = player_pos + 1
elif pressed[pygame.K_LEFT]:
new_player_pos = player_pos - 1
if new_player_pos < 0 or new_player_pos > 15:
new_player_pos = player_pos
# --- Game logic
player_pos = new_player_pos
coin_row = j
if player_pos + 1 == coin_col and j == 10:
score += 1
# --- Drawing code
# First clear screen
screen.fill(WHITE)
player_icon = game_font.render("|__|", True, BLACK, WHITE)
print_at_pos(10, new_player_pos, player_icon)
coin_text = game_font.render("O", True, BLACK, WHITE)
print_at_pos(coin_row, coin_col, coin_text)
score_text = game_font.render(f"SCORE: {score}", True, BLACK, WHITE)
print_at_pos(12, 0, score_text)
# --- Update the screen.
pygame.display.flip()
# --- Limit to 6 frames/sec maximum. Adjust to taste.
clock.tick(8)
msg_text = game_font.render("PRESS ANY KEY TO PLAY AGAIN", True, BLACK, WHITE)
print_at_pos(5, 0, msg_text)
pygame.display.flip()
waiting = True
while waiting:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(0)
if event.type == pygame.KEYDOWN:
waiting = False
Here's my reorganisation of your code:
import pygame
import random
# Define global constants
TEXT_SIZE = 16
SCREEN_SIZE = (16 * TEXT_SIZE, 13 * TEXT_SIZE)
NUM_ROUNDS = 5
def print_at_pos(row_num, col_num, item):
"""Blits text to row, col position."""
screen.blit(item, (col_num * TEXT_SIZE, row_num * TEXT_SIZE))
# Set up stuff
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption("Dropout")
game_font = pygame.font.SysFont("consolas", TEXT_SIZE)
# Create clock to manage how fast the screen updates
clock = pygame.time.Clock()
# draw the images
player_icon = game_font.render("|__|", True, "black", "white")
# if we don't specify a background color, it'll be transparent
coin_text = game_font.render("O", True, "black")
msg_text = game_font.render("PRESS ANY KEY TO PLAY AGAIN", True, "black", "white")
# initialize some game variables
waiting = False # start in game
player_pos = 0
score = 0
game_round = 0
coin_row = 0
coin_col = random.randint(0, 15)
running = True # For program exit
# -------- Main Program Loop -----------
while running:
# event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if waiting:
waiting = False
score = 0 # reset score
elif event.key == pygame.K_LEFT:
player_pos -= 1
elif event.key == pygame.K_RIGHT:
player_pos += 1
# --- Game logic
if waiting:
# don't update the game state or redraw screen
print_at_pos(5, 0, msg_text)
else:
coin_row += 1 # TODO: decouple from frame rate
if -1 > player_pos:
player_pos = -1 # so we can catch a coin at zero
elif 15 < player_pos:
player_pos = 15
# coin is in scoring position
if coin_row == 10:
if player_pos + 1 == coin_col:
score += 1
elif coin_row > 10: # round is over
coin_col = random.randint(0, 15)
coin_row = 0
game_round+= 1
if game_round >= NUM_ROUNDS:
waiting = True
game_round = 0 # reset round counter
# --- Drawing code
screen.fill("white") # clear screen
print_at_pos(10, player_pos, player_icon)
print_at_pos(coin_row, coin_col, coin_text)
score_text = game_font.render(f"SCORE: {score}", True, "black", "white")
print_at_pos(12, 0, score_text)
# --- Update the screen.
pygame.display.flip()
# --- Limit to 6 frames/sec maximum. Adjust to taste.
clock.tick(6)
pygame.quit()
I've used a boolean waiting to allow for common event and game state handling that only moves during gameplay. For more complex interactions, you'll want a state machine.
The coin movement is currently coupled to the frame rate, which is easy, but ideally you'd specify a rate/time interval, e.g. 200ms between row drops and then you could have a refresh rate similar to the monitor refresh rate.

issues with checking if my images collided in pygame [duplicate]

This question already has an answer here:
Why is my collision test always returning 'true' and why is the position of the rectangle of the image always wrong (0, 0)?
(1 answer)
Closed 1 year ago.
So I'm trying to check im my bird images are touching my could images and if they are to print print('Collided1!').
My Issue is that print('Collided1!') goes off no matter what and is not checking whether the images are touching. colliderect was the solution I found online but I don't seem to know how it works because this is not working.
Do You Know how to fix this? and check whether my images are touching or not?
from random import randint
import pygame, sys
import random
import time
pygame.init()
pygame.display.set_caption('Lokaverkefni')
DISPLAYSURF = pygame.display.set_mode((1224, 724))
fpsClock = pygame.time.Clock()
FPS = 60
a = 1
b = 1
c = 15
x = 100
y = 480
start = 0
score = 0
landX = 1205
totalScore = 0
level = 'low'
directionForBird = 'none'
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BASICFONT = pygame.font.Font('freesansbold.ttf', 30)
background_resized = pygame.image.load('sky.jpg')
background = pygame.transform.scale(background_resized, (1224, 724))
bird1 = pygame.image.load('bird1.png')
bird1_resized = pygame.transform.scale(bird1, (170, 150))
bird1Surface = bird1_resized.get_rect()
bird2 = pygame.image.load('bird2.png')
bird2_resized = pygame.transform.scale(bird2, (170, 150))
bird2Surface = bird2_resized.get_rect()
cloudsList = ['cloud1.png', 'cloud2.png', 'cloud3.png', 'cloud4.png']
clouds = random.choice(cloudsList)
cloud = pygame.image.load(clouds)
cloud_resized = pygame.transform.scale(cloud, (352, 352))
cloudSurface = cloud_resized.get_rect()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if level == 'low':
if (event.key == K_SPACE ):
directionForBird = 'up'
level = 'high'
FPS += 2
c += 1
if directionForBird == 'up':
y -= 10
if y == 10:
directionForBird = 'down'
if directionForBird == 'down':
y += 10
if y == 480:
directionForBird = 'none'
if a == 1:
DISPLAYSURF.blit(background, (0, 0))
DISPLAYSURF.blit(bird1_resized, (x, y))
DISPLAYSURF.blit(cloud_resized, (landX, 300))
b += 1
if b == c:
a += 1
if a == 2:
DISPLAYSURF.blit(background, (0, 0))
DISPLAYSURF.blit(bird2_resized, (x, y))
DISPLAYSURF.blit(cloud_resized, (landX, 300))
b -= 1
if b == 1:
a -= 1
start += 1
if start == 100:
start -= 1
directionForLand = 'left'
if directionForLand == 'left':
landX -= 15
if landX == -550:
landX = 1205
level = 'low'
clouds = random.choice(cloudsList)
cloud = pygame.image.load(clouds)
cloud_resized = pygame.transform.scale(cloud, (352, 352))
score += 1
if score == 30:
score = 0
totalScore += 1
scoreText = BASICFONT.render('Stig : %s' % (totalScore), True, (BLACK))
scoreRect = scoreText.get_rect()
scoreRect.topleft = (1070, 10)
DISPLAYSURF.blit(scoreText, scoreRect)
# This is Supossed to Be what checks if the bird images
# colide with the cloud images
if bird1Surface.colliderect(cloudSurface):
print('Collided1!')
if bird2Surface.colliderect(cloudSurface):
print('Collided1!')
pygame.display.update()
fpsClock.tick(FPS)
bird1Surface, bird2Surface and cloudSurface always have an upper left of (0,0), so they are always on top of each other.. You don't change the rectangles when you move the birds. You need to track the bird x,y and the cloud x,y, and construct new rectangles with the current x,y and the known width and height before you do the collision check.

Mastermind Game, Pygame, Adding the guess Indicators

I have got my game working, and i am happy with how it looks, I need to add the 4 indicators next to each row in the game, to signal whether the guess by the user is close to the computer guess
A quick explanation of the game
If the user guesses a colour but it is in the wrong position then it should change a indicator to orange
if its in the correct position it shoulde change to red. Then the user uses this to keep guessing
I think i could possibly draw 4 circles next to each row and then change the colour of them depending
On the guess from the user. However I am not sure on how to do this
There also might be a mor efficient way to do this, so of there is any suggestions would be great
The code looks like this
I have added some code, for the computer guess and if you guess correctly
import pygame
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0 , 0, 255)
WIDTH = 20
HEIGHT = 20
WIDTH1 = 30
HEIGHT1 = 30
MARGIN = 5
MARGIN1 = 10
array_width = 4
array_height = 8
grid = []
for row in range(10):
grid.append([])
for column in range(10):
grid[row].append(0)
colors = [(0, 0, 0) for i in range(array_width * array_height)]
blocks = [False for i in range(array_width * array_height)]
pygame.init()
# Set the HEIGHT and WIDTH of the screen
WINDOW_SIZE = [300, 300]
screen = pygame.display.set_mode(WINDOW_SIZE)
# Set title of screen
pygame.display.set_caption("MASTERMIND GAME")
sair = True
done = False
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
grid[row][column] = 1
#TEXT BOX VARIABLES AND DATA
base_font = pygame.font.Font(None, 32)
user_text = ""
input_rect = pygame.Rect (10,250,100,50)
color_active = pygame.Color('lightskyblue3')
color_passive = pygame.Color('gray15')
color=color_passive
active = False
current_color = "white"
grid = [[current_color for column in range(4)] for row in range(8)]
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
print (blocks)
pos = pygame.mouse.get_pos()
column = pos[0] // (WIDTH + MARGIN)
row = pos[1] // (HEIGHT + MARGIN)
print(row)
print(column)
# TEXT BOX CREATION AND USAGE
# check if column and row are valid grid indices
if 0 <= row < array_height and 0 <= column < array_width:
try:
grid[row][column] = current_color
except:
print("invalid color")
if event.type == pygame.MOUSEBUTTONDOWN:
if input_rect.collidepoint(event.pos):
active = True
else:
active = False
if event.type == pygame.KEYDOWN:
if active == True:
if event.key == pygame.K_BACKSPACE:
user_text = user_text[0:-1]
else:
user_text += event.unicode
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
user_text = user_text
print(user_text)
if user_text != "":
current_color = user_text
user_text = ""
print("Click ", pos, "Grid coordinates: ", row, column)
if active:
color = color_active
else:
color=color_passive
screen.fill(0)
pygame.draw.rect(screen,color,input_rect,2)
text_surface= base_font.render(user_text,True,(255,255,255))
screen.blit(text_surface, (input_rect.x +5, input_rect.y + 5))
for row, gridrow in enumerate(grid):
for column, color in enumerate(gridrow):
pygame.draw.rect(screen,
color,
[(MARGIN + WIDTH) * column + MARGIN,
(MARGIN + HEIGHT) * row + MARGIN,
WIDTH,
HEIGHT])
clock.tick(60)
pygame.display.flip()
pygame.quit
Thanks
The question has several sub-questions and I just answered one. So there are plenty of opportunities for additional answers from other contributors.
Create a new grid for the indicators. The initial value for all fields is None:
indicator_grid = [[None for column in range(4)] for row in range(8)]
Draw the indicators in nested loops:
while not done:
# [...]
for row, gridrow in enumerate(indicator_grid):
for column, status in enumerate(gridrow):
x = 100 + (MARGIN + WIDTH) * column + MARGIN
y = (MARGIN + HEIGHT) * row + MARGIN
color = "grey"
if status != None:
color = "red" if status else "orange"
pygame.draw.circle(screen, color, (x+WIDTH//2, y+WIDTH//2), WIDTH//2)
When you want to set the state in indicator_grid to True or False, the color of the corresponding circle changes.

How can I display both circles without flashing caused by double refresh

The code should display 1 or 2 circles depending on what you ask, and the program asks the user for the frequency of both circles.
I'm pretty sure the code works right, but the problem is that when the circles are displayed, 1 of the circles keeps flashing, but I don't know how to adjust it.
I have tried by playing around with it, by moving the update after or before, by updating it 2 times, after or before, anyway i'm stuck and I don't know how I should do it
import pygame
import math
import time
clock = pygame.time.Clock()
pygame.init()
pygame.display.set_caption("circles")
screen = pygame.display.set_mode([1000,700])
width_2 = int(screen.get_width() / 2)
width_3 = int(screen.get_width() / 3)
height_center = int(screen.get_height() / 2 )
black = (0,0,0)
keep_going = True
onecircle = False
twocircles = False
white = (255,255,255)
blue = (0,0,255)
red = (255,0,0)
freq = 0
circle1spot = (0,0)
circle2spot = (0,0)
freq2 = 0
pointradius = 3
num_circles = 0
num_circles2 = 0
radius = 0
radius2 = 0
centerradius = 20
howmanycircles = int(input("How many circles? \n"))
if howmanycircles == 1:
onecircle = True
elif howmanycircles == 2:
twocircles = True
else:
print("Answer not correct, 1 circle selected by default")
onecircle = True
if howmanycircles == 1:
freqinput = int(input("Frequency 1 circle, MIN [1], MAX [148]: \n"))
freq = 150 - freqinput
elif howmanycircles == 2:
freqinput = int(input("Frequency 1 circle, MIN [1], MAX [148]: \n"))
freq = 150 - freqinput
freqinput2 = int(input("Frequency 2 circle, MIN [1], MAX [148]: \n"))
freq2 = 150 - freqinput2
def circle1(radius, centerradius):
radius = radius + 1
num_circles = math.ceil(radius / freq)
#screen.fill(white)
radiusMax = num_circles * freq
pace = freq / radiusMax
for y in range(num_circles, 1, -1):
radiusY = int(((pace * (num_circles - y)) + pace) * radiusMax) + (radius % freq)
pygame.draw.circle(screen, black, circle1spot, centerradius, 1 )
pygame.draw.circle(screen, black, circle1spot, radiusY, 1)
#pygame.display.update()
return radius
def circle2(raggio2, centerradius):
radius2 = radius2 + 1
num_circles2 = math.ceil(radius2 / freq2)
#screen.fill(white)
radiusMax = num_circles2 * freq2
pace = freq2 / radiusMax
for y in range(num_circles2, 1, -1):
radiusY = int(((pace * (num_circles2 - y)) + pace) * radiusMax) + (radius2 % freq2)
pygame.draw.circle(screen, red, circle2spot, centerradius, 1 )
pygame.draw.circle(screen, red, circle2spot, radiusY, 1)
#pygame.display.update()
return radius2
while keep_going:
for event in pygame.event.get():
if event.type == pygame.QUIT:
keep_going = False
if event.type == pygame.MOUSEBUTTONDOWN:
if pygame.mouse.get_pressed()[0]:
#mousedownleft = True
circle1spot = pygame.mouse.get_pos()
print(circle1spot)
if pygame.mouse.get_pressed()[2]:
#mousedownright = True
circle2spot = pygame.mouse.get_pos()
pygame.draw.circle(screen, blue, (width_3,height_center), pointradius, 3 )
pygame.draw.circle(screen, blue, ((width_3*2),height_center), pointradius, 3 )
pygame.draw.circle(screen, blue, ((width_2),height_center), pointradius, 3 )
if onecircle == True:
radius = circle1(radius,centerradius)
pygame.display.update()
elif twocircles == True:
radius = circle1(radius,centerradius) #this is the critical zone
pygame.display.update() #this is the critical zone
radius2 = circle2(radius2, centerradius) #this is the critical zone
pygame.display.update() #this is the critical zone
screen.fill(white) #this is the critical zone
pygame.quit()
I'm looking for a possible solution to make it work correctly and to get it refreshed correctly
It is sufficient to do one single pygame.display.update() at the end of the main loop.
clear the display
do all the drawing
update the display
while keep_going:
# [...]
# 1. clear the display
screen.fill(white)
# 2. do all the drawing
pygame.draw.circle(screen, blue, (width_3,height_center), pointradius, 3 )
pygame.draw.circle(screen, blue, ((width_3*2),height_center), pointradius, 3 )
pygame.draw.circle(screen, blue, ((width_2),height_center), pointradius, 3 )
if onecircle == True:
radius = circle1(radius,centerradius)
elif twocircles == True:
radius = circle1(radius,centerradius)
radius2 = circle2(radius2, centerradius)
# 3. update the display
pygame.display.update()

I get an incorrect position from .get_rect()?

I'm currently working on a school project where I'm making a "hexcells" similar game in pygame and now I'm trying to blit an a new image if the user has clicked a current image. It will blit an image in the top left area, if clicked in the top left area, but not if I click any of the existing images. I told the program to print the coordinates from the images with help of the .get_rect() function, but it remains the same whereever I click and the coordinates aren't even where a image is. Can someone help me understand how this works and help me blit the new images on top of the existing images? Code below is not the entire document, however there is so much garbage/trash/unused code so I'd thought I spare you the time of looking at irrelevant code. Also sorry if the formatting is wrong or the information isn't enough, I tried my best.
import pygame, sys
from pygame.locals import *
#Magic numbers
fps = 30
winW = 640
winH = 480
boxSize = 40
gapSize = 75
boardW = 3
boardH = 3
xMargin = int((winW - (boardW * (boxSize + gapSize))) / 2)
yMargin = int((winW - (boardW * (boxSize + gapSize))) / 2)
#Lil bit o' color R G B
NAVYBLUE = ( 60, 60, 100)
correctCords = [[175,275,375],[375,275,175]]
bgColor = NAVYBLUE
unC = pygame.image.load("unC.png")
cor = pygame.image.load("correct.png")
inc = pygame.image.load("wrong.png")
correct = "Correct"
inCorrect = "Incorrect"
def main():
global FPSCLOCK, DISPLAYSURF
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((winW, winH))
mousex = 0 #stores x-coordinate of mouse event
mousey = 0 #stores y-coordinate of mouse event
pygame.display.set_caption("Branches")
DISPLAYSURF.fill(bgColor)
gridGame(inCorrect, correct,gapSize,xMargin,yMargin,boxSize)
while True:
mouseClicked = False
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
mousex,mousey = event.pos
elif event.type == MOUSEBUTTONUP:
mousex, mousey = event.pos
pos = pygame.mouse.get_pos()
mouseClicked = True
unCa = unC.get_rect()
corA = cor.get_rect()
print unCa
print corA
print pos
if unCa.collidepoint(pos):
DISPLAYSURF.blit(cor,(mousey,mousex))
"""lada = unC.get_rect()
lada =
if mousex and mousey == lada:
for x in correctCords:
for y in x:
for z in x:
if mousey and mousex == z and y:
DISPLAYSURF.blit(cor,(mousey,mousex))
print lada"""
pygame.display.update()
FPSCLOCK.tick(fps)
def gridGame(inCorrect, correct,gapSize,xMargin,yMargin,boxSize):
grid = []
cordX = []
cordY = []
correctRecs = []
#cordinates = []
#cordinates.append([])
#cordinates.append([])
#cordinates.append([])
#this is basically getBoard() all over again
#This part will arrange the actual backend grid
for row in range(3):
grid.append([])
#cordinates[0].append(gapSize+(row+1)*100)
#cordinates[1].append(gapSize+(row+1)*100)
#cordinates[2].append(gapSize+(row+1)*100)
for column in range(3):
grid[row].append(inCorrect)
for row in range(3):
cordX.append([])
for column in range(3):
cordX[row].append(gapSize+(row+1)*100)
for row in range(3):
cordY.append([])
for column in range(3):
cordY[row].append(gapSize+(column+1)*100)
#print cordX[0][0], cordY[0][0]
grid[0][2] = correct
grid[1][1] = correct
grid[2][0] = correct
#Y-AXEL SKRIVS FoRST ([Y][X])
#print cordinates[2][1]
DISPLAYSURF.blit(cor,(100,100))
#Let's draw it as well
for row in range(3):
for column in range(3):
DISPLAYSURF.blit(unC,(gapSize+(row+1)*100,gapSize+(column+1)*100))
main()
Also real sorry about the horrible variable naming and occasional swedish comments.
unCa = unC.get_rect() gives you only image size - so use it only once at start (before while True) - and later use the same unCa all the time to keep image position and change it.
btw: better use more readable names - like unC_rect
ie.
# move 10 pixel to the right
unC_rect.x += 10
# set new position
unC_rect.x = 10
unC_rect.right = 100
unC_rect.topleft = (10, 200)
unC_rect.center = (10, 200)
# center on screen
unC_rect.center = DISPLAYSURF.get_rect().center
etc.
And then use this rect to blit image
blit(unC, unC_rect)
and check collision with other rect
if unC_rect.colliderect(other_rect):
or with point - like mouse position
elif event.type == MOUSEMOTION:
if unC_rect.collidepoint(pygame.mouse.get_pos()):
hover = True
# shorter
elif event.type == MOUSEMOTION:
hover = unC_rect.collidepoint(pygame.mouse.get_pos()):

Categories

Resources