Related
I'm trying to create a walking spider like this:
I considered using a SimpleMotor at the pink and red joints and control them using the rate function. But when I tried, I get an error that the function is not callable.
self.motorJoint1.rate(0.0) TypeError: 'float' object is not callable
I don't see any other functions in the pymunk API that allow controlling the joints at will. Is there really no function or am I missing something?
Basically in the run loop I want to specify rotations to the joints at certain points of time, to not just make the spider walk, but to eventually be able to use Neural Networks to allow it to experiment with various configurations of leg positions and figure out which ones can make it walk:
angle1 = 30
angle2 = 10
redJoint1.rotate(angle1)
pinkJoint2.rotate(angle2)
if angle1 < 50:
angle1 = angle1 + 1
Is it possible at all to achieve such a level of control over joints using Pymunk? To be able to stop moving the legs (without needing to put the body to sleep), or to rotate the leg joints to whatever angle the spider 'wishes to' at any point in time?
Sample code would be a great help.
From the servo example I took a hint and implemented this basic leg:
import sys
import pygame
from pygame.locals import USEREVENT, QUIT, KEYDOWN, KEYUP, K_s, K_r, K_q, K_ESCAPE, K_UP, K_DOWN, K_RIGHT, K_LEFT
from pygame.color import THECOLORS
import pymunk
from pymunk import Vec2d
import pymunk.pygame_util
class Simulator(object):
def __init__(self):
self.display_flags = 0
self.display_size = (600, 600)
self.space = pymunk.Space()
self.space.gravity = (0.0, -1900.0)
#self.space.damping = 0.999 # to prevent it from blowing up.
# Pymunk physics coordinates start from the lower right-hand corner of the screen.
self.ground_y = 100
ground = pymunk.Segment(self.space.static_body, (5, self.ground_y), (595, self.ground_y), 1.0)
ground.friction = 1.0
self.space.add(ground)
self.screen = None
self.draw_options = None
def reset_bodies(self):
for body in self.space.bodies:
if not hasattr(body, 'start_position'):
continue
body.position = Vec2d(body.start_position)
body.force = 0, 0
body.torque = 0
body.velocity = 0, 0
body.angular_velocity = 0
body.angle = body.start_angle
def draw(self):
self.screen.fill(THECOLORS["white"])### Clear the screen
self.space.debug_draw(self.draw_options)### Draw space
pygame.display.flip()### All done, lets flip the display
def main(self):
pygame.init()
self.screen = pygame.display.set_mode(self.display_size, self.display_flags)
width, height = self.screen.get_size()
self.draw_options = pymunk.pygame_util.DrawOptions(self.screen)
def to_pygame(p):
return int(p.x), int(-p.y+height) #Small hack to convert pymunk to pygame coordinates
def from_pygame(p):
return to_pygame(p)
clock = pygame.time.Clock()
running = True
font = pygame.font.Font(None, 16)
# Create the spider
chassisXY = Vec2d(self.display_size[0]/2, self.ground_y+100)
chWd = 70; chHt = 50
chassisMass = 10
legWd_a = 50; legHt_a = 5
legWd_b = 100; legHt_b = 5
legMass = 1
relativeAnguVel = 0
#---chassis
chassis_b = pymunk.Body(chassisMass, pymunk.moment_for_box(chassisMass, (chWd, chHt)))
chassis_b.position = chassisXY
chassis_shape = pymunk.Poly.create_box(chassis_b, (chWd, chHt))
chassis_shape.color = 200, 200, 200, 100
print("chassis position");print(chassis_b.position)
#---first left leg a
leftLeg_1a_body = pymunk.Body(legMass, pymunk.moment_for_box(legMass, (legWd_a, legHt_a)))
leftLeg_1a_body.position = chassisXY - ((chWd/2)+(legWd_a/2), 0)
leftLeg_1a_shape = pymunk.Poly.create_box(leftLeg_1a_body, (legWd_a, legHt_a))
leftLeg_1a_shape.color = 255, 0, 0, 100
#---first left leg b
leftLeg_1b_body = pymunk.Body(legMass, pymunk.moment_for_box(legMass, (legWd_b, legHt_b)))
leftLeg_1b_body.position = leftLeg_1a_body.position - ((legWd_a/2)+(legWd_b/2), 0)
leftLeg_1b_shape = pymunk.Poly.create_box(leftLeg_1b_body, (legWd_b, legHt_b))
leftLeg_1b_shape.color = 0, 255, 0, 100
#---first right leg a
rightLeg_1a_body = pymunk.Body(legMass, pymunk.moment_for_box(legMass, (legWd_a, legHt_a)))
rightLeg_1a_body.position = chassisXY + ((chWd/2)+(legWd_a/2), 0)
rightLeg_1a_shape = pymunk.Poly.create_box(rightLeg_1a_body, (legWd_a, legHt_a))
rightLeg_1a_shape.color = 255, 0, 0, 100
#---first right leg b
rightLeg_1b_body = pymunk.Body(legMass, pymunk.moment_for_box(legMass, (legWd_b, legHt_b)))
rightLeg_1b_body.position = rightLeg_1a_body.position + ((legWd_a/2)+(legWd_b/2), 0)
rightLeg_1b_shape = pymunk.Poly.create_box(rightLeg_1b_body, (legWd_b, legHt_b))
rightLeg_1b_shape.color = 0, 255, 0, 100
#---link left leg b with left leg a
pj_ba1left = pymunk.PinJoint(leftLeg_1b_body, leftLeg_1a_body, (legWd_b/2,0), (-legWd_a/2,0))#anchor point coordinates are wrt the body; not the space
motor_ba1Left = pymunk.SimpleMotor(leftLeg_1b_body, leftLeg_1a_body, relativeAnguVel)
#---link left leg a with chassis
pj_ac1left = pymunk.PinJoint(leftLeg_1a_body, chassis_b, (legWd_a/2,0), (-chWd/2, 0))
motor_ac1Left = pymunk.SimpleMotor(leftLeg_1a_body, chassis_b, relativeAnguVel)
#---link right leg b with right leg a
pj_ba1Right = pymunk.PinJoint(rightLeg_1b_body, rightLeg_1a_body, (-legWd_b/2,0), (legWd_a/2,0))#anchor point coordinates are wrt the body; not the space
motor_ba1Right = pymunk.SimpleMotor(rightLeg_1b_body, rightLeg_1a_body, relativeAnguVel)
#---link right leg a with chassis
pj_ac1Right = pymunk.PinJoint(rightLeg_1a_body, chassis_b, (-legWd_a/2,0), (chWd/2, 0))
motor_ac1Right = pymunk.SimpleMotor(rightLeg_1a_body, chassis_b, relativeAnguVel)
self.space.add(chassis_b, chassis_shape)
self.space.add(leftLeg_1a_body, leftLeg_1a_shape, rightLeg_1a_body, rightLeg_1a_shape)
self.space.add(leftLeg_1b_body, leftLeg_1b_shape, rightLeg_1b_body, rightLeg_1b_shape)
self.space.add(pj_ba1left, motor_ba1Left, pj_ac1left, motor_ac1Left)
self.space.add(pj_ba1Right, motor_ba1Right, pj_ac1Right, motor_ac1Right)
#---prevent collisions with ShapeFilter
shape_filter = pymunk.ShapeFilter(group=1)
chassis_shape.filter = shape_filter
leftLeg_1a_shape.filter = shape_filter
rightLeg_1a_shape.filter = shape_filter
leftLeg_1b_shape.filter = shape_filter
rightLeg_1b_shape.filter = shape_filter
simulate = False
rotationRate = 2
while running:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key in (K_q, K_ESCAPE)):
#running = False
sys.exit(0)
elif event.type == KEYDOWN and event.key == K_s:
# Start/stop simulation.
simulate = not simulate
elif event.type == KEYDOWN and event.key == K_r:
# Reset.
# simulate = False
self.reset_bodies()
elif event.type == KEYDOWN and event.key == K_UP:
motor_ba1Left.rate = rotationRate
elif event.type == KEYDOWN and event.key == K_DOWN:
motor_ba1Left.rate = -rotationRate
elif event.type == KEYDOWN and event.key == K_LEFT:
motor_ac1Left.rate = rotationRate
elif event.type == KEYDOWN and event.key == K_RIGHT:
motor_ac1Left.rate = -rotationRate
elif event.type == KEYUP:
motor_ba1Left.rate = 0
motor_ac1Left.rate = 0
self.draw()
### Update physics
fps = 50
iterations = 25
dt = 1.0/float(fps)/float(iterations)
if simulate:
for x in range(iterations): # 10 iterations to get a more stable simulation
self.space.step(dt)
pygame.display.flip()
clock.tick(fps)
if __name__ == '__main__':
sim = Simulator()
sim.main()
It can be controlled with the up, left, right and down arrow keys after first pressing the s key to start the simulation. I've also made sure the variables are created properly linked with each other and named well.
The part about making the joints move to a desired angle is yet to be implemented, but perhaps that could be calculated by taking the x,y positions of the ends of the joints and using a formula to calculate the angle and then move the motor until it reaches a desired angle.
If there's a better way, do let me know by posting an answer or editing this one.
I am trying to find the distance from the start node named seeker to the goal node named target. I have already done most of the implementation of the algorithm and each of the nodes have a coordinate or box on a grid. My python code is lacking and I cannot find the coordinates and distance.
I have tried using the vector in the math class which gave me logical errors.
I also tried sending the actual objects hoping I could use those to reference the coordinates as I'd done in the code but got a TypeError: expected sequence object with len >= 0 or a single integer.
import numpy as np
import pygame as pg
import sys
from Settings import *
from Sprites import *
vec = pg.math.Vector2
class Game:
# initialise game window, etc
def __init__(self):
self.playing = True
pg.init()
self.mover = 'target'
self.screen = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption(Title)
self.clock = pg.time.Clock()
pg.key.set_repeat(500, 100)
self.load_data()
# pg.mouse.set_pos(0, 0)
self.walls = []
def load_data(self):
pass
# start a new game
def new(self):
self.all_sprites = pg.sprite.Group()
self.player = Player(self, 10, 10)
self.target = Target(self, 5, 5)
def load_data(self):
pass
# game loop
def run(self):
while self.playing:
self.dt = self.clock.tick(FPS) / 10000
self.events()
self.update()
self.draw()
def draw_grid(self):
for x in range(0, WIDTH, TILESIZE):
pg.draw.line(self.screen, LIGHTGREY, (x, 0), (x, HEIGHT))
for y in range(0, HEIGHT, TILESIZE):
pg.draw.line(self.screen, LIGHTGREY, (0, y), (WIDTH, y))
def quit(self):
pg.quit()
sys.exit()
def update(self):
# game loop update
self.all_sprites.update()
def events(self):
# game loop events
for event in pg.event.get():
if event.type == pg.QUIT:
self.quit()
if event.type == pg.MOUSEBUTTONDOWN:
mpos = vec(pg.mouse.get_pos()) // TILESIZE
if event.button == 1:
if mpos in g.walls:
g.walls.remove(mpos)
else:
g.walls.append(mpos)
if event.type == pg.KEYDOWN:
if event.key == pg.K_b:
# start breadth first
breadthfirst(self.target, self.player, self.walls, self.screen)
if event.key == pg.K_d:
# start depth first
depthfirst(self.target, self.player, self.walls, self.screen)
if event.key == pg.K_a:
# start A* search
astarsearch(self.target, self.player, self.walls, self.screen)
if event.key == pg.K_ESCAPE:
self.quit()
if event.key == pg.K_t:
self.mover = 'target'
if event.key == pg.K_s:
self.mover = 'seeker'
if self.mover == 'target':
if event.key == pg.K_LEFT:
self.target.move(dx=-1)
if event.key == pg.K_RIGHT:
self.target.move(dx=1)
if event.key == pg.K_UP:
self.target.move(dy=-1)
if event.key == pg.K_DOWN:
self.target.move(dy=1)
else:
if event.key == pg.K_LEFT:
self.player.move(dx=-1)
if event.key == pg.K_RIGHT:
self.player.move(dx=1)
if event.key == pg.K_UP:
self.player.move(dy=-1)
if event.key == pg.K_DOWN:
self.player.move(dy=1)
def draw(self):
# game loop - draw
self.screen.fill(BGCOLOR)
self.draw_grid()
self.all_sprites.draw(self.screen)
for wall in self.walls:
rect = pg.Rect(wall * TILESIZE, (TILESIZE, TILESIZE))
pg.draw.rect(self.screen, GREEN, rect)
# always do the flip after drawing everything
pg.display.flip()
def show_start_screen(self):
# game splash/start screen
pass
def show_go_screen(self):
# game over/continue screen
pass
def breadthfirst(target, seeker, walls, maingrid):
pass
def depthfirst(target, seeker, wall, maingrid):
pass
def astarsearch(target, seeker, wall, maingrid):
# array to store path locations
direct_graph = {}
# target location, returns a tuple
target = np.where(target.pos) # problem area
# seeker location, returns locations
start = np.where(seeker.pos) # problem area
# array of cost to travel so far
g_cost_array = np.zeros(seeker) # problem area
g_cost_array[start] = 0
total_g_cost = 0
# array for heuristic cost
h_cost_array = np.zeros(seeker) # problem area
# need to use a loop unfortunately...
t = 0
# possible steps
steps = ((-1, 0), (+1, 0), (0, -1), (0, +1))
for rows in h_cost_array:
s = 0
for cols in rows:
# check if it's a wall! if not - get the distance to target
loc = (t, s)
if (maingrid[loc]):
pass
else:
dist = abs(target[0] - s) + abs(target[1] - t)
h_cost_array[t, s] = dist
s += 1
t += 1
# total cost = h + g
f_cost_array = g_cost_array + h_cost_array
# closed and open sets
open_set = []
open_set.append(start)
closed_set = []
# actual path
path = []
path.append([tuple(target[0]), tuple(target[1])])
solution_found = False
while (open_set):
open_f_cost = []
# get the heuristic cost for the candidates in the open set
for vals in open_set:
open_f_cost.append(f_cost_array[vals])
# the shortest heuristic now
# the index of the candidate with the lowest distance/heuristic
best_dist_now = open_f_cost.index(min(open_f_cost))
# the current best position
best_pos_now = open_set[best_dist_now]
# if the destination is reached, finish!
if (tuple(best_pos_now) == target):
solution_found = True
break
else:
# remove the best guy from the open_set and add it to the closed set
closed_set.append(open_set.pop(best_dist_now))
# analyze the steps from the current best
for step in steps:
cand = (best_pos_now[0] + step[0], best_pos_now[1] + step[1])
# check if there's a wall or beyond the screen
if cand[0] < 0 or cand[1] < 0 or cand[0] > 39 or cand[1] > 23:
pass
# skip this candidate because it's a wall!
elif maingrid[cand]:
pass
# need an else clause here to weed out the off-screen locations
else:
# check if the candidate is in the closed set
already_seen = False
for dead in closed_set:
if np.all(dead == cand):
already_seen = True
break
# if the cell is in the closed set, skip it
if already_seen:
pass
else:
approx_g_score = g_cost_array[best_pos_now] + 1
# check if it's in the open list:
new = True
for others in open_set:
if np.all(others == cand):
new = False
break
# if a new cell or improved
if (new or approx_g_score < g_cost_array[cand]):
direct_graph[tuple(cand[0]), tuple(cand[1])] = (
tuple(best_pos_now[0]), tuple(best_pos_now[1]))
g_cost_array[cand] = approx_g_score
f_cost_array[cand] = g_cost_array[cand] + h_cost_array[cand]
if new:
open_set.append(cand)
if not solution_found:
return None
else:
recurrentPath(path, direct_graph, target, start)
return path
# takes a dictionary as input
def recurrentPath(final_path, raw_path, dest, origin):
a = raw_path[tuple(dest[0]), tuple(dest[1])]
final_path.append(a)
if (a != origin):
recurrentPath(final_path, raw_path, a, origin)
else:
return final_path
g = Game()
g.show_start_screen()
while True:
g.new()
g.run()
g.show_go_screen()
pg.QUIT
the expected results is to return the correct path to the target object from the seeker object after you press the keyboard character a. Note that with a left click, a wall can be constructed to add a hindrance to the seeking of the goal.
First, sorry for my poor English.
I'm writing a game with Python 3.4 and Pygame. Game includes scenes what provide view of screen, and music, etc, parsed from XML scripts.
I expect music plays instantly, but not plays at next scene.
and cannot find similar problem on web.
how can I rewrite code to play music scene-instantly?
I wrote code like it:
(graphic part removed)
xml file is here : https://pastebin.com/bSBiv1jX
import pygame
import xml.etree.ElementTree as ET
class Script():
def __init__(self, name, filename):
self.name = name
self.parsed = ET.parse(filename)
self.root = self.parsed.getroot()
self.scene_list = self.root.findall("scene")
self.flag_list = str(self.root.findtext("flags")).split(",")
for flag in self.flag_list:
setattr(self, flag, False)
def music_play(self, number):
scene = self.scene_list[number]
if scene.findtext("music") == 'stop':
pygame.mixer.music.stop()
elif scene.findtext("music") != '':
pygame.mixer.music.load(scene.findtext("music"))
pygame.mixer.music.play(-1, 0.0)
def goto(self, number):
string = self.scene_list[number].findtext("goto")
if string == '':
return number
elif isNumber(string) == True:
return int(string)
elif isNumber(string) == False:
return string
def if_goto(self, string, number):
iflist = string.split(', ')
if getattr(self, iflist[0]) == True
return int(iflist[1])
else:
return number + 1
def isNumber(s):
try:
float(s)
return True
except ValueError:
return False
def runGame():
pygame.init()
windowSurface = pygame.display.set_mode((200, 200))
clock = pygame.time.Clock()
run = True
scene_number = 0
script = Script('dummy', 'scenario/dummy.xml')
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_SPACE:
if scene_number == script.goto(scene_number):
scene_number += 1
elif scene_number != script.goto(scene_number):
if isNumber(script.goto(scene_number)):
scene_number = script.goto(scene_number)
else:
scene_number = script.if_goto(script.goto(scene_number), scene_number)
script.music_play(scene_number)
pygame.display.update()
clock.tick(30)
pygame.quit()
def main():
runGame()
if __name__ == "__main__":
main()
https://www.pygame.org/docs/ref/music.html#pygame.mixer.music.load
If a music stream is already playing it will be stopped
https://www.pygame.org/docs/ref/music.html#pygame.mixer.music.play
If the music is already playing it will be restarted.
At every iteration of your game loop you call music_play and restart the music. You should only start the music if it's not already running.
You could, for instance, only call this when a scene changes.
I'm building a multiple choice quiz game in pygame however there is an issue with my while loop.
I successfully built the game in python without the GUI and all the logic works fine, however, when I try and add the GUI to the logic it doesn't work in the same way.
In my working logic game the continuous while loop is paused at every question due to me using the 'raw_input()' function and waits for the user to answer. When I do the GUI version my questions are read in successfully but it reads them all in at once and there is no time to answer.
I've tried adding time.sleep() after reading each question but this means that the program doesn't respond to event handlers. If the event handlers did work then this would be the perfect solution, giving users a certain amount of time to answer.
This example code below won't compile as I have left out many classes and methods but wanted to show this is where my issue lies. I read dictionary keys and values in and then try and match the user input with the index of the correct answer which is always answerMain[0] before getting shuffled.
Has anyone had a similar issue or know of a possible solution?
attemptMain = {'Q': 'Question Here', 'A': 'Answer1','B': 'Answer2','c': 'Answer3','D': 'Answer4', }
def normalQuestions(self, list):
for i in list:
questionMain = self.attemptMain.keys()[i - 1]
answersMain = (self.attemptMain.values()[i - 1])
correctAnswerMain = answersMain[0]
shuffle(answersMain)
answersMainIndex = (1 + answersMain.index(correctAnswerMain) )
self.layout.questionandAnswers(questionMain, answersMain[0], answersMain[1], answersMain[2], answersMain[3])
time.sleep(10)
x = self.layout.controls()
if (x == answersMainIndex):
print("this is the correct answer")
def controls(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
print("here" + str(1))
return '1'
elif event.key == pygame.K_2:
print("here" + str(2))
return '2'
elif event.key == pygame.K_3:
print("here" + str(3))
return '3'
elif event.key == pygame.K_4:
print("here" + str(4))
return '4'
Here's a quiz game example. I use the dt = clock.tick(fps) solution from the linked answer. You can just decrement a time variable by the dt and if it's below 0, switch to the next question. The user can input 1-4 which is then compared with the last element of the question tuple to check if the answer was correct.
import random
import pygame as pg
pg.init()
FONT = pg.font.Font(None, 34)
FONT_SMALL = pg.font.Font(None, 24)
BLUE = pg.Color('steelblue1')
def get_question(questions, question_index):
"""Create a surface with the question and the 4 answer choices."""
question, *answers, _ = questions[question_index]
# Blit the question and answers onto this transparent surface.
question_surface = pg.Surface((500, 150), pg.SRCALPHA)
question_surface.blit(FONT.render(str(question), True, BLUE), (0, 0))
for y, answer in enumerate(answers, 1):
txt = FONT_SMALL.render('{}: {}'.format(y, answer), True, BLUE)
question_surface.blit(txt, (0, 20*y+20))
return question_surface
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
dt = 0
time_to_answer = 5 # User has 5 seconds to answer.
time = time_to_answer
# A list of tuples that contain the question, 4 multiple choice
# answers and the last element is the correct answer.
questions = [
('Is it A, B, C or D?', 'A', 'B', 'C', 'D', '3'),
("What's 2+3?", '23', '5', '3', '2', '2'),
]
random.shuffle(questions)
question_index = 0
question_surface = get_question(questions, question_index)
correct = 0
incorrect = 0
game_over = False
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.KEYDOWN:
if not game_over:
user_input = event.unicode
correct_answer = questions[question_index][-1]
if user_input == correct_answer:
print('Correct')
correct += 1
time = time_to_answer
else:
incorrect += 1
time = time_to_answer
question_index += 1
if question_index >= len(questions):
game_over = True
else:
question_surface = get_question(questions, question_index)
else: # Restart.
game_over = False
correct = 0
incorrect = 0
random.shuffle(questions)
question_index = 0
question_surface = get_question(questions, question_index)
if not game_over:
time -= dt
# If the timer is below 0, switch to the next question.
if time <= 0:
question_index += 1
incorrect += 1
if question_index >= len(questions):
game_over = True
else:
time = time_to_answer
print('next')
question_surface = get_question(questions, question_index)
screen.fill((30, 30, 30))
if not game_over:
screen.blit(question_surface, (20, 50))
time_surface = FONT.render(str(round(time, 1)), True, BLUE)
screen.blit(time_surface, (20, 20))
correct_answer_surface = FONT_SMALL.render(
'Correct {}, incorrect {}'.format(correct, incorrect),
True, BLUE)
screen.blit(correct_answer_surface, (20, 250))
pg.display.flip()
dt = clock.tick(30) / 1000
if __name__ == '__main__':
main()
pg.quit()
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()):