Why is pygame.blit() reseting back to 0 after 65500 pixels? - python

Im creating a program that will show every image from a folder, i created a function for scrolling because in case there were a lot of images it wouldn't fit the screen, the problem is that after reaching 65536 on the y value, it will start bliting at 0 again, like placing the new names on top of the old ones.
This is a preview code that recreates my problem, what should happen when you press a key is a black screen or maybe a little of green on top, what really happens is that the top half is the y = 0 and the bottom half is y = -65540
import pygame
screen = pygame.display.set_mode((500,500))
colors = pygame.Surface((50,66000))#73825
colors.fill("green", (0,33, 50, 65600))
x = 0
running = True
while running:
pygame.time.Clock().tick(30)
screen.fill("black")
screen.blit(colors, (225,x))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYUP:
x = 0
if event.type == pygame.KEYDOWN:
x = -65540
if event.type == pygame.QUIT:
running = False
this only happens when using blit as rects work perfectly beyond the 65k pixel

it wouldn't fit the screen, the problem is that after reaching 65536
65535 is 0xffff, which is the maximum number that can be represented by 2 bytes or a variable of type "uint16". Likely this is the internal data type pygame uses to represent a pixel on the screen or the size of a pygame.Surface. This is far enough for any display in the world.
It is not a good idea to create a pygame.Surface of this size. It would be better to draw the parts of the images on the screen that should be displayed in each frame.
Minimal example of a scrollable image grid of images of the same size:
import pygame, random, math
screen = pygame.display.set_mode((500, 500))
scr_w, scr_h = screen.get_size()
img_w, img_h = 300, 200
images = []
for i in range(98):
img = pygame.Surface((img_w, img_h))
img.fill([random.randrange(256) for _ in range(3)])
images.append(img)
columns = 10
rows = math.ceil(len(images) / columns)
offset_x = 0
offset_y = 0
def fill_display():
row = offset_y // img_h
display_y = (img_h - (offset_y % img_h)) - img_h
while display_y < scr_w:
col = offset_x // img_w
display_x = (img_w - (offset_x % img_w)) - img_w
while display_x < scr_h:
i = row * columns + col
if i < len(images):
screen.blit(images[i], (display_x, display_y))
display_x += img_w
col += 1
display_y += img_h
row += 1
clock = pygame.time.Clock()
running = True
while running:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
offset_x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * 20
offset_y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * 20
offset_x = min((columns) * img_w - scr_w, max(0, offset_x))
offset_y = min((rows) * img_h - scr_h, max(0, offset_y))
screen.fill("black")
fill_display()
pygame.display.update()

Related

Python Pygame changing two positions based on a angle [duplicate]

