Hi im new to python and am trying to make a simple tank game where I want the tank gun to follow the position of the mouse cursor. Im am having some trouble in doing this. Below is my code. Whenever I run I get an error. So far I want the idle screen to print out the position of the mouse and display the co-ordinates. I can get the mouse button down function to work but not the mouse position. Any ideas please. Again I am new to Python.

def mouse_position():

    running = True
    while running:

        for event in pygame.event.get():
            #if event.type == pygame.MOUSEBUTTONDOWN:
                #mosdown = pygame.mouse.get_pos()
                #print(mosdown)

            if event in pygame.event.get_rel():
                mospos = pygame.mouse.get_rel()
                print(mospos)

Recommended Answers

All 2 Replies

Here is an example ...

''' pg_mouseposition1.py
show mouse position with module pygame

to see a list of event constants use:
import pygame.constants
help(pygame.constants)
'''

import pygame as pg

# create a 640x400 window/screen
screen = pg.display.set_mode((640, 400))
screen.fill((255, 0, 0))  # red

running = True
while running:
    event = pg.event.poll()
    # quit when window corner x is clicked
    if event.type == pg.QUIT:
        running = False
    elif event.type == pg.MOUSEMOTION:
        mouse_pos = "mouse at (%d, %d)" % event.pos
        pg.display.set_caption(mouse_pos)
    elif event.type == pg.MOUSEBUTTONDOWN:
        mouse_pos = "mouse click at (%d, %d)" % event.pos
        pg.display.set_caption(mouse_pos)

    # update display
    pg.display.flip()

Thank you

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.