This question already has answers here:
How to set the pivot point (center of rotation) for pygame.transform.rotate()?
(5 answers)
How can you rotate an image around an off center pivot in Pygame
(1 answer)
Closed 4 months ago.
Basically im trying to make a line point out out of the muzzle of this gun.
Picture of player, gun and make shift cross hair for reference (not part of the game)
How i made the gun was by get_rect() the gun surface, and setting the rectangles pos values to the players right side. I also made it so the gun will rotate to always point towards the mouse, but when the cross hair goes past the players right side (the angle goes past 90 or -90) the gun will flip to the players left side. Sorry for very messy code, im still quite new.
gunxposmdl = Player.player_rect.right
gunyposmdl = Player.player_rect.top
gunyposmdl += 20
mouse_x, mouse_y = pygame.mouse.get_pos()
rel_x, rel_y = mouse_x - gunxposmdl, mouse_y - gunyposmdl
angle = (180 / math.pi) * -math.atan2(rel_y, rel_x)
if angle > 90 or angle < -90:
if angle > 0:
angle =-abs(angle)
else:
angle = abs(angle)
rshotgunmdl = pygame.transform.rotate(Weapons.shotgun, int(angle))
rshotgunrect = rshotgunmdl.get_rect(midleft=(gunxposmdl,gunyposmdl))
player_surf_cpy = Player.player_surf.copy()
player_fliped = pygame.transform.flip(player_surf_cpy, False, True)
flipgunxposmdl = Player.player_rect.left
rshotgunmdlcpy = rshotgunmdl.copy()
rshotgunmdlfliped = pygame.transform.flip(rshotgunmdlcpy, False, True )
rshotgunrectfliped = rshotgunmdlfliped.get_rect(midright=(flipgunxposmdl, gunyposmdl))
screen.blit(player_fliped, Player.player_rect)
screen.blit(rshotgunmdlfliped, rshotgunrectfliped)
sg_muzzle_x, sg_muzzle_y = rshotgunrectfliped.midleft[0], rshotgunrectfliped.midleft[1]
else:
rshotgunmdl = pygame.transform.rotate(Weapons.shotgun, int(angle))
rshotgunrect = rshotgunmdl.get_rect(midleft=(gunxposmdl,gunyposmdl))
screen.blit(Player.player_surf, Player.player_rect)
screen.blit(rshotgunmdl, rshotgunrect)
sg_muzzle_x, sg_muzzle_y = rshotgunrect.midright[0], rshotgunrect.midright[1]
#Cast rays
pygame.draw.line(screen, ("Green"), (sg_muzzle_x, sg_muzzle_y), (sg_muzzle_x, sg_muzzle_y), 3)
The problem with this is that when the guns surface is rotated, the rectangle doesnt rotate with it. So when i rotate the gun with the mouse, the line still gets drawn where the rectangles right side is and not where the muzzle is. I need the line to stick out of the muzzle as a visual on where the gun is pointing. Im going to be using this to implement hit casting.
E.g.
Image example (actual in game cross hair this time)
Could somebody please help me make it so the line is coming out of the muzzle in both examples please?
full code:
#!/bin/env python3
import pygame
from sys import exit
import time
import math
pygame.init()
video_infos = pygame.display.Info()
width, height = video_infos.current_w, video_infos.current_h
screen = pygame.display.set_mode((width, height), pygame.FULLSCREEN,
pygame.RESIZABLE)
pygame.display.set_caption('2D Quake')
clock = pygame.time.Clock()
keys = pygame.key.get_pressed()
mousec = pygame.image.load("textures/UI/crossh.png").convert_alpha()
pygame.mouse.set_visible(False)
backround = pygame.Surface((width, height)).convert_alpha()
backround.fill('White')
sbar = pygame.image.load("textures/UI/HUD/SBAR.png").convert_alpha()
class Player:
player_surf = pygame.Surface((50,100))
player_surf.fill('Black')
player_rect = player_surf.get_rect(midbottom = (300, height))
player_gravity = 0
player = {"Inv": [1,1,0], "Hand": 1, "Health": 100}
class Weapons:
shotgun = pygame.image.load("textures/weapons/SHOTGUN.png").convert_alpha()
class Enemies:
esoldier_surf = pygame.Surface((50,100))
esoldier_surf.fill('Black')
esoldier_rect = esoldier_surf.get_rect(midbottom = (800, height))
esoldier = {"Health": 100}
print(width, height)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == pygame.K_h:
Player.player["Health"] -= 1
#Backround
screen.blit(backround,(0,0))
#Enemies
screen.blit(Enemies.esoldier_surf, Enemies.esoldier_rect)
#Player
healthnum = Player.player["Health"]
healthnums = [int(x) for x in str(healthnum)]
Player.player_gravity += 1
Player.player_rect.y += Player.player_gravity
if Player.player_rect.bottom >= height: Player.player_rect.bottom = height
keys = pygame.key.get_pressed()
if keys[pygame.K_d] == 1:
if keys[pygame.K_LCTRL] == 1:
Player.player_rect.x += 9
else:
Player.player_rect.x += 5
if keys[pygame.K_a] == 1:
if keys[pygame.K_LCTRL] == 1:
Player.player_rect.x -= 9
else:
Player.player_rect.x -= 5
if keys[pygame.K_SPACE] == 1 and Player.player_rect.bottom >= height:
Player.player_gravity = -20
gunxposmdl = Player.player_rect.right
gunyposmdl = Player.player_rect.top
gunyposmdl += 20
mouse_x, mouse_y = pygame.mouse.get_pos()
rel_x, rel_y = mouse_x - gunxposmdl, mouse_y - gunyposmdl
angle = (180 / math.pi) * -math.atan2(rel_y, rel_x)
if angle > 90 or angle < -90:
if angle > 0:
angle =-abs(angle)
else:
angle = abs(angle)
rshotgunmdl = pygame.transform.rotate(Weapons.shotgun, int(angle))
rshotgunrect = rshotgunmdl.get_rect(midleft=(gunxposmdl,gunyposmdl))
player_surf_cpy = Player.player_surf.copy()
player_fliped = pygame.transform.flip(player_surf_cpy, False, True)
flipgunxposmdl = Player.player_rect.left
rshotgunmdlcpy = rshotgunmdl.copy()
rshotgunmdlfliped = pygame.transform.flip(rshotgunmdlcpy, False, True )
rshotgunrectfliped = rshotgunmdlfliped.get_rect(midright=(flipgunxposmdl,
gunyposmdl))
screen.blit(player_fliped, Player.player_rect)
screen.blit(rshotgunmdlfliped, rshotgunrectfliped)
sg_muzzle_x, sg_muzzle_y = rshotgunrectfliped.midleft[0],
rshotgunrectfliped.midleft[1]
else:
rshotgunmdl = pygame.transform.rotate(Weapons.shotgun, int(angle))
rshotgunrect = rshotgunmdl.get_rect(midleft=(gunxposmdl,gunyposmdl))
screen.blit(Player.player_surf, Player.player_rect)
screen.blit(rshotgunmdl, rshotgunrect)
sg_muzzle_x, sg_muzzle_y = rshotgunrect.midright[0], rshotgunrect.midright[1]
#Cast rays
pygame.draw.line(screen, ("Green"), (sg_muzzle_x, sg_muzzle_y), (sg_muzzle_x,
sg_muzzle_y), 3)
#UI
mpos = pygame.mouse.get_pos()
sbarxpos = width - 600
sbarxpos = sbarxpos / 2
sbarypos = height - 46
screen.blit(sbar,(sbarxpos,sbarypos))
if len(healthnums) == 3:
hnum1 = pygame.image.load("textures/UI/HUD/NUM_1.png").convert_alpha()
hnum2 = pygame.image.load("textures/UI/HUD/NUM_0.png").convert_alpha()
hnum3 = pygame.image.load("textures/UI/HUD/NUM_0.png").convert_alpha()
if width == 1366:
screen.blit(hnum1,(645,727))
screen.blit(hnum2,(685,727))
screen.blit(hnum3,(727,727))
elif width == 1920:
numypos = height - 44
#screen.blit(hnum1,(, numypos))
#screen.blit(hnum2,(, numypos))
#screen.blit(hnum3,(, numypos))
if len(healthnums) == 2:
numa = healthnums[0]
numb = healthnums[1]
hnum2 = pygame.image.load(f"textures/UI/HUD/NUM_{numa}.png").convert_alpha()
hnum3 = pygame.image.load(f"textures/UI/HUD/NUM_{numb}.png").convert_alpha()
if width == 1366:
screen.blit(hnum2,(685,727))
screen.blit(hnum3,(727,727))
elif width == 1920:
numypos = height - 44
if len(healthnums) == 1:
numb = healthnums[0]
hnum3 = pygame.image.load(f"textures/UI/HUD/NUM_{numb}.png").convert_alpha()
screen.blit(hnum3,(727,727))
screen.blit(mousec, (mpos))
pygame.display.update()
clock.tick(60)
Link to Source files: https://www.dropbox.com/s/4tuk7v675go1urv/2DQuake.zip?dl=0

Generate tiles in piano tiles consecutively in pygame

I have created a simple piano tiles game clone in pygame.
Everything working fine except the way i am generating tiles after every certain interval, but as the game speed increases this leaves a gap between two tiles.
In the original version of the game, there's no lag (0 distance ) between two incoming tiles.
Here's a preview of the game:
Currently I am generating tiles like this:
ADDBLOCK = pygame.USEREVENT + 1
ADDTIME = 650
pygame.time.set_timer(ADDBLOCK, ADDTIME)
if event.type == ADDBLOCK:
x_col = random.randint(0,3)
block = Block(win, (67.5 * x_col, -120))
block_group.add(block)
But with time, these tiles speed increase so there's remain a gap between generation of two tiles as shown by red line in the preview. Is there any way to generate tiles consecutively?
Source Code
Use a variable number to know how many tiles have been generated since the start. This variable will start with 0, then you will add 1 to this variable every time a tile is generated.
Then, you can use a variable like scrolling which increases continuously. You will add this scrolling to every tile y pos to render them.
Now you just have to add a tile which y position is like -tile_height - tile_height * number.
If that doesn't make sense to you, look at this MRE:
import pygame
from pygame.locals import *
from random import randint
pygame.init()
screen = pygame.display.set_mode((240, 480))
clock = pygame.time.Clock()
number_of_tiles = 0
tile_height = 150
tile_surf = pygame.Surface((60, tile_height))
tiles = [] # [column, y pos]
scrolling = 0
score = 0
speed = lambda: 200 + 5*score # increase with the score
time_passed = 0
while True:
click = None # used to click on a tile
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
if event.type == MOUSEBUTTONDOWN:
click = event.pos
screen.fill((150, 200, 255))
if scrolling > number_of_tiles * tile_height:
# new tile
# use "while" instead of "if" if you want to go at really high speed
tiles.append([randint(0, 3), -tile_height - number_of_tiles * tile_height])
number_of_tiles += 1
for x, y in tiles:
screen.blit(tile_surf, (60 * x, y + scrolling))
if y + scrolling > 480: # delete any tile that is no longer visible
tiles.remove([x, y])
if click is not None and Rect((60 * x, y + scrolling), tile_surf.get_size())
.collidepoint(click):
tiles.remove([x, y]) # delete any tile that has been clicked
score += 1 # used to calculate speed
scrolling += speed() * time_passed
pygame.display.flip()
time_passed = clock.tick() / 1000

How adjust code that works only if I move the mouse

My code should be right, however it works only if I move my mouse, even if I didn't even set up one.
the code should draw concentric circles moving.
I have even tried by blocking the mouse, but it still doesn't work
import pygame
import math
import time
pygame.init()
screen = pygame.display.set_mode([800,600])
black = (0,0,0)
keep_going = True
white = (255,255,255)
freq = 10
num_circles = 0
radius = 0
while keep_going:
for event in pygame.event.get():
if event.type == pygame.QUIT:
keep_going = False
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,(400, 300), radiusY, 1)
pygame.display.update()
pygame.quit()
I would like to know why the hell I get this kind of bug, how to solve it, and if it's not possible, a possible solution.
The issue is caused, because you do all the code in the event loop. The code in the event loop is executed only, when an event occurs, such as mouse movement (pygame.MOUSEMOTION).
Do the drawing in the main loop rather than the event loop, to solve the issue:
while keep_going:
for event in pygame.event.get():
if event.type == pygame.QUIT:
keep_going = False
#<--
#<--
#while input() != "quit":
#for x in range(1): #importante
raggio = raggio + 1
num_cerchi = math.ceil(raggio / freq)
screen.fill(white)
raggioMax = num_cerchi * freq
passo = freq / raggioMax
#time.sleep(5)
for y in range(num_cerchi, 1, -1):
# 1, -1
raggioY = int(((passo * (num_cerchi - y)) + passo) * raggioMax) + (raggio % freq)
pygame.draw.circle(screen, black,(400, 300), raggioY, 1)
#raggio = raggio+1 #importante
clock.tick(60)
pygame.display.update()
pygame.quit()

Pygame resizing a surface and window based on a rect size

I have a display area and a surface that is blitted on the display. On the surface is an image, in this case a rect. In the future it may be multiple rects or lines drawn on the surface keep that in mind.
I am trying to enlarge (by pressing x) the Rect named Sprite that is on SpriteSurface and SpriteSurface as well as the whole display window. The SpriteSurface image should be centered despite the resize. Currently the window will enlarge and the image stays centered, but if you uncomment the spritesizeX and Y lines the image gets larger but too big too fast and the window doesn't seem to enlarge big enough. Lowering the values shows that the offset of centering gets thrown off after the first resize. I feel like the solution should be relatively easy but im stumped. Any help would be appreciated.
Settings.py
spriteSizeX = 30
spriteSizeY = 30
SpHalfX = int(round(spriteSizeX / 2))
SpHalfY = int(round(spriteSizeY / 2))
multiplyer = 3
windowSizeX = int(round(spriteSizeX * multiplyer))
windowSizeY = int(round(spriteSizeY * multiplyer))
HalfWinX = int(round((windowSizeX / 2) - SpHalfX))
HalfWinY = int(round((windowSizeY / 2) - SpHalfY))
Orange = (238,154,0)
Gold = (255,215,0)
Black = (0,0,0)
Blue = (0,0,255)
Gray = (128,128,128)
DarkGray = (100,100,100)
Green = (0,128,0)
Lime = (0,255,0)
Purple = (128,0,128)
Red = (255,0,0)
Teal = (0,200, 128)
Yellow = (255,255,0)
White = (255,255,255)
run = True
SpriteCapture.py
#!/usr/local/bin/python3.6
import sys, pygame
from pygame.locals import *
from settings import *
pygame.init()
pygame.display.set_caption("Sprite Capture")
Screen = pygame.display.set_mode((windowSizeX, windowSizeY),RESIZABLE)
SpriteSurface = pygame.Surface((spriteSizeX,spriteSizeY))
Sprite = Rect(0,0,spriteSizeX,spriteSizeY)
while run == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if pygame.key.get_pressed()[pygame.K_s]:
pygame.image.save(SpriteSurface, 'img1.png')
run = False
if pygame.key.get_pressed()[pygame.K_q]:
run = False
if pygame.key.get_pressed()[pygame.K_z]:
#spriteSizeX += 10
#spriteSizeY += 10
windowSizeX += -10
windowSizeY += -10
HalfWinX = int(round(windowSizeX / 2 - SpHalfX))
HalfWinY = int(round(windowSizeY / 2 - SpHalfY))
Screen = pygame.display.set_mode((windowSizeX, windowSizeY),RESIZABLE)
SpriteSurface = pygame.Surface((spriteSizeX,spriteSizeY))
if pygame.key.get_pressed()[pygame.K_x]:
#spriteSizeX += 10
#spriteSizeY += 10
windowSizeX += 10
windowSizeY += 10
HalfWinX = int(round(windowSizeX / 2 - SpHalfX))
HalfWinY = int(round(windowSizeY / 2 - SpHalfY))
Screen = pygame.display.set_mode((windowSizeX, windowSizeY),RESIZABLE)
SpriteSurface = pygame.Surface((spriteSizeX,spriteSizeY))
Sprite = Sprite = Rect(0,0,spriteSizeX,spriteSizeY)
Screen.fill(Black)
pygame.draw.rect(SpriteSurface,Orange,Sprite)
Screen.blit(SpriteSurface, (HalfWinX,HalfWinY))
pygame.display.flip()
If you want to scale your surfaces or rects according to the screen size, you can define a zoom_factor variable which you can just increase when a key gets pressed and then use it to scale the window and the surfaces. Multiply it by the original screen width and height to scale the window, and also scale your surfaces with pygame.transform.rotozoom and pass the zoom_factor as the scale argument.
import sys
import pygame
from pygame.locals import *
width = 30
height = 30
multiplyer = 3
window_width = round(width * multiplyer)
window_height = round(height * multiplyer)
zoom_factor = 1
ORANGE = (238,154,0)
BLACK = (0,0,0)
pygame.init()
screen = pygame.display.set_mode((window_width, window_height), RESIZABLE)
screen_rect = screen.get_rect() # A rect with the size of the screen.
clock = pygame.time.Clock()
# Keep a reference to the original image to preserve the quality.
ORIG_SURFACE = pygame.Surface((width, height))
ORIG_SURFACE.fill(ORANGE)
surface = ORIG_SURFACE
# Center the rect on the screen's center.
rect = surface.get_rect(center=screen_rect.center)
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
run = False
elif event.key == pygame.K_z:
zoom_factor = round(zoom_factor-.1, 1)
# Scale the screen.
w, h = int(window_width*zoom_factor), int(window_height*zoom_factor)
screen = pygame.display.set_mode((w, h), RESIZABLE)
screen_rect = screen.get_rect() # Get a new rect.
# Scale the ORIG_SURFACE (the original won't be modified).
surface = pygame.transform.rotozoom(ORIG_SURFACE, 0, zoom_factor)
rect = surface.get_rect(center=screen_rect.center) # Get a new rect.
elif event.key == pygame.K_x:
zoom_factor = round(zoom_factor+.1, 1)
w, h = int(window_width*zoom_factor), int(window_height*zoom_factor)
screen = pygame.display.set_mode((w, h), RESIZABLE)
screen_rect = screen.get_rect()
surface = pygame.transform.rotozoom(ORIG_SURFACE, 0, zoom_factor)
rect = surface.get_rect(center=screen_rect.center)
# Note that the rect.w/screen_rect.w ratio is not perfectly constant.
print(zoom_factor, screen_rect.w, rect.w, rect.w/screen_rect.w)
screen.fill(BLACK)
screen.blit(surface, rect) # Blit the surface at the rect.topleft coords.
pygame.display.flip()
clock.tick(60)
Alternatively, you could just blit all of your surfaces onto a background surface, then scale this background with pygame.transform.rotozoom each frame and blit it onto the screen. However, scaling a big background surface each frame will be bad for the performance.

